{"text": "# Experiment 5: Air Track III---Conservation of Energy\n### Objectives\n- To learn to take good measurements\n- To learn how to estimate and propagate errors\n- To learn how to take measurements to verify a theory\n- To learn how to measure potential and kinetic energies\n\n### Equipment\n- One Airtrack, Blower, and Cart\n- One accessory kit containing: one pulley, one mass hanger, and masses for cart and hanger.\n- One string (150 cm long)\n- One photogate\n- One 30 cm ruler\n- One scale\n- One vernier caliper\n- One two-meter stick\n- One 3” x 5/32” rod\n- One 6” x 5/32” rod\n- One 6 mm x 44 mm spring\n- One flat washer\n- One 2x4\n- One 1x4\n- One set of slotted weights: (Eight 100g and four 50g)\n\n### Safety\n- **Be careful placing the carts on the track. Do not damage the track.**\n- Please place paper underneath the carts when they are resting on the track without the air turned on. **Do not slide the carts on the track without the air turned on.**\n- **Do not launch the cart unless a rubber-band bumper is secured to the opposite end of the track.**\n\n# Introduction\nThere are two kinds of energy in mechanical systems: Potential energy and Kinetic energy. *Potential* energy is stored energy. When this energy is released, it can be converted into *kinetic* energy---energy of motion. In this lab you will conduct two experiments to determine if all of the potential energy stored in a system can be converted into kinetic energy.\n\nIn the first experiment, you will convert gravitational potential energy to kinetic energy (using the hanging mass and pulley). In the second, you will convert spring potential energy to kinetic energy.\n\n# Theory\n### Kinematics\nFirst and foremost, you will need to compute the velocity of the aitrack glider. The information you will have, however, is velocity computed by a photogate. The photogate measures the\nvelocity of the glider as it passes through by timing how long the infrared LED is blocked by the object (sometimes called a “flag”) passing through and uses the definition of velocity: \n\\begin{equation}\nv \\equiv \\frac{\\Delta x}{\\Delta t}\n\\tag{1}\n\\end{equation}\n\nwhere $\\Delta x$ is the length of the flag and $\\Delta t$ is the time the LED was blocked.\n\n### Gravitational Potential Energy\nRecall that the amount of energy stored in an object in a gravitational field is \n\n\\begin{equation}\nU_{g} = m g \\Delta y\n\\tag{2}\n\\end{equation} \n\nwhere *m* is the mass of the object, *g* is the gravitational constant, and $ \\Delta y$ is the change in height of that object.\n\n### Spring Potential Energy\nThe amount of energy stored in a compressed spring is \n\n\\begin{equation}\nU_{s} = \\frac{1}{2} k (\\Delta x)^2\n\\tag{3}\n\\end{equation} \n\nwhere *k* is the spring constant. You will need to measure this spring constant for your spring. You can find this constant by recalling Hooke’s Law: \n\n\\begin{equation}\nF = -k \\Delta x\n\\tag{4}\n\\end{equation} \n\nThe force you apply to the spring is directly related to the compression, $ \\Delta x$, of that spring (the negative sign is a reminder that the force is opposes the spring compression). By plotting the force vs. compression for different weights, you can plot a straight line. The slope of that straight line will be the spring constant (if you have plotted the correct variable on the correct axis---recall the definition of the slope of a straight line and you’ll figure it out).\n\n### Kinetic Energy\nKinetic energy is the energy of motion. For objects moving much slower than the speed of light, we can use the formula: \n\n\\begin{equation}\nK = \\frac{1}{2} m v^2\n\\tag{5}\n\\end{equation} \n\nwhere *m* is the mass of all the objects moving at speed v.\n\n### Uncertainty Analysis\nYour Lab Manual and the previous labs can guide you in estimating the uncertainties in your measurements and propagating those uncertainties into your computed energies. The uncertainty in the masses of the glider and hanging mass will be determined by the accuracy of the scale. In some cases, it might be easier to use the standard deviation of a large number of measurements as your velocity measurement uncertainty. The uncertainty in your spring constant and kinetic and potential energies, however, will have to be computed using the three equations in your Lab Manual.\n\nIn order to minimize random errors, it is extremely important that each of your measurements be performed several times.\n\n# Experimental Procedure\n\n### Setting up the Air Track\nEnsure that the pulley is securely inserted into the top hole in the bracket at the far end of the track, that it spins freely, and that the hanging mass does not strike the table as it falls. You will need to level the airtrack for two of the experiments. Look back to the second lab for instructions if you’ve forgotten how to do this.\n\n### Setting up a Photogate\n1. Turn on the PASCO 850 Interface and start the PASCO Capstone software.\n2. Plug a photogate into a Digital input.\n3. Click the “Hardware Setup” tab in the left “Tools” palette, left-click the jack on the diagram where you inserted the plug, and select “Photogate” from the drop-down menu.\n4. You should see a tab labeled “Timer Setup.” Open that tab and set up a pre-configured timer:\n 1. Select the photogate you just installed.\n 2. You will be using this photogate with a single flag.\n 3. The computer need only keep track of the speed through the gate.\n 4. A text box requesting the length of the flag in meters will appear. Measure the flag as best you can and enter that information in the box.\n 5. Give this sensor a name such as “Photogate 1” or similar.\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom P201_Functions import *\n\n# Flag length measurement (m) and its uncertainty\nflag_len = 0.1\ndelta_x = 0.005\n```\n\nWhen you adjust the height of the photogate, make sure that it is triggered only by the flag. The string should not trigger the photogate. You can tell when the photogate is triggered by looking for the red LED to light when the infrared LED is blocked. Ensure that the red LED only lights when the proper portion of the cart passes through.\n\nWhen choosing the positions for your photogate, think carefully about whether you want the cart to be coasting through the gate or experiencing a force as it travels through the gate. Also keep in mind that the airtrack only *reduces* friction, it does not eliminate it.\n\n### Measuring the Spring Constant\nIt will be easiest to measure the compression of the spring while it is on a long rod. This will keep the spring from bending while weights are applied to the spring. Place one end of the rod on the table, then place the spring on the rod, and then place a washer on top of the spring. You should then be able to measure the compression of the spring as a function of the masses you apply. A series of ten 100 g weights should give you a good graph. (It might be instructive to start with ten 10 g weights before applying the remaining nine 100g weights to see if the spring constant is truly linear.)\n\n
\n\n
\n\n**Don’t forget to include the mass of the washer and do not exceed 1.1 kg of mass on the spring!**\n\n(Ask your instructor how to remove and use one of the end-brackets of the air-track to support the bottom portion of the rod if that would help make your compression measurements easier).\n\nYou must use PASCO Capstone to create the graph of \"Weight vs. Compression\": \n1. Start the Capstone program and click “Table & Graph” in the main window.\n2. In the first table column, click `` button on each axis and select the data you would like on that axis.\n\n**For reasons you will soon discover, plot the *compression* on the x-axis.** You will need to print\nthe graphs you produce for each team member. **Be sure to properly label your graphs!**\n\n\n```python\n# Weight vs. Compression Graph\n\n# Reads the name of the csv file and gets the data\ndf = pd.read_csv(\"./ExampleFiles/Spring Constant.csv\")\n\n# Prints information about the file\n#df.info()\nprint(df)\nprint()\n\n\n# Defines the x and y values\nweight = df.filter(['Weight (N)'], axis=1).dropna()\ncompr = df.filter(['Compression (m)'], axis=1).dropna()\n\n# Create a figure of reasonable size and resolution, white background, black edge color\nfig=plt.figure(figsize=(7,5), dpi= 100, facecolor='w', edgecolor='k')\n\n# Gets the data values for x and y\nx_data = compr.values.reshape(-1, 1)\ny_data = weight.values.reshape(-1, 1)\n\nxi = df['Compression (m)'].to_numpy()\nyi = df['Weight (N)'].to_numpy()\n\n# Creates the base plot with titles\nplt.plot(x_data,y_data,'b.',label='Raw Data')\nplt.ylabel('Weight (N)')\nplt.xlabel('Measured Compression (m)')\nplt.title('Weight vs. Compression')\n\n# Takes the x and y values to make a trendline\n#intercept, slope = linear_fit_plot(x_data,y_data)\nintercept, slope, dintercept, dslope = linear_fit_plot_errors(xi,yi,0.006,0.024)\n\n# Adds the legend to the plot\nplt.legend()\n\n# Displays the plot\nplt.show()\n\nprint()\n```\n\n## Experiment 1: Gravitational Potential Energy vs. Kinetic Energy\nFor this experiment, repeat the set up from the last lab. You will be comparing the initial potential energy of the mass hanger to **the sum of** the final kinetic energies of both the cart and the mass hanger (the instant before it strikes the ground). Do four trials (for statistics) for four different combinations of masses (the hanger mass must change each time).\n\nWhere should the photogate be placed for this experiment?\n\n\n```python\n# Experiment 1 Raw Data\n# Cart 1\n\n# Create an empty numpy array to hold the raw data\nraw_data_1 = np.empty((4,2))\n\n# Set the trial number column identifiers for each Trial\nraw_data_1[0][0]=1\nraw_data_1[1][0]=2\nraw_data_1[2][0]=3\nraw_data_1[3][0]=4\n\n# Create a Pandas dataframe, and convert the Trial number column to integer format\ndf1 = pd.DataFrame(raw_data_1, columns=[\"Trial\", \n \"Measured v_f (m/s)\"])\n\ndf1['Trial'] = df1['Trial'].astype(int)\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Mass of the cart (kg) and its uncertainty\nm_cart = 0.18995\ndelta_m_cart = 5e-06\n\n# Mass of hanging mass (kg) and its uncertainty\nm_hang = 0.01175\ndelta_m_hang = 5e-06\n\n# Height of the spring (m) and its uncertainty\nh = 0.952\ndelta_h = 0.0005\n\n# Predicted Final Velocity (m/s) and its uncertainty\nv_p = 1.028\ndelta_v_p = 0.0007081\n\n# Enter the measured values of v_f (m/s)\ndf1['Measured v_f (m/s)'] = [0.98,0.98,0.97,0.99]\n\n###########################################\n\n\n# calculates the mass of the cart with the mass of the hanger and its uncertainty\nm_total = m_cart + m_hang\ndelta_m_total = np.sqrt(2) * delta_m_cart\n\n# Calculates the uncertainty of the velocity using standard deviation\nuncertainty_v = np.std(df1['Measured v_f (m/s)'])\n\n# prints out the cart data\nprint(\"Data for: \")\nprint(\"m_cart = %0.5f kg 𝛿m_cart = %g\" % (m_cart, delta_m_cart))\nprint(\"m_hang = %0.5f kg 𝛿m_hang = %g\" % (m_hang,delta_m_hang))\nprint(\"h = %0.3f m 𝛿h = %0.4f\" % (h,delta_h))\nprint(\"Predicted v_f = %0.5f m/s 𝛿v_p_f = %0.4f\" % (v_p,delta_v_p))\nprint(\"\")\n\n# Display the dataframe\nfrom IPython.display import display\nprint (\"Cart 1\")\ndisplay(df1)\n# Print statements for uncertainty of final velocity\nprint(\"𝛿v = %0.5f m/s\" % (uncertainty_v))\n```\n\n Data for: \n m_cart = 0.18995 kg 𝛿m_cart = 5e-06\n m_hang = 0.01175 kg 𝛿m_hang = 5e-06\n h = 0.952 m 𝛿h = 0.0005\n Predicted v_f = 1.02800 m/s 𝛿v_p_f = 0.0007\n \n Cart 1\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TrialMeasured v_f (m/s)
010.98
120.98
230.97
340.99
\n
\n\n\n 𝛿v = 0.00707 m/s\n\n\n***\n\n\n```python\n# Experiment 1 Raw Data\n# Cart 2\n\n# Create an empty numpy array to hold the raw data\nraw_data_2 = np.empty((4,2))\n\n# Set the trial number column identifiers for each Trial\nraw_data_2[0][0]=1\nraw_data_2[1][0]=2\nraw_data_2[2][0]=3\nraw_data_2[3][0]=4\n\n# Create a Pandas dataframe, and convert the Trial number column to integer format\ndf2 = pd.DataFrame(raw_data_2, columns=[\"Trial\", \n \"Measured v_f (m/s)\"])\n\ndf2['Trial'] = df2['Trial'].astype(int)\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Mass of the cart (kg) and its uncertainty\nm_cart = 0.18995\ndelta_m_cart = 5e-06\n\n# Mass of hanging mass (kg) and its uncertainty\nm_hang = 0.01665\ndelta_m_hang = 5e-06\n\n# Height of the spring (m) and its uncertainty\nh = 0.952\ndelta_h = 0.0005\n\n# Predicted Final Velocity (m/s) and its uncertainty\nv_p = 1.209\ndelta_v_p = 0.0007081\n\n# Enter the measured values of v_f (m/s)\ndf2['Measured v_f (m/s)'] = [1.17,1.18,1.17,1.16]\n\n###########################################\n\n\n# calculates the mass of the cart with the mass of the hanger and its uncertainty\nm_total = m_cart + m_hang\ndelta_m_total = np.sqrt(2) * delta_m_cart\n\n# Calculates the uncertainty of the velocity using standard deviation\nuncertainty_v = np.std(df2['Measured v_f (m/s)'])\n\n# prints out the cart data\nprint(\"Data for: \")\nprint(\"m_cart = %0.5f kg 𝛿m_cart = %g\" % (m_cart, delta_m_cart))\nprint(\"m_hang = %0.5f kg 𝛿m_hang = %g\" % (m_hang,delta_m_hang))\nprint(\"h = %0.3f m 𝛿h = %0.4f\" % (h,delta_h))\nprint(\"Predicted v_f = %0.5f m/s 𝛿v_p_f = %0.4f\" % (v_p,delta_v_p))\nprint(\"\")\n\n# Display the dataframe\nfrom IPython.display import display\nprint (\"Cart 2\")\ndisplay(df2)\n# Print statements for uncertainty of final velocity\nprint(\"𝛿v = %0.5f m/s\" % (uncertainty_v))\n```\n\n Data for: \n m_cart = 0.18995 kg 𝛿m_cart = 5e-06\n m_hang = 0.01665 kg 𝛿m_hang = 5e-06\n h = 0.952 m 𝛿h = 0.0005\n Predicted v_f = 1.20900 m/s 𝛿v_p_f = 0.0007\n \n Cart 2\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TrialMeasured v_f (m/s)
011.17
121.18
231.17
341.16
\n
\n\n\n 𝛿v = 0.00707 m/s\n\n\n***\n\n\n```python\n# Experiment 1 Raw Data\n# Cart 3\n\n# Create an empty numpy array to hold the raw data\nraw_data_3 = np.empty((4,2))\n\n# Set the trial number column identifiers for each Trial\nraw_data_3[0][0]=1\nraw_data_3[1][0]=2\nraw_data_3[2][0]=3\nraw_data_3[3][0]=4\n\n# Create a Pandas dataframe, and convert the Trial number column to integer format\ndf3 = pd.DataFrame(raw_data_3, columns=[\"Trial\", \n \"Measured v_f (m/s)\"])\n\ndf3['Trial'] = df3['Trial'].astype(int)\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Mass of the cart (kg) and its uncertainty\nm_cart = 0.18995\ndelta_m_cart = 5e-06\n\n# Mass of hanging mass (kg) and its uncertainty\nm_hang = 0.00965\ndelta_m_hang = 5e-06\n\n# Height of the spring (m) and its uncertainty\nh = 0.820\ndelta_h = 0.0005\n\n# Predicted Final Velocity (m/s) and its uncertainty\nv_p = 0.9367\ndelta_v_p = 0.0007081\n\n# Enter the measured values of v_f (m/s)\ndf3['Measured v_f (m/s)'] = [0.83,0.85,0.82,0.83]\n\n###########################################\n\n\n# calculates the mass of the cart with the mass of the hanger and its uncertainty\nm_total = m_cart + m_hang\ndelta_m_total = np.sqrt(2) * delta_m_cart\n\n# Calculates the uncertainty of the velocity using standard deviation\nuncertainty_v = np.std(df3['Measured v_f (m/s)'])\n\n# prints out the cart data\nprint(\"Data for: \")\nprint(\"m_cart = %0.5f kg 𝛿m_cart = %g\" % (m_cart, delta_m_cart))\nprint(\"m_hang = %0.5f kg 𝛿m_hang = %g\" % (m_hang,delta_m_hang))\nprint(\"h = %0.3f m 𝛿h = %0.4f\" % (h,delta_h))\nprint(\"Predicted v_f = %0.5f m/s 𝛿v_p_f = %0.4f\" % (v_p,delta_v_p))\nprint(\"\")\n\n# Display the dataframe\nfrom IPython.display import display\nprint (\"Cart 3\")\ndisplay(df3)\n# Print statements for uncertainty of final velocity\nprint(\"𝛿v = %0.5f m/s\" % (uncertainty_v))\n```\n\n Data for: \n m_cart = 0.18995 kg 𝛿m_cart = 5e-06\n m_hang = 0.00965 kg 𝛿m_hang = 5e-06\n h = 0.820 m 𝛿h = 0.0005\n Predicted v_f = 0.93670 m/s 𝛿v_p_f = 0.0007\n \n Cart 3\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TrialMeasured v_f (m/s)
010.83
120.85
230.82
340.83
\n
\n\n\n 𝛿v = 0.01090 m/s\n\n\n***\n\n\n```python\n# Experiment 1 Raw Data\n# Cart 4\n\n# Create an empty numpy array to hold the raw data\nraw_data_4 = np.empty((4,2))\n\n# Set the trial number column identifiers for each Trial\nraw_data_4[0][0]=1\nraw_data_4[1][0]=2\nraw_data_4[2][0]=3\nraw_data_4[3][0]=4\n\n# Create a Pandas dataframe, and convert the Trial number column to integer format\ndf4 = pd.DataFrame(raw_data_4, columns=[\"Trial\", \n \"Measured v_f (m/s)\"])\n\ndf4['Trial'] = df4['Trial'].astype(int)\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Mass of the cart (kg) and its uncertainty\nm_cart = 0.18995\ndelta_m_cart = 5e-06\n\n# Mass of hanging mass (kg) and its uncertainty\nm_hang = 0.01000\ndelta_m_hang = 5e-06\n\n# Height of the spring (m) and its uncertainty\nh = 0.95\ndelta_h = 0.0005\n\n# Predicted Final Velocity (m/s) and its uncertainty\nv_p = 0.9666\ndelta_v_p = 0.0007081\n\n# Enter the measured values of v_f (m/s)\ndf4['Measured v_f (m/s)'] = [0.93,0.93,0.92,0.94]\n\n###########################################\n\n\n# calculates the mass of the cart with the mass of the hanger and its uncertainty\nm_total = m_cart + m_hang\ndelta_m_total = np.sqrt(2) * delta_m_cart\n\n# Calculates the uncertainty of the velocity using standard deviation\nuncertainty_v = np.std(df4['Measured v_f (m/s)'])\n\n# prints out the cart data\nprint(\"Data for: \")\nprint(\"m_cart = %0.5f kg 𝛿m_cart = %g\" % (m_cart, delta_m_cart))\nprint(\"m_hang = %0.5f kg 𝛿m_hang = %g\" % (m_hang,delta_m_hang))\nprint(\"h = %0.3f m 𝛿h = %0.4f\" % (h,delta_h))\nprint(\"Predicted v_f = %0.5f m/s 𝛿v_p_f = %0.4f\" % (v_p,delta_v_p))\nprint(\"\")\n\n# Display the dataframe\nfrom IPython.display import display\nprint (\"Cart 4\")\ndisplay(df4)\n# Print statements for uncertainty of final velocity\nprint(\"𝛿v = %0.5f m/s\" % (uncertainty_v))\n```\n\n Data for: \n m_cart = 0.18995 kg 𝛿m_cart = 5e-06\n m_hang = 0.01000 kg 𝛿m_hang = 5e-06\n h = 0.950 m 𝛿h = 0.0005\n Predicted v_f = 0.96660 m/s 𝛿v_p_f = 0.0007\n \n Cart 4\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TrialMeasured v_f (m/s)
010.93
120.93
230.92
340.94
\n
\n\n\n 𝛿v = 0.00707 m/s\n\n\n***\n\n\n```python\n# Initial Potential Energy vs. Final Kinetic Energy Plot\n\n# Reads the name of the csv file and gets the data\ndf = pd.read_csv(\"./ExampleFiles/Lab 5 Graphs - PEi vs KEf.csv\")\n\n# Prints information about the file\n#df.info()\nprint(df)\nprint()\n\n# Defines the x and y values\npe = df.filter(['Ug (J)'], axis=1).dropna()\nke = df.filter(['Kf (J)'], axis=1).dropna()\n\n# Create a figure of reasonable size and resolution, white background, black edge color\nfig=plt.figure(figsize=(7,5), dpi= 100, facecolor='w', edgecolor='k')\n\n# Gets the data values for x and y\nx_data = pe.values.reshape(-1, 1)\ny_data = ke.values.reshape(-1, 1)\n\nxi = df['Ug (J)'].to_numpy()\nyi = df['Kf (J)'].to_numpy()\n\n# Creates the base plot with titles\nplt.plot(x_data,y_data,'b.',label='Raw Data')\n#plt.errorbar(x_data,y_data,Delta_x,Delta_t,'b.',label='Raw Data')\nplt.ylabel('Kinetic Energy (J)')\nplt.xlabel('Gravitational Potential Energy(J)')\nplt.title('Initial Potential Energy vs. Final Kinetic Energy')\n\n# Takes the x and y values to make a trendline\nintercept, slope, dintercept, dslope = linear_fit_plot_errors(xi,yi,0.07763,0.15120)\n\n# Adds the legend to the plot\nplt.legend()\n\n# Displays the plot\nplt.show()\n\nprint(\"\")\n```\n\n***\n***\n\n## Experiment 2: Spring Potential Energy vs. Kinetic Energy\nFor this experiment, you will store potential energy in a compressed spring and launch the cart down the airtrack. You will need to use the 3” rod to support the spring to launch the cart (See the diagram below). The best way to launch the cart is to use a fingernail to hold the cart back on the compressed spring and then let the cart slip out from under your fingernail. You might devise a better method, but it is important to release the cart as quickly as possible. \n\n
\n\n
\n\n**Do not fully compress the spring!** The last few millimeters are non-linear. But don’t be too gentle: at least compress the spring 1 cm.\n\nYou will need to perform four trial launches for each value of compression, $x_{s}$, that you determine is necessary (minimum of two). Consider carefully what your uncertainty, $ \\delta x_{s}$, in compression is over each set of trials. This will be important in calculating your uncertainty in the stored potential energy.\n\nWhere should the photogate be placed for *this* experiment?\n\n\n```python\n# Experiment 2 Raw Data\n# Cart 1\n\n# Create an empty numpy array to hold the raw data\nraw_data_5 = np.empty((4,2))\n\n# Set the trial number column identifiers for each Trial\nraw_data_5[0][0]=1\nraw_data_5[1][0]=2\nraw_data_5[2][0]=3\nraw_data_5[3][0]=4\n\n# Create a Pandas dataframe, and convert the Trial number column to integer format\ndf5 = pd.DataFrame(raw_data_5, columns=[\"Trial\", \n \"Measured v_f (m/s)\"])\n\ndf5['Trial'] = df5['Trial'].astype(int)\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Mass of the cart (kg) and its uncertainty\nm_cart = 0.18995\ndelta_m_cart = 5e-06\n\n# Value of compression (m) and its uncertainty\nx_s = 0.01\ndelta_xs = 0.005\n\n# Predicted Final Velocity (m/s) and its uncertainty\nv_p = 0.4104\ndelta_v_p = 0.2052\n\n# Enter the measured values of v_f (m/s)\ndf5['Measured v_f (m/s)'] = [0.54,0.44,0.50,0.50]\n\n###########################################\n\n# Calculates the uncertainty of the velocity using standard deviation\nuncertainty_v = np.std(df5['Measured v_f (m/s)'])\n\n# prints out the cart data\nprint(\"Data for: \")\nprint(\"m_cart = %0.5f kg 𝛿m_cart = %g\" % (m_cart, delta_m_cart))\nprint(\"x_s = %0.2f m 𝛿x_s = %0.4f\" % (x_s,delta_xs))\nprint(\"Predicted v_f = %0.5f m/s 𝛿v_p_f = %0.4f\" % (v_p,delta_v_p))\nprint(\"\")\n\n# Display the dataframe\nfrom IPython.display import display\nprint (\"Cart 1\")\ndisplay(df5)\n# Print statements for uncertainty of final velocity\nprint(\"𝛿v = %0.5f m/s\" % (uncertainty_v))\n```\n\n Data for: \n m_cart = 0.18995 kg 𝛿m_cart = 5e-06\n x_s = 0.01 m 𝛿x_s = 0.0050\n Predicted v_f = 0.41040 m/s 𝛿v_p_f = 0.2052\n \n Cart 1\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TrialMeasured v_f (m/s)
010.54
120.44
230.50
340.50
\n
\n\n\n 𝛿v = 0.03571 m/s\n\n\n***\n\n\n```python\n# Experiment 2 Raw Data\n# Cart 2\n\n# Create an empty numpy array to hold the raw data\nraw_data_6 = np.empty((4,2))\n\n# Set the trial number column identifiers for each Trial\nraw_data_6[0][0]=1\nraw_data_6[1][0]=2\nraw_data_6[2][0]=3\nraw_data_6[3][0]=4\n\n# Create a Pandas dataframe, and convert the Trial number column to integer format\ndf6 = pd.DataFrame(raw_data_6, columns=[\"Trial\", \n \"Measured v_f (m/s)\"])\n\ndf6['Trial'] = df6['Trial'].astype(int)\n\n\n#### Enter Raw Data Here!!!!!!!!!!!!!! ####\n\n# Mass of the cart (kg) and its uncertainty\nm_cart = 0.18995\ndelta_m_cart = 5e-06\n\n# Value of compression (m) and its uncertainty\nx_s = 0.02\ndelta_xs = 0.005\n\n# Predicted Final Velocity (m/s) and its uncertainty\nv_p = 0.6739\ndelta_v_p = 0.16\n\n# Enter the measured values of v_f (m/s)\ndf6['Measured v_f (m/s)'] = [0.82,0.81,0.83,0.82]\n\n###########################################\n\n# Calculates the uncertainty of the velocity using standard deviation\nuncertainty_v = np.std(df6['Measured v_f (m/s)'])\n\n# prints out the cart data\nprint(\"Data for: \")\nprint(\"m_cart = %0.5f kg 𝛿m_cart = %g\" % (m_cart, delta_m_cart))\nprint(\"x_s = %0.2f m 𝛿x_s = %0.4f\" % (x_s,delta_xs))\nprint(\"Predicted v_f = %0.5f m/s 𝛿v_p_f = %0.4f\" % (v_p,delta_v_p))\nprint(\"\")\n\n# Display the dataframe\nfrom IPython.display import display\nprint (\"Cart 2\")\ndisplay(df6)\n# Print statements for uncertainty of final velocity\nprint(\"𝛿v = %0.5f m/s\" % (uncertainty_v))\n```\n\n Data for: \n m_cart = 0.18995 kg 𝛿m_cart = 5e-06\n x_s = 0.02 m 𝛿x_s = 0.0050\n Predicted v_f = 0.67390 m/s 𝛿v_p_f = 0.1600\n \n Cart 2\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TrialMeasured v_f (m/s)
010.82
120.81
230.83
340.82
\n
\n\n\n 𝛿v = 0.00707 m/s\n\n\n***\n***\n\n## Experiment 3: Spring Potential Energy vs. Gravitational Potential Energy\n**This experiment is optional.**\n\nRemove the photogate and prop the leg on the far end of the airtrack (away from the spring launcher) on a wooden “shim” (a 2x4). By compressing the spring, you can launch the cart up the inclined airtrack. You will need to find an accurate method for determining the change in height between the starting and ending positions of the glider. Should you use a direct measurement (from a meter stick) or an indirect measurement (knowing the angle and measuring the distance the cart moved along the track)? \n\nIf you perform this experiment, you must record the data and describe it carefully in your report.\n\n# Your Report\n\n### Experimental Procedure\nYou will need to write a page or two describing how you set up your experiment and collected\nyour data. Specifically, you must mention:\n\n- How did you measure the spring constant of your spring?\n- Describe the setup you used to compare gravitational-potential and kinetic energies.\n - How did you ensure that the cart’s potential energy did not change?\n - How did you measure the height of your mass hanger and keep that height consistent between runs?\n - Where did you place your photogate and what did you use for the “flag?”\n - How did you compute the velocity of the mass hanger for its kinetic energy?\n- Describe the setup you used to compare spring-potential and kinetic energies.\n - How did you measure the amount you compressed the spring? What was your uncertainty in that measurement?\n - Where did you place your photogate and what did you use for your “flag?” \n\nWrite it so that someone else could repeat your experiment by just reading this section. Talk\nabout any problems you encountered and how you handled them.\n\n### Results and Conclusion\nThis will be your longest section. Use good paragraph structure to compare each experimental\nresult with each theoretical prediction:\n\n- How do your initial and final energies compare for each experiment?\n- Compute the spring constant for your spring given the results in the second experiment. How does this compare to the value you measured initially?\n- Does your data support or refute Conservation of Mechanical Energy? What, if anything, might have interfered with perfect agreement?\n\nAs always, talk about your uncertainties, how they affected your data and how you might be able to reduce them. Make sure that you discuss all possible sources of uncertainties in your experiments.\n\n### Appendix\n*Include your signed raw data sheet(s) and sample calculations.*\n", "meta": {"hexsha": "34b95bc5d3efe511e358d8df54dfdb5172a8ce12", "size": 150603, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "PHYS201/Lab5.ipynb", "max_stars_repo_name": "JNichols-19/PhysicsLabs", "max_stars_repo_head_hexsha": "289cb0d07408afde252fe2cabad17fc0b4d987c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PHYS201/Lab5.ipynb", "max_issues_repo_name": "JNichols-19/PhysicsLabs", "max_issues_repo_head_hexsha": "289cb0d07408afde252fe2cabad17fc0b4d987c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PHYS201/Lab5.ipynb", "max_forks_repo_name": "JNichols-19/PhysicsLabs", "max_forks_repo_head_hexsha": "289cb0d07408afde252fe2cabad17fc0b4d987c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.0345528455, "max_line_length": 52588, "alphanum_fraction": 0.8148642457, "converted": true, "num_tokens": 9144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.3499320178907083}} {"text": "\n\n- original: https://pytorch.org/tutorials/beginner/transformer_tutorial.html\n- date: 2020-0807\n- modified: Shin Asakawa \n\n\n\n```python\n# 2020年8月8日 JST 現在 colab にインストールされている torchtext のバージョンが 0.3.0 と少々古い\n# update しないとエラーになるので,一旦このセルを実行して torchtext を最新版にした上で runtime を\n# 再起動されたい。-- asakawa\n!pip install --upgrade torchtext\n```\n\n Collecting torchtext\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/b9/f9/224b3893ab11d83d47fde357a7dcc75f00ba219f34f3d15e06fe4cb62e05/torchtext-0.7.0-cp36-cp36m-manylinux1_x86_64.whl (4.5MB)\n \u001b[K |████████████████████████████████| 4.5MB 4.7MB/s \n \u001b[?25hRequirement already satisfied, skipping upgrade: torch in /usr/local/lib/python3.6/dist-packages (from torchtext) (1.6.0+cu101)\n Requirement already satisfied, skipping upgrade: tqdm in /usr/local/lib/python3.6/dist-packages (from torchtext) (4.41.1)\n Collecting sentencepiece\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)\n \u001b[K |████████████████████████████████| 1.1MB 51.9MB/s \n \u001b[?25hRequirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from torchtext) (1.18.5)\n Requirement already satisfied, skipping upgrade: requests in /usr/local/lib/python3.6/dist-packages (from torchtext) (2.23.0)\n Requirement already satisfied, skipping upgrade: future in /usr/local/lib/python3.6/dist-packages (from torch->torchtext) (0.16.0)\n Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (3.0.4)\n Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (2020.6.20)\n Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (2.10)\n Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->torchtext) (1.24.3)\n Installing collected packages: sentencepiece, torchtext\n Found existing installation: torchtext 0.3.1\n Uninstalling torchtext-0.3.1:\n Successfully uninstalled torchtext-0.3.1\n Successfully installed sentencepiece-0.1.91 torchtext-0.7.0\n\n\n\n\n\n```python\n# from https://github.com/dmlc/xgboost/issues/1715\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n```\n\n\n```python\n%matplotlib inline\n```\n\n## ``nn.Transformer`` と ``TorchText`` を用いた Seq2Seq (系列-to-系列) モデル\n\n\nこのチュートリアルでは,[nn.Transformer](https://pytorch.org/docs/master/nn.html?highlight=nn%20transformer#torch.nn.Transformer) モジュールを用いた sequence-to-sequnce (訳注:日本語では `seq2seq モデル` などと呼ばれます) モデルの訓練方法を示します。\n\n\n\nPyTorch リリース 1.2 には,[Attention is All You Need](https://arxiv.org/pdf/1706.03762.pdf) (訳注:初めてトランスフォーマーを提案した論文) に基づいた標準的なトランスフォーマーモジュールが含まれます。\nトランスフォーマーは並列化が容易で,seq2seq モデルを凌ぐ性能が示されています。\n``nn.Transfomer`` モジュールは,注意機構に基づいて,入出力情報間大域的依存性を解消する機構です\n(最近の別実装は [nn.MultiheadAttention](https://pytorch.org/docs/master/nn.html?highlight=multiheadattention#torch.nn.MultiheadAttention))。\n``nn.Transformer`` は単一要素で構成されており,本チュートリアル内の [nn.TransformerEncoder](https://pytorch.org/docs/master/nn.html?highlight=nn%20transformerencoder#torch.nn.TransformerEncoder) のごとく,修正,構成が容易です。\n\n\n
\n\n\n\n\n\n### (訳注) 位置符号器 Position encoders\nトランスフォーマーの入力には,上述の単語表現に加えて,位置符号器からの信号も重ね合わされる。\n位置 $i$ の信号は次式で周波数領域へと変換される:\n\n$$\n\\begin{align}\n\\text{PE}_{(\\text{pos},2i)} &= \\sin\\left(\\frac{\\text{pos}}{10000^{\\frac{2i}{d_{\\text{model}}}}}\\right)\\\\\n\\text{PE}_{(\\text{pos},2i+1)} &= \\cos\\left(\\frac{\\text{pos}}{10000^{\\frac{2i}{d_{\\text{model}}}}}\\right)\n\\end{align}\n$$\n\n位置符号器による位置表現は,$i$ 番目の位置情報をワンホット表現するのではなく,周波数領域に変換することで周期情報を表現する試みと見なし得るだろう。\n\n\n\n```python\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\nLoad and batch data\n-------------------\n\n\n\n\nThe training process uses Wikitext-2 dataset from ``torchtext``. The\nvocab object is built based on the train dataset and is used to numericalize\ntokens into tensors. Starting from sequential data, the ``batchify()``\nfunction arranges the dataset into columns, trimming off any tokens remaining\nafter the data has been divided into batches of size ``batch_size``.\nFor instance, with the alphabet as the sequence (total length of 26)\nand a batch size of 4, we would divide the alphabet into 4 sequences of\nlength 6:\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\nThese columns are treated as independent by the model, which means that\nthe dependence of ``G`` and ``F`` can not be learned, but allows more\nefficient batch processing.\n\n\n\n\n\n```python\nimport torchtext\nfrom torchtext.data.utils import get_tokenizer\nTEXT = torchtext.data.Field(tokenize=get_tokenizer(\"basic_english\"),\n init_token='',\n eos_token='',\n lower=True)\ntrain_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)\nTEXT.build_vocab(train_txt)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef batchify(data, bsz):\n data = TEXT.numericalize([data.examples[0].text])\n # Divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n return data.to(device)\n\nbatch_size = 20\neval_batch_size = 10\ntrain_data = batchify(train_txt, batch_size)\nval_data = batchify(val_txt, eval_batch_size)\ntest_data = batchify(test_txt, eval_batch_size)\n```\n\n /usr/local/lib/python3.6/dist-packages/torchtext/data/field.py:150: UserWarning: Field class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.\n warnings.warn('{} class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.'.format(self.__class__.__name__), UserWarning)\n\n\n downloading wikitext-2-v1.zip\n\n\n wikitext-2-v1.zip: 100%|██████████| 4.48M/4.48M [00:00<00:00, 8.92MB/s]\n\n\n extracting\n\n\n /usr/local/lib/python3.6/dist-packages/torchtext/data/example.py:78: UserWarning: Example class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.\n warnings.warn('Example class will be retired in the 0.8.0 release and moved to torchtext.legacy. Please see 0.7.0 release notes for further information.', UserWarning)\n\n\n\n```python\ntorchtext.__version__ # 0.3.1 --> 0.7.0\n```\n\n\n\n\n '0.7.0'\n\n\n\n### Functions to generate input and target sequence\n\n\n\n\n``get_batch()`` function generates the input and target sequence for\nthe transformer model. It subdivides the source data into chunks of\nlength ``bptt``. For the language modeling task, the model needs the\nfollowing words as ``Target``. For example, with a ``bptt`` value of 2,\nwe’d get the following two Variables for ``i`` = 0:\n\n\n\n\n\n\nIt should be noted that the chunks are along dimension 0, consistent\nwith the ``S`` dimension in the Transformer model. The batch dimension\n``N`` is along dimension 1.\n\n\n\n\n\n```python\nbptt = 35\ndef get_batch(source, i):\n seq_len = min(bptt, len(source) - 1 - i)\n data = source[i:i+seq_len]\n target = source[i+1:i+1+seq_len].view(-1)\n return data, target\n```\n\nInitiate an instance\n--------------------\n\n\n\n\nThe model is set up with the hyperparameter below. The vocab size is\nequal to the length of the vocab object.\n\n\n\n\n\n```python\nntokens = len(TEXT.vocab.stoi) # the size of vocabulary\nemsize = 200 # embedding dimension\nnhid = 200 # the dimension of the feedforward network model in nn.TransformerEncoder\nnlayers = 2 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder\nnhead = 2 # the number of heads in the multiheadattention models\ndropout = 0.2 # the dropout value\nmodel = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)\n```\n\nRun the model\n-------------\n\n\n\n\n[CrossEntropyLoss](https://pytorch.org/docs/master/nn.html?highlight=crossentropyloss#torch.nn.CrossEntropyLoss) is applied to track the loss and [SGD](https://pytorch.org/docs/master/optim.html?highlight=sgd#torch.optim.SGD) implements stochastic gradient descent method as the optimizer. \nThe initial learning rate is set to 5.0. [StepLR](https://pytorch.org/docs/master/optim.html?highlight=steplr#torch.optim.lr_scheduler.StepLR) is applied to adjust the learn rate through epochs. \nDuring the training, we use [nn.utils.clip_grad_norm](https://pytorch.org/docs/master/nn.html?highlight=nn%20utils%20clip_grad_norm#torch.nn.utils.clip_grad_norm_) function to scale all the gradient together to prevent exploding.\n\n\n\n\n```python\ncriterion = nn.CrossEntropyLoss()\nlr = 5.0 # learning rate\noptimizer = torch.optim.SGD(model.parameters(), lr=lr)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n\nimport time\ndef train():\n model.train() # Turn on the train mode\n total_loss = 0.\n start_time = time.time()\n ntokens = len(TEXT.vocab.stoi)\n for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):\n data, targets = get_batch(train_data, i)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output.view(-1, ntokens), targets)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n total_loss += loss.item()\n log_interval = 200\n if batch % log_interval == 0 and batch > 0:\n cur_loss = total_loss / log_interval\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | '\n 'lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f}'.format(\n epoch, batch, len(train_data) // bptt, scheduler.get_lr()[0],\n elapsed * 1000 / log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\ndef evaluate(eval_model, data_source):\n eval_model.eval() # Turn on the evaluation mode\n total_loss = 0.\n ntokens = len(TEXT.vocab.stoi)\n with torch.no_grad():\n for i in range(0, data_source.size(0) - 1, bptt):\n data, targets = get_batch(data_source, i)\n output = eval_model(data)\n output_flat = output.view(-1, ntokens)\n total_loss += len(data) * criterion(output_flat, targets).item()\n return total_loss / (len(data_source) - 1)\n```\n\nLoop over epochs. Save the model if the validation loss is the best\nwe've seen so far. Adjust the learning rate after each epoch.\n\n\n\n\n```python\nbest_val_loss = float(\"inf\")\nepochs = 3 # The number of epochs\nbest_model = None\n\nfor epoch in range(1, epochs + 1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(model, val_data)\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print('-' * 89)\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_model = model\n\n scheduler.step()\n```\n\n /usr/local/lib/python3.6/dist-packages/torch/optim/lr_scheduler.py:351: UserWarning: To get the last learning rate computed by the scheduler, please use `get_last_lr()`.\n \"please use `get_last_lr()`.\", UserWarning)\n\n\n | epoch 1 | 200/ 2981 batches | lr 5.00 | ms/batch 17.66 | loss 8.07 | ppl 3190.20\n | epoch 1 | 400/ 2981 batches | lr 5.00 | ms/batch 16.16 | loss 6.81 | ppl 904.06\n | epoch 1 | 600/ 2981 batches | lr 5.00 | ms/batch 16.21 | loss 6.37 | ppl 583.67\n | epoch 1 | 800/ 2981 batches | lr 5.00 | ms/batch 16.27 | loss 6.23 | ppl 508.50\n | epoch 1 | 1000/ 2981 batches | lr 5.00 | ms/batch 16.31 | loss 6.11 | ppl 451.57\n | epoch 1 | 1200/ 2981 batches | lr 5.00 | ms/batch 16.34 | loss 6.09 | ppl 440.42\n | epoch 1 | 1400/ 2981 batches | lr 5.00 | ms/batch 16.40 | loss 6.04 | ppl 420.47\n | epoch 1 | 1600/ 2981 batches | lr 5.00 | ms/batch 16.40 | loss 6.04 | ppl 421.31\n | epoch 1 | 1800/ 2981 batches | lr 5.00 | ms/batch 16.40 | loss 5.96 | ppl 388.35\n | epoch 1 | 2000/ 2981 batches | lr 5.00 | ms/batch 16.44 | loss 5.95 | ppl 385.04\n | epoch 1 | 2200/ 2981 batches | lr 5.00 | ms/batch 16.47 | loss 5.85 | ppl 346.06\n | epoch 1 | 2400/ 2981 batches | lr 5.00 | ms/batch 16.56 | loss 5.89 | ppl 361.99\n | epoch 1 | 2600/ 2981 batches | lr 5.00 | ms/batch 16.59 | loss 5.89 | ppl 362.61\n | epoch 1 | 2800/ 2981 batches | lr 5.00 | ms/batch 16.65 | loss 5.79 | ppl 328.52\n -----------------------------------------------------------------------------------------\n | end of epoch 1 | time: 51.73s | valid loss 5.69 | valid ppl 296.12\n -----------------------------------------------------------------------------------------\n | epoch 2 | 200/ 2981 batches | lr 4.51 | ms/batch 16.83 | loss 5.80 | ppl 331.27\n | epoch 2 | 400/ 2981 batches | lr 4.51 | ms/batch 16.78 | loss 5.77 | ppl 320.24\n | epoch 2 | 600/ 2981 batches | lr 4.51 | ms/batch 16.84 | loss 5.60 | ppl 270.97\n | epoch 2 | 800/ 2981 batches | lr 4.51 | ms/batch 16.89 | loss 5.63 | ppl 278.71\n | epoch 2 | 1000/ 2981 batches | lr 4.51 | ms/batch 16.90 | loss 5.59 | ppl 266.43\n | epoch 2 | 1200/ 2981 batches | lr 4.51 | ms/batch 17.00 | loss 5.60 | ppl 271.78\n | epoch 2 | 1400/ 2981 batches | lr 4.51 | ms/batch 17.02 | loss 5.62 | ppl 276.21\n | epoch 2 | 1600/ 2981 batches | lr 4.51 | ms/batch 17.05 | loss 5.65 | ppl 285.20\n | epoch 2 | 1800/ 2981 batches | lr 4.51 | ms/batch 17.08 | loss 5.58 | ppl 265.18\n | epoch 2 | 2000/ 2981 batches | lr 4.51 | ms/batch 17.20 | loss 5.61 | ppl 272.27\n | epoch 2 | 2200/ 2981 batches | lr 4.51 | ms/batch 17.21 | loss 5.50 | ppl 245.18\n | epoch 2 | 2400/ 2981 batches | lr 4.51 | ms/batch 17.25 | loss 5.57 | ppl 261.72\n | epoch 2 | 2600/ 2981 batches | lr 4.51 | ms/batch 17.29 | loss 5.58 | ppl 264.56\n | epoch 2 | 2800/ 2981 batches | lr 4.51 | ms/batch 17.19 | loss 5.50 | ppl 245.27\n -----------------------------------------------------------------------------------------\n | end of epoch 2 | time: 53.38s | valid loss 5.55 | valid ppl 256.81\n -----------------------------------------------------------------------------------------\n | epoch 3 | 200/ 2981 batches | lr 4.29 | ms/batch 17.23 | loss 5.54 | ppl 253.60\n | epoch 3 | 400/ 2981 batches | lr 4.29 | ms/batch 17.06 | loss 5.55 | ppl 256.59\n | epoch 3 | 600/ 2981 batches | lr 4.29 | ms/batch 17.05 | loss 5.35 | ppl 210.74\n | epoch 3 | 800/ 2981 batches | lr 4.29 | ms/batch 17.12 | loss 5.41 | ppl 223.24\n | epoch 3 | 1000/ 2981 batches | lr 4.29 | ms/batch 17.05 | loss 5.37 | ppl 214.11\n | epoch 3 | 1200/ 2981 batches | lr 4.29 | ms/batch 17.13 | loss 5.40 | ppl 220.69\n | epoch 3 | 1400/ 2981 batches | lr 4.29 | ms/batch 17.09 | loss 5.43 | ppl 228.11\n | epoch 3 | 1600/ 2981 batches | lr 4.29 | ms/batch 17.08 | loss 5.46 | ppl 235.35\n | epoch 3 | 1800/ 2981 batches | lr 4.29 | ms/batch 17.08 | loss 5.40 | ppl 222.21\n | epoch 3 | 2000/ 2981 batches | lr 4.29 | ms/batch 17.07 | loss 5.43 | ppl 229.29\n | epoch 3 | 2200/ 2981 batches | lr 4.29 | ms/batch 17.07 | loss 5.32 | ppl 203.94\n | epoch 3 | 2400/ 2981 batches | lr 4.29 | ms/batch 17.08 | loss 5.39 | ppl 220.12\n | epoch 3 | 2600/ 2981 batches | lr 4.29 | ms/batch 17.14 | loss 5.41 | ppl 224.23\n | epoch 3 | 2800/ 2981 batches | lr 4.29 | ms/batch 17.15 | loss 5.34 | ppl 208.53\n -----------------------------------------------------------------------------------------\n | end of epoch 3 | time: 53.56s | valid loss 5.52 | valid ppl 249.41\n -----------------------------------------------------------------------------------------\n\n\nEvaluate the model with the test dataset\n-------------------------------------\n\nApply the best model to check the result with the test dataset.\n\n\n\n\n```python\ntest_loss = evaluate(best_model, test_data)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\nprint('=' * 89)\n```\n\n =========================================================================================\n | End of training | test loss 5.43 | test ppl 227.81\n =========================================================================================\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "002616a0e2e0eb88a80c80a1eba516794c7b6868", "size": 37867, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/01torchtext_transformer_tutorial.ipynb", "max_stars_repo_name": "JPA-BERT/jpa-bert.github.io", "max_stars_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/01torchtext_transformer_tutorial.ipynb", "max_issues_repo_name": "JPA-BERT/jpa-bert.github.io", "max_issues_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/01torchtext_transformer_tutorial.ipynb", "max_forks_repo_name": "JPA-BERT/jpa-bert.github.io", "max_forks_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0313953488, "max_line_length": 303, "alphanum_fraction": 0.5064039929, "converted": true, "num_tokens": 7544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.3497261489931118}} {"text": "\n\n\n# Tutorial-IllinoisGRMHD: Convert_to_HydroBase ETKThorn\n\n## Authors: Leo Werneck & Zach Etienne\n\n**This module is currently under development**\n\n## In this tutorial module we generate the Convert_to_HydroBase ETK thorn files, compatible with our latest implementation of IllinoisGRMHD\n\n### Required and recommended citations:\n\n* **(Required)** Etienne, Z. B., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L. IllinoisGRMHD: an open-source, user-friendly GRMHD code for dynamical spacetimes. Class. Quantum Grav. 32 (2015) 175009. ([arxiv:1501.07276](http://arxiv.org/abs/1501.07276)).\n* **(Required)** Noble, S. C., Gammie, C. F., McKinney, J. C., Del Zanna, L. Primitive Variable Solvers for Conservative General Relativistic Magnetohydrodynamics. Astrophysical Journal, 641, 626 (2006) ([astro-ph/0512420](https://arxiv.org/abs/astro-ph/0512420)).\n* **(Recommended)** Del Zanna, L., Bucciantini N., Londrillo, P. An efficient shock-capturing central-type scheme for multidimensional relativistic flows - II. Magnetohydrodynamics. A&A 400 (2) 397-413 (2003). DOI: 10.1051/0004-6361:20021641 ([astro-ph/0210618](https://arxiv.org/abs/astro-ph/0210618)).\n\nIf using the version of `IllinoisGRMHD` with piecewise polytropic *or* tabulated (coming soon!) EOS support, then the following citation is also required:\n\n* **(Required)** Etienne, Z. B., Werneck, L., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L., *IllinoisGRMHD github repository* (2019). Source Code URL: https://github.com/zachetienne/nrpytutorial/tree/master/IllinoisGRMHD/.\n\n### Dependencies\n\nThe files generated in this tutorial notebook depends on the following files:\n\n* `IllinoisGRMHD_headers.h` \\[[**tutorial**](Tutorial-IllinoisGRMHD__IllinoisGRMHD_headers.ipynb)\\]\n* `IllinoisGRMHD_EoS_lowlevel_functs.C` \\[[**tutorial**](Tutorial-IllinoisGRMHD__EoS_lowlevel_functs.ipynb)\\]\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis module is organized as follows\n\n0. [Step 0](#src_dir): **Source directory creation**\n1. [Step 1](#convert_to_hydrobase__src): **The `Convert_to_HydroBase.C` file**\n 1. [Step 1.a](#initialize_eos_struct__compute_eps): *Initializing the EOS struct, computing $\\epsilon$*\n 1. [Step 1.b](#valencia_vi_from_vi): *Computing the Valencia 3-velocity from $v^{i}$*\n 1. [Step 1.c](#computing_lorentz_factor__update_bi): *Computing the Lorentz factor $\\gamma_{v}$ and updating $B^{i}$*\n1. [Step 2](#convert_to_hydrobase__param): **The `param.ccl` file**\n1. [Step 3](#convert_to_hydrobase__interface): **The `interface.ccl` file**\n1. [Step 4](#convert_to_hydrobase__schedule): **The `schedule.ccl` file**\n1. [Step 5](#convert_to_hydrobase__make): **The `make.code.defn` file**\n1. [Step 6](#code_validation): **Code validation**\n1. [Step 7](#latex_pdf_output): **Output this notebook to $\\LaTeX$-formatted PDF file**\n\n\n\n# Step 0: Source directory creation \\[Back to [top](#toc)\\]\n$$\\label{src_dir}$$\n\nWe will now use the [cmdline_helper.py NRPy+ module](Tutorial-Tutorial-cmdline_helper.ipynb) to create the source directory within the `IllinoisGRMHD` NRPy+ directory, if it does not exist yet.\n\n\n```python\n# Step 0: Creation of the IllinoisGRMHD source directory\n# Step 0a: Load up cmdline_helper and create the directory\nimport os,sys\nnrpy_dir_path = os.path.join(\"..\",\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\nimport cmdline_helper as cmd\nbasedir = os.path.join(\"..\",\"Convert_to_HydroBase\")\ncmd.mkdir(basedir)\nsrcdir = os.path.join(basedir,\"src\")\ncmd.mkdir(srcdir)\n```\n\n\n\n# Step 1: The `Convert_to_HydroBase.C` file \\[Back to [top](#toc)\\]\n$$\\label{convert_to_hydrobase__src}$$\n\n\n\n## Step 1.a: Initializing the EOS struct, computing $\\epsilon$ \\[Back to [top](#toc)\\]\n$$\\label{initialize_eos_struct__compute_eps}$$\n\nOur goal here is to compute $\\epsilon$, the specific internal energy. `IllinoisGRMHD` implements a hybrid EOS (see equation (20) in [Etienne *et al*.](https://arxiv.org/pdf/1501.07276.pdf))\n\n$$\nP = P_{\\rm cold} + P_{\\rm th} = P_{\\rm cold} + \\left(\\Gamma_{\\rm th} - 1\\right)\\rho_{b}\\epsilon_{\\rm th}\\ ,\n$$\n\nwhere $P_{\\rm cold}$ is determined using a single or piecewise polytropic EOS. We assume $\\epsilon = \\epsilon_{\\rm cold} + \\epsilon_{\\rm th}$, i.e.\n\n$$\nP = P_{\\rm cold} + \\left(\\Gamma_{\\rm th} - 1\\right)\\rho_{b}\\left(\\epsilon - \\epsilon_{\\rm cold}\\right)\\ ,\n$$\n\nso that we obtain\n\n$$\n\\boxed{\\epsilon = \\epsilon_{\\rm cold} + \\frac{P - P_{\\rm cold}}{\\rho_{b}\\left(\\Gamma_{\\rm th}-1\\right)}}\\ .\n$$\n\nBelow, $P_{\\rm cold}$ and $\\epsilon_{\\rm cold}$ are determined using the `compute_P_cold__eps_cold()` function, which is documented in the [EoS_lowlevel_functs `IllinoisGRMHD` tutorial notebook](Tutorial-IllinoisGRMHD__EoS_lowlevel_functs.ipynb).\n\n\n```python\n%%writefile $srcdir/Convert_to_HydroBase.C\n#include \"cctk.h\"\n#include \n#include \n#include \n#include \n#include \"cctk_Arguments.h\"\n#include \"cctk_Parameters.h\"\n\n#include \"IllinoisGRMHD_headers.h\"\n\nvoid Convert_to_HydroBase(CCTK_ARGUMENTS) {\n\n DECLARE_CCTK_ARGUMENTS;\n DECLARE_CCTK_PARAMETERS;\n\n // Generally, we only need the HydroBase variables for diagnostic purposes, so we run the below loop only at iterations in which diagnostics are run.\n if(Convert_to_HydroBase_every==0 || cctk_iteration%Convert_to_HydroBase_every!=0) return;\n\n /***************\n * PPEOS Patch *\n ***************\n * We will need to set up our EOS in\n * order to be able to compute eps below\n */\n eos_struct eos;\n initialize_EOS_struct_from_input(eos);\n \n#pragma omp parallel for \n for(int k=0;k\n\n## Step 1.b: Computing the Valencia 3-velocity from $v^{i}$ \\[Back to [top](#toc)\\]\n$$\\label{valencia_vi_from_vi}$$\n\nIn `IllinoisGRMHD`, we use the 3-velocity\n\n$$\nv^{i}\\equiv\\frac{u^{i}}{u^{0}}\\ ,\n$$\n\nwhere $u^{\\mu}$ is the fluid 4-velocity. The [HydroBase ETK Thorn](http://einsteintoolkit.org/thornguide/EinsteinBase/HydroBase/documentation.html), however, uses the Valencia formalism, which adopts the 3-velocity as measured by a normal observers (also referred to as the Eulerian 3-velocity), $v^{i}_{(n)}$, which is given by (see equation (14) in [Mösta *et al*.](https://arxiv.org/pdf/1304.5544.pdf))\n\n$$\nv^{i}_{(n)} = \\frac{u^{i}}{\\alpha u^{0}} + \\frac{\\beta^{i}}{\\alpha}\\ .\n$$\n\nThus, we can read off the relation\n\n$$\n\\boxed{v^{i}_{(n)} = \\frac{1}{\\alpha}\\left(v^{i} + \\beta^{i}\\right)}\\ ,\n$$\n\nwhich we implement below.\n\n\n```python\n%%writefile -a $srcdir/Convert_to_HydroBase.C\n\n\n // IllinoisGRMHD defines v^i = u^i/u^0.\n \n // Meanwhile, the ET/HydroBase formalism, called the Valencia \n // formalism, splits the 4 velocity into a purely spatial part\n // and a part that is normal to the spatial hypersurface:\n // u^a = G (n^a + U^a), (Eq. 14 of arXiv:1304.5544; G=W, U^a=v^a)\n // where n^a is the unit normal vector to the spatial hypersurface,\n // n_a = {-\\alpha,0,0,0}, and U^a is the purely spatial part, which\n // is defined in HydroBase as the vel[] vector gridfunction.\n // Then u^a n_a = - \\alpha u^0 = G n^a n_a = -G, and\n // of course \\alpha u^0 = 1/sqrt(1+γ^ij u_i u_j) = \\Gamma,\n // the standard Lorentz factor.\n\n // Note that n^i = - \\beta^i / \\alpha, so \n // u^a = \\Gamma (n^a + U^a) \n // -> u^i = \\Gamma ( U^i - \\beta^i / \\alpha )\n // which implies\n // v^i = u^i/u^0\n // = \\Gamma/u^0 ( U^i - \\beta^i / \\alpha ) <- \\Gamma = \\alpha u^0\n // = \\alpha ( U^i - \\beta^i / \\alpha )\n // = \\alpha U^i - \\beta^i\n CCTK_REAL lapseL=alp[index];\n CCTK_REAL lapseL_inv=1.0/lapseL;\n vel[CCTK_GFINDEX4D(cctkGH,i,j,k,0)] = (PRIMS[VX] + betax[index])*lapseL_inv;\n vel[CCTK_GFINDEX4D(cctkGH,i,j,k,1)] = (PRIMS[VY] + betay[index])*lapseL_inv;\n vel[CCTK_GFINDEX4D(cctkGH,i,j,k,2)] = (PRIMS[VZ] + betaz[index])*lapseL_inv;\n```\n\n Appending to ../Convert_to_HydroBase/src/Convert_to_HydroBase.C\n\n\n\n\n## Step 1.c: Computing the Lorentz factor $\\gamma_{v}$ and updating $B^{i}$ \\[Back to [top](#toc)\\]\n$$\\label{computing_lorentz_factor__update_bi}$$\n\nWe now want to compute the Lorentz factor $\\gamma_{v}=\\left(1+\\gamma_{ij}u^{i}u^{j}\\right)^{-1/2}$. Below we implement the quantity\n\n$$\nA = 1 - \\frac{1}{\\left(\\alpha u^{0}\\right)^{2}} = \\gamma_{ij}\\left(\\frac{v^{i}+\\beta^{i}}{\\alpha}\\right)\\left(\\frac{v^{j}+\\beta^{j}}{\\alpha}\\right)\\ ,\n$$\n\nwhich imply that $\\gamma_{v}=\\alpha u^{0}$. First let us show that this is indeed the case. Consider\n\n$$\n\\begin{align}\nA \n&= \\gamma_{ij}\\left(\\frac{v^{i}+\\beta^{i}}{\\alpha}\\right)\\left(\\frac{v^{j}+\\beta^{j}}{\\alpha}\\right)\\\\\n&= \\frac{\\gamma_{ij}}{\\alpha^{2}}\\left[\\frac{\\gamma^{ik}u_{k}}{u^{0}} - \\beta^{i} + \\beta^{i}\\right]\\left[\\frac{\\gamma^{j\\ell}u_{\\ell}}{u^{0}} - \\beta^{j} + \\beta^{j}\\right]\\\\\n&=\\frac{\\gamma_{ij}u^{i}u^{j}}{\\left(\\alpha u^{0}\\right)^{2}}\\\\\n&=\\frac{\\left(\\alpha u^{0}\\right)^{2}-1}{\\left(\\alpha u^{0}\\right)^{2}}\\\\\n&=1 - \\frac{1}{\\left(\\alpha u^{0}\\right)^{2}}\\ \\\\\n\\implies &\\boxed{A = 1 - \\frac{1}{\\left(\\alpha u^{0}\\right)^{2}}}\\ ,\n\\end{align}\n$$\n\nwhere when going from line 1 to 2 and from line 3 to 4 we have used eqs. (53) and (56) from [Duez *et al.*](https://arxiv.org/pdf/astro-ph/0503420.pdf), respectively. Keep in mind that the equation we are going to implement below is\n\n$$\n\\boxed{{\\rm one\\_minus\\_one\\_over\\_alpha\\_u0\\_squared} = \\gamma_{ij}\\left(\\frac{v^{i}+\\beta^{i}}{\\alpha}\\right)\\left(\\frac{v^{j}+\\beta^{j}}{\\alpha}\\right)}\\ ,\n$$\n\nbut it is important to know that this equation also equals $A$ above.\n\nFinally, we update the `Bvec` array with the appropriate (`Bx`,`By`,`Bz`) values.\n\n\n```python\n%%writefile -a $srcdir/Convert_to_HydroBase.C\n\n\n // \\alpha u^0 = 1/sqrt(1+γ^ij u_i u_j) = \\Gamma = w_lorentz\n // First compute u^0:\n // Derivation of first equation:\n // \\gamma_{ij} (v^i + \\beta^i)(v^j + \\beta^j)/(\\alpha)^2 \n // = \\gamma_{ij} 1/(u^0)^2 ( \\gamma^{ik} u_k \\gamma^{jl} u_l /(\\alpha)^2 <- Using Eq. 53 of arXiv:astro-ph/0503420\n // = 1/(u^0 \\alpha)^2 u_j u_l \\gamma^{jl} <- Since \\gamma_{ij} \\gamma^{ik} = \\delta^k_j\n // = 1/(u^0 \\alpha)^2 ( (u^0 \\alpha)^2 - 1 ) <- Using Eq. 56 of arXiv:astro-ph/0503420\n // = 1 - 1/(u^0 \\alpha)^2 <= 1\n CCTK_REAL shiftxL = betax[index];\n CCTK_REAL shiftyL = betay[index];\n CCTK_REAL shiftzL = betaz[index];\n\n CCTK_REAL gxxL = gxx[index];\n CCTK_REAL gxyL = gxy[index];\n CCTK_REAL gxzL = gxz[index];\n CCTK_REAL gyyL = gyy[index];\n CCTK_REAL gyzL = gyz[index];\n CCTK_REAL gzzL = gzz[index];\n\n CCTK_REAL one_minus_one_over_alpha_u0_squared = (gxxL* SQR(PRIMS[VX] + shiftxL) +\n 2.0*gxyL*(PRIMS[VX] + shiftxL)*(PRIMS[VY] + shiftyL) +\n 2.0*gxzL*(PRIMS[VX] + shiftxL)*(PRIMS[VZ] + shiftzL) +\n gyyL* SQR(PRIMS[VY] + shiftyL) +\n 2.0*gyzL*(PRIMS[VY] + shiftyL)*(PRIMS[VZ] + shiftzL) +\n gzzL* SQR(PRIMS[VZ] + shiftzL) )*SQR(lapseL_inv);\n /*** Check for superluminal velocity ***/\n //FIXME: Instead of >1.0, should be one_minus_one_over_alpha_u0_squared > ONE_MINUS_ONE_OVER_GAMMA_SPEED_LIMIT_SQUARED, for consistency with conserv_to_prims routines\n\n if(one_minus_one_over_alpha_u0_squared > 1.0) {\n CCTK_VInfo(CCTK_THORNSTRING,\"Convert_to_HydroBase WARNING: Found superluminal velocity. This should have been caught by IllinoisGRMHD.\");\n }\n\n // A = 1.0-one_minus_one_over_alpha_u0_squared = 1-(1-1/(al u0)^2) = 1/(al u0)^2\n // 1/sqrt(A) = al u0\n CCTK_REAL alpha_u0 = 1.0/sqrt(1.0-one_minus_one_over_alpha_u0_squared);\n if(std::isnan(alpha_u0*lapseL_inv)) printf(\"BAD FOUND NAN ALPHAU0 CALC: %.15e %.15e %.15e\\n\",alpha_u0,lapseL_inv,one_minus_one_over_alpha_u0_squared);\n\n w_lorentz[index] = alpha_u0;\n\n Bvec[CCTK_GFINDEX4D(cctkGH,i,j,k,0)] = PRIMS[BX_CENTER];\n Bvec[CCTK_GFINDEX4D(cctkGH,i,j,k,1)] = PRIMS[BY_CENTER];\n Bvec[CCTK_GFINDEX4D(cctkGH,i,j,k,2)] = PRIMS[BZ_CENTER];\n\n }\n}\n\n```\n\n Appending to ../Convert_to_HydroBase/src/Convert_to_HydroBase.C\n\n\n\n\n# Step 2: The `param.ccl` file \\[Back to [top](#toc)\\]\n$$\\label{convert_to_hydrobase__param}$$\n\nThe `param.ccl` file sets up parameters that are used by the `Convert_to_HydroBase` ETK thorn. These parameters are accessed as globals after calling the `DECLARE_CCTK_PARAMETERS` macro.\n\nWhen declaring a parameter, we have the following notation\n\n
\nTYPE name \"Comment\" STEERABLE=?\n{\nminimum allowed value:maximum allowed value :: \"Comment\"\nother possible value #1                     :: \"Comment\"\nother possible value #2                     :: \"Comment\"\n         ...                                ::    ...\nfinal possible value                        :: \"Comment\"\n} Default value\n
\n\n\nThe *STEERABLE* option is either set to never (default value, for which the keyword is not necessary at all) or to ALWAYS, which allows for the value of the parameter to change after set to its initial value. For example, when declaring the $\\Gamma_{\\rm th}$ parameter below, we have\n\n
\nREAL Gamma_th \"thermal gamma parameter\"\n{\n 0:* :: \"Physical values\"\n-1   :: \"forbidden value to make sure it is explicitly set in the parfile\"\n} -1\n
\n\n\nThis declares the *REAL* (usually a macro for double) $\\Gamma_{\\rm th}$ parameter as ${\\rm Gamma\\_th}$. We allow this parameter to have only positive values, hence the notation `0:*`. The asterisk means \"any positive value is allowed\". The notation `*:*` then means \"any value is allowed. The second line above sets the value \"$-1$\" to be a forbidden value, which if read after the code starts would produce an error saying that this value has not been initialized properly. Finally, the default value of the variable is set to \"$-1$\", the forbidden value. Because the STEERABLE keyword is not explicitly set to ALWAYS above, this means that once set, the value of $\\Gamma_{\\rm th}$ cannot be changed.\n\nThe `shares: THORN` syntax tells the ETK that the `Convert_to_HydroBase` thorn will share the parameters from the `THORN` thorn. For example, the following code\n\n
\nshares: ADMBase\nUSES CCTK_INT lapse_timelevels \nUSES CCTK_INT shift_timelevels \nUSES CCTK_INT metric_timelevels \n
\n\nwill tell the ETK that the variables `lapse_timelevels`, `shift_timelevels`, and `metric_timelevels` from the [ADMBase ETK thorn](http://einsteintoolkit.org/thornguide/EinsteinBase/ADMBase/documentation.html) should also be available for the `Convert_to_HydroBase` thorn once the `DECLARE_CCTK_PARAMETERS` macro has been executed.\n\nFor more details on how to build a `param.ccl` file, please refer to the [official Cactus documentation](https://einsteintoolkit.org/usersguide/UsersGuidech12.html).\n\n\n```python\n%%writefile $basedir/param.ccl\n# Parameter definitions for thorn convert_to_HydroBase\n# $Header:$\n\n#############################################################################\n### import HydroBase & ADMBase parameters\n\nshares: HydroBase\nUSES CCTK_INT timelevels\n\nshares: ADMBase\nUSES CCTK_INT lapse_timelevels\nUSES CCTK_INT shift_timelevels\nUSES CCTK_INT metric_timelevels\n\nshares: IllinoisGRMHD\nUSES KEYWORD neos\nUSES KEYWORD Gamma_th\nUSES KEYWORD K_ppoly_tab0\nUSES KEYWORD rho_ppoly_tab_in[10]\nUSES KEYWORD Gamma_ppoly_tab_in[10]\n#############################################################################\n\nprivate:\nINT Convert_to_HydroBase_every \"How often to convert IllinoisGRMHD primitive variables to HydroBase (Valencia formulation) primitive variables? Needed for some ET-based diagnostics. NOT needed for pure IllinoisGRMHD runs.\"\n{\n 0:* :: \"zero (disable) or positive (every N iterations)\"\n} 0\n\n\n```\n\n Overwriting ../Convert_to_HydroBase/param.ccl\n\n\n\n\n# Step 3: The `interface.ccl` file \\[Back to [top](#toc)\\]\n$$\\label{convert_to_hydrobase__interface}$$\n\n\nThe `interface.ccl` file sets up a few different things of how `Convert_to_HydroBase` interfaces with the rest of the toolkit. For starters, it tells which thorns are used by `Convert_to_HydroBase`, which is done using the keyword `inherits`.\n\nIt also requests to use files from different thorns using the `uses include header: HEADER_FILE.h` command.\n\nFor more details on how to build a `interface.ccl` file, please refer to the [official Cactus documentation](https://einsteintoolkit.org/usersguide/UsersGuidech12.html).\n\n\n```python\n%%writefile $basedir/interface.ccl\n# Interface definition for thorn Convert_to_HydroBase\n# $Header:$\n\nimplements: Convert_to_HydroBase\ninherits: grid HydroBase ADMBase IllinoisGRMHD\n\nuses include header: IllinoisGRMHD_headers.h\n\n\n```\n\n Overwriting ../Convert_to_HydroBase/interface.ccl\n\n\n\n\n# Step 4: The `schedule.ccl` file \\[Back to [top](#toc)\\]\n$$\\label{convert_to_hydrobase__schedule}$$\n\nThe `schedule.ccl` file sets up the structure of a given ETK run. It tells when the functions of `Convert_to_HydroBase` must be called and in what order. The general form of a scheduling is\n\n
\nschedule name IN thorn_name as alias after afunct_1 ... after afunct_n before bfunct_1 ... before bfunct_m\n{\nLANG:    function programming language\nOPTIONS: options\nSYNC:    sync options\n} \"Comment\"\n
\n\nFollowing the notation above, the schedule keyword sets up the function whose name is name defined IN the ETK thorn thorn_name. We are also allowed to set an alias, if the function name is too long, but this is optional. We then set exactly when the function should be called, i.e. by saying it should be called before and/or after other functions.\n\nInside curly braces, we set up the programming language of the function, e.g. C, options, e.g. LOCAL, and whether or not variables need to be synchronized with other functions. Finally, one can place a commend outside the curly braces, explaining the schedule just implemented.\n\nFor more details on how to build a `schedule.ccl` file, please refer to the [official Cactus documentation](https://einsteintoolkit.org/usersguide/UsersGuidech12.html).\n\n\n```python\n%%writefile $basedir/schedule.ccl\n# Schedule definitions for thorn Convert_to_HydroBase\n# $Header:$\n\nSCHEDULE Convert_to_HydroBase AT CCTK_INITIAL AFTER SetTmunu\n{\n LANG: C\n} \"Convert IllinoisGRMHD-native variables to HydroBase\"\n\nSCHEDULE Convert_to_HydroBase AT CCTK_ANALYSIS BEFORE compute_bi_b2_Poyn_fluxET BEFORE particle_tracerET BEFORE VolumeIntegralGroup BEFORE convert_to_MHD_3velocity AFTER ML_BSSN_evolCalcGroup\n{\n OPTIONS: GLOBAL-EARLY,LOOP-LOCAL\n LANG: C\n} \"Convert IllinoisGRMHD-native variables to HydroBase\"\n\n\n```\n\n Overwriting ../Convert_to_HydroBase/schedule.ccl\n\n\n\n\n# Step 5: The `make.code.defn` file \\[Back to [top](#toc)\\]\n$$\\label{convert_to_hydrobase__make}$$\n\nThe `make.code.defn` file tells the toolkit which files should be compiled during the ETK build.\n\n\n```python\n%%writefile $srcdir/make.code.defn\n# Main make.code.defn file for thorn Convert_to_HydroBase\n# $Header:$\n\n# Source files in this directory\nSRCS = Convert_to_HydroBase.C\n\n# Subdirectories containing source files\nSUBDIRS = \n\n\n```\n\n Overwriting ../Convert_to_HydroBase/src/make.code.defn\n\n\n\n\n# Step 6: Code validation \\[Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/A_i_rhs_no_gauge_terms.C\"\n# original_IGM_file_name = \"A_i_rhs_no_gauge_terms-original.C\"\n# original_IGM_file_path = os.path.join(IGM_src_dir_path,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__A_i_rhs_no_gauge_terms__C = !diff $original_IGM_file_path $outfile_path__A_i_rhs_no_gauge_terms__C\n\n# if Validation__A_i_rhs_no_gauge_terms__C == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for A_i_rhs_no_gauge_terms.C: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for A_i_rhs_no_gauge_terms.C: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__A_i_rhs_no_gauge_terms__C:\n# print(diff_line)\n```\n\n\n\n# Step 7: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.pdf](Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means).\n\n\n```python\nlatex_nrpy_style_path = os.path.join(nrpy_dir_path,\"latex_nrpy_style.tplx\")\n#!jupyter nbconvert --to latex --template $latex_nrpy_style_path --log-level='WARN' Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.ipynb\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.tex\n!rm -f Tut*.out Tut*.aux Tut*.log\n```\n", "meta": {"hexsha": "3ea6798eb62075b1f9d437a78c0bada4fc1f23f8", "size": 34202, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.ipynb", "max_stars_repo_name": "leowerneck/NRPyIGM", "max_stars_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.ipynb", "max_issues_repo_name": "leowerneck/NRPyIGM", "max_issues_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__ETKThorn__Convert_to_HydroBase.ipynb", "max_forks_repo_name": "leowerneck/NRPyIGM", "max_forks_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.6635514019, "max_line_length": 723, "alphanum_fraction": 0.5763113268, "converted": true, "num_tokens": 7734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5, "lm_q1q2_score": 0.34962721052937923}} {"text": "\n\n# Tutorial 1: Learn how to use modern convnets\n\n**Week 2, Day 2: Modern Convnets**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Laura Pede, Richard Vogg, Marissa Weis, Timo Lüddecke, Alexander Ecker (based on an initial version by Ben Heil)\n\n__Content reviewers:__ Arush Tagade, Polina Turishcheva, Yu-Fang Yang, Bettina Hein, Melvin Selim Atay, Kelson Shilling-Scrivo\n\n__Content editors:__ Roberto Guidotti, Spiros Chavlis\n\n__Production editors:__ Anoop Kulkarni, Roberto Guidotti, Cary Murray, Spiros Chavlis\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n---\n# Tutorial Objectives\n\nIn this tutorial we are going to learn more about Convnets. More specifically, we will:\n\n1. Learn about modern CNNs and Transfer Learning.\n2. Understand how architectures incorporate ideas we have about the world.\n3. Understand the operating principles underlying the basic building blocks of modern CNNs.\n4. Understand the concept of transfer learning and learn to recognize opportunities for applying it.\n5. (Bonus) Understand the speed vs. accuracy trade-off.\n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorial\n\n# @markdown If you want to download locally the slides, click [here](https://osf.io/tzfsn/download)\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/tzfsn/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n# Setup\n\n\n```python\n# @title Install dependencies\n!pip install Pillow --quiet\n\n!pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet\nfrom evaltools.airtable import AirtableForm\n\n# generate airtable form\natform = AirtableForm('appn7VdPRseSoMXEG','W2D2_T1','https://portal.neuromatchacademy.org/api/redirect/to/96ec754b-e76b-43f7-903e-76df0ac63749')\n```\n\n\n```python\n# Import libraries\nimport os\nimport time\nimport tqdm\nimport torch\nimport IPython\nimport torchvision\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torchvision import transforms\nfrom torchvision.models import AlexNet\nfrom torchvision.utils import make_grid\nfrom torchvision.datasets import ImageFolder\n\nfrom PIL import Image\nfrom io import BytesIO\n```\n\n\n```python\n# @title Figure settings\nimport ipywidgets as widgets # interactive display\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\nimport torch\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n# especially if torch modules used.\n\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nSEED = 2021\nset_seed(seed=SEED)\nDEVICE = set_device()\n```\n\n---\n# Section 1: Modern CNNs and Transfer Learning\n\n*Time estimate: ~25mins*\n\n\n```python\n# @title Video 1: Modern CNNs and Transfer Learning\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Wf4y157wE\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"mfOd2EKzscM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 1: Modern CNNs and Transfer Learning')\n\ndisplay(out)\n```\n\nImages are high dimensional. That is to say that `image_length` * `image_width` * `image_channels` is a big number, and multiplying that big number by a normal sized fully-connected layer leads to a ton of parameters to learn. Yesterday, we learned about convolutional neural networks, one way of working around high dimensionality in images and other domains. \n\nThe widget below (i.e., *Interactive Demo 1*) calculates the parameters required for a single convolutional or fully connected layer that operates on an image of a certain height and width.\n\nRecall that, the number of parameters of a convolutional layer $l$ are calculated as:\n\n\\begin{equation}\n\\text{num_of_params}_l = \\left[ \\left( H \\times W \\times K_{l-1} \\right) + 1 \\right] \\times K_l\n\\end{equation}\n\nwhere $H$ denotes the shape of the height of the filter, $W$ the shape of the width of the filter, and $K_l$ denotes the number of the filters in the $l$-th layer. The added $1$ is because of the bias term for each filter.\n\n\nWhile a fully connected layer contains:\n\n\\begin{equation}\n\\text{num_of_params}_l = \\left[ \\left( N_{l-1} \\times N_l \\right) + 1 \\times N_l \\right]\n\\end{equation}\n\nwhere $N_l$ denotes the number of nodes in the $l$-th layer.\n\n\nAdjust the sliders to gain an intuition for how different model and data characteristics affect the number of parameters your model need to fit.\n\nNote: these classes are designed to show parameter scaling in the first layer of a network, to be actually useful they would need more layers, an activation function, etc.\n\n\n```python\nclass FullyConnectedNet(nn.Module):\n def __init__(self):\n super(FullyConnectedNet, self).__init__()\n\n image_width = 128\n image_channels = 3\n self.input_size = image_channels * image_width ** 2\n\n self.fc1 = nn.Linear(self.input_size, 256)\n\n def forward(self, x):\n x = x.view(-1, self.input_size)\n return self.fc1(x)\n```\n\n\n```python\nclass ConvNet(nn.Module):\n def __init__(self):\n super(ConvNet, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=3,\n out_channels=256,\n kernel_size=(3, 3),\n padding=1)\n\n def forward(self, x):\n return self.conv1(x)\n```\n\n## Coding Exercise 1: Calculate number of parameters in FCNN vs ConvNet \n\nWrite a function that calculates the number of parameters of a given network. Apply the function to the above defined fully-connected network and convolutional network and compare the parameter counts.\n\n**Hint:** `torch.numel`\n\n\n```python\ndef get_parameter_count(network):\n \"\"\"\n Calculate the number of parameters used by the fully connected network.\n Hint: Casting the result of network.parameters() to a list may make it\n easier to work with\n\n Args:\n network: Network to calculate the parameters of\n\n Returns:\n param_count: The number of parameters in the network\n \"\"\"\n\n ####################################################################\n # Fill in all missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Convolution math\")\n ####################################################################\n # Get the network's parameters\n parameters = ...\n\n param_count = 0\n # Loop over all layers\n for layer in parameters:\n param_count += ...\n\n return param_count\n\n\n# add event to airtable\natform.add_event('Coding Exercise 1: Calculate number of parameters in FCNN vs ConvNet')\n\n# Initialize networks\nfccnet = FullyConnectedNet()\nconvnet = ConvNet()\n## Apply the above defined function to both networks by uncommenting the following lines\n# print(f\"FCCN parameter count: {get_parameter_count(fccnet)}\")\n# print(f\"ConvNet parameter count: {get_parameter_count(convnet)}\")\n```\n\n\n```python\n# to_remove solution\ndef get_parameter_count(network):\n \"\"\"\n Calculate the number of parameters used by the fully connected network.\n Hint: Casting the result of network.parameters() to a list may make it\n easier to work with\n\n Args:\n network: Network to calculate the parameters of\n\n Returns:\n param_count: The number of parameters in the network\n \"\"\"\n\n # Get the network's parameters\n parameters = network.parameters()\n\n param_count = 0\n # Loop over all layers\n for layer in parameters:\n param_count += torch.numel(layer)\n\n return param_count\n\n\n# add event to airtable\natform.add_event('Coding Exercise 1: Calculate number of parameters in FCNN vs ConvNet')\n\n# Initialize networks\nfccnet = FullyConnectedNet()\nconvnet = ConvNet()\n## Apply the above defined function to both networks by uncommenting the following lines\nprint(f\"FCCN parameter count: {get_parameter_count(fccnet)}\")\nprint(f\"ConvNet parameter count: {get_parameter_count(convnet)}\")\n```\n\n```\nFCCN parameter count: 12583168\nConvNet parameter count: 7168\n```\n\n## Interactive Demo 1: Check your results\nThe widget below calculates the number of parameters in a FCNN and CNN with the same architecture as our models above. Our models had an input image that was 128x128, and used 256 filters (or 256 nodes in the FCNN case). Check that the calculations you made above are correct.\n\nNote how few parameters the convolutional networks take, especially as you increase the input image size.\n\n\n```python\n# @title Parameter Calculator\n# @markdown Run this cell to enable the widget!\n\ndef calculate_parameters(filter_count, image_width, fcnn_nodes):\n # Convnet math: Implement how parameters scale as a function of image size\n # between convnets and FCNN\n\n filter_width = 3\n image_channels = 3\n\n # Assuming a square, RGB image\n image_area = image_width ** 2\n image_volume = image_area * image_channels\n\n # If we're using padding=same, the output of a convnet will be the same shape\n # as the original image, but with more features\n fcnn_parameters = image_volume * fcnn_nodes\n cnn_parameters = image_channels * filter_count * filter_width ** 2\n\n # Add bias\n fcnn_parameters += fcnn_nodes\n cnn_parameters += filter_count\n\n print(f\"CNN parameters: {cnn_parameters}\")\n print(f\"Fully Connected parameters: {fcnn_parameters}\")\n\n return None\n\n\n_ = widgets.interact(calculate_parameters,\n filter_count=(16, 512, 16),\n image_width=(16, 512, 16),\n fcnn_nodes=(16, 512, 16))\n```\n\n--- \n# Section 2: The History of Convnets\n\n*Time estimate: ~15mins*\n\nConvolutional neural networks have been around for a long time. [The first CNN model](https://www.rctn.org/bruno/public/papers/Fukushima1980.pdf) was published in 1980, and was based on ideas in neuroscience that [predated it by decades](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1359523/). Why is it then that [AlexNet](https://proceedings.neurips.cc/paper/2012/hash/c399862d3b9d6b76c8436e924a68c45b-Abstract.html), a CNN model published in 2012, is generally considered to mark the start of the deep learning revolution?\n\nWatch the video below to get a better idea of the role that hardware and the internet have played in progressing deep learning.\n\n\n```python\n# @title Video 2: History of convnets\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1364y167Qy\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"xtoLjKSPrUQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 2: History of convnets')\n\ndisplay(out)\n```\n\n## Think! 2: Challenges of improving CNNs\nAs we shall see today, the story of deep learning and CNNs has been one of scaling networks: making them bigger and deeper.\n\nBased on what you know so far from previous days, what challenges might researchers have faced when trying to scale up CNNs and applying them to different visual recognition tasks? Do you already have some ideas how these challenges might have been addressed?\n\nDiscuss this with your group for ~10 minutes.\n\n(Hint: labeled data, compute and memory are all finite)\n\n\n```python\n# @title Student Response\nfrom ipywidgets import widgets\n\n\ntext=widgets.Textarea(\n value='Type your answer here and click on `Submit!`',\n placeholder='Type something',\n description='',\n disabled=False\n)\n\nbutton = widgets.Button(description=\"Submit!\")\n\ndisplay(text,button)\n\ndef on_button_clicked(b):\n atform.add_answer('q1', text.value)\n print(\"Submission successful!\")\n\n\nbutton.on_click(on_button_clicked)\n```\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nChallenge 1: limited data / overfitting. Limited amount of labeled data for many tasks beyond ImageNet.\nLabels are expensive, for many tasks we don't have enough of them. --> Large networks will overfit.\n[Solution: transfer learning: adapt networks trained on ImageNet to other tasks]\n\nChallenge 2: hardware limitations. Making networks bigger/deeper will increase\ncompute and memory requirements. --> There are physical limits what can be done, and completed in reasonable time.\n[Solution: more efficient architectures than standard convolutions]\n\nChallenge 3: training deep networks \"out-of-the-box\" is unstable / training diverges\n[Solution:.1 mechanisms like batch normalization and architectures like ResNets]\n\nNOTE: Students cannot know any of the solutions to the problems from the material.\nThe intention of the question is to have them discuss and think about the\nchallenges (primarily the first two). The solutions are just provided for completeness for the tutors.\n\"\"\";\n```\n\n---\n# Section 3: Big and Deep Convnets\n\n*Time estimate: 18mins*\n\n\n```python\n# @title Video 3: AlexNet & VGG\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV12U4y1n7q5\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"ZB87qC7yPiE\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 3: AlexNet & VGG')\n\ndisplay(out)\n```\n\n## Section 3.1: Introduction to AlexNet\n\nAlexNet arguably marked the start of the current age of deep learning.\nIt incorporates a number of the defining characteristics of successful DL today: deep networks, GPU-powered paralellization, and building blocks encoding task-specific priors.\nIn this section you'll have the opportunity to play with AlexNet and see the world through its eyes.\n\n\n```python\n# @title Import Alexnet\n# @markdown This cell gives you the `alexnet` model as well as the `input_image` and `input_batch` variables used below\nimport requests, urllib\n\n# original link: https://s3.amazonaws.com/pytorch/models/alexnet-owt-4df8aa71.pth\nstate_dict = torch.hub.load_state_dict_from_url(\"https://osf.io/9dzeu/download\")\n\nalexnet = AlexNet()\nalexnet.load_state_dict(state_dict=state_dict)\n\nurl, filename = (\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W2D2_ModernConvnets/static/dog.jpg\", \"dog.jpg\")\ntry: urllib.URLopener().retrieve(url, filename)\nexcept: urllib.request.urlretrieve(url, filename)\n\ninput_image = Image.open(filename)\npreprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\ninput_tensor = preprocess(input_image)\ninput_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model\n\n# move the input and model to GPU for speed if available\nif torch.cuda.is_available():\n input_batch = input_batch.cuda()\n alexnet.cuda()\n```\n\n## Section 3.2: What does AlexNet learn?\nThis code visualizes the top-layer filters learned by AlexNet.\nWhat do these filters remind you of?\n\n\n```python\nwith torch.no_grad():\n params = list(alexnet.parameters())\n fig, axs = plt.subplots(8, 8, figsize=(8, 8))\n filters = []\n for filter_index in range(params[0].shape[0]):\n row_index = filter_index // 8\n col_index = filter_index % 8\n\n filter = params[0][filter_index,:,:,:]\n filter_image = filter.permute(1, 2, 0).cpu()\n scale = np.abs(filter_image).max()\n scaled_image = filter_image / (2 * scale) + 0.5\n filters.append(scaled_image.cpu())\n axs[row_index, col_index].imshow(scaled_image.cpu())\n axs[row_index, col_index].axis('off')\n plt.show()\n```\n\n### Think! 3.2.1: Filter Similarity\n\nWhat do these filters remind you of?\n\n\n```python\n# @title Student Response\nfrom ipywidgets import widgets\n\n\ntext=widgets.Textarea(\n value='Type your answer here and click on `Submit!`',\n placeholder='Type something',\n description='',\n disabled=False\n)\n\nbutton = widgets.Button(description=\"Submit!\")\n\ndisplay(text,button)\n\ndef on_button_clicked(b):\n atform.add_answer('q2', text.value)\n print(\"Submission successful!\")\n\n\nbutton.on_click(on_button_clicked)\n```\n\n\n```python\n# to_remove explanation\n\"\"\"\nSome of the filters look like edge detectors, as they are color insensitive and consist of vertical or horizontal patterns.\n\"\"\";\n```\n\n### Interactive Demo 3.2: What does AlexNet see?\nOne way of visualizing CNNs is to look at the output of individual filters for a given image. Below is a widget that lets you examine the outputs of various filters used in AlexNet.\n\n\n```python\n# @title Image Widget Code\n# @markdown Run this cell to enable the widget\n\ndef alexnet_intermediate_output(net, image):\n return F.relu(net.features[0](image))\n\n\ndef browse_images(input_batch, input_image):\n intermediate_output = alexnet_intermediate_output(alexnet, input_batch)\n n = intermediate_output.shape[1]\n\n def view_image(i):\n with torch.no_grad():\n channel = intermediate_output[0, i, :].squeeze()\n fig, ax = plt.subplots(1, 3, figsize=(18, 6))\n ax[0].imshow(input_image)\n ax[1].imshow(filters[i])\n ax[1].set_xlim([-22, 33])\n ax[2].imshow(channel.cpu())\n ax[0].set_title('Input image')\n ax[1].set_title(f\"Filter {i}\")\n ax[2].set_title(f\"Filter {i} on input image\")\n [axi.set_axis_off() for axi in ax.ravel()]\n\n widgets.interact(view_image, i=(0, n-1))\n\n\nbrowse_images(input_batch, input_image)\n```\n\n### Think! 3.2.2 Filter Purpose\nWhat do these filters appear to be doing? Note that different filters play different roles so there are several good answers.\n\n\n```python\n# @title Student Response\nfrom ipywidgets import widgets\n\n\ntext=widgets.Textarea(\n value='Type your answer here and click on `Submit!`',\n placeholder='Type something',\n description='',\n disabled=False\n)\n\nbutton = widgets.Button(description=\"Submit!\")\n\ndisplay(text,button)\n\ndef on_button_clicked(b):\n atform.add_answer('q3', text.value)\n print(\"Submission successful!\")\n\n\nbutton.on_click(on_button_clicked)\n```\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nBased on the areas that are highlighted in the outupt, some filters seem to be detecting edges,\nwhile others seem to react to the white color of the dog or the green of the background.\n\"\"\";\n```\n\n## Further Reading\nIf the question \"what are neural network filters looking for\" is at all interesting to you, or if you like geometric art, you'll enjoy [this post](https://distill.pub/2017/feature-visualization/) creating images that maximize output of various CNN neurons. There is also a good article showing what the space of images looks like as models train [here](https://distill.pub/2020/grand-tour/).\n\n---\n# Section 4: Convnets After AlexNet\n\n*Time estimate: ~25mins*\n\n\n```python\n# @title Video 4: Residual Networks (ResNets)\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1bf4y1j7od\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"EJSZnJyy4PI\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 4: Residual Networks (ResNets)')\n\ndisplay(out)\n```\n\nIn this section we'll be working with a state of the art CNN model called [ResNet](https://arxiv.org/abs/1512.03385). ResNet has two particularly interesting features. First, it uses skip connections to avoid the vanishing gradient problem. Second, each block (collection of layers) in a ResNet can be treated as learning a residual function.\n\nMathematically, a neural network can be thought of as a series of operations that maps an input (like an image of a dog) to an output (like the label \"dog\"). In math-speak a mapping from an input to an output is called a function. Neural networks are a flexible way of expressing that function. \n\nIf you were to subtract out the true function mapping images to class labels from the function learned by a network, you'd be left with the residual error or \"residual function\". ResNets try to learn the original function, then the residual function, then the residual of the residual, and so on, using their residual blocks and adding them to the output of the preceeding layers.\n\nIn this section we'll run several images through a pre-trained ResNet and see what happens.\n\n\n```python\n# @title Download imagenette\nimport requests, tarfile, os\n\nfname = 'imagenette2-320'\nurl = 'https://osf.io/mnve4/download'\n\nif not os.path.exists(fname):\n print(\"Data is being downloaded...\")\n r = requests.get(url, stream=True)\n with open(fname+'tgz', 'wb') as fd:\n fd.write(r.content)\n\n with tarfile.open(fname+'tgz', \"r\") as ft:\n ft.extractall()\n\n os.remove(fname+'tgz')\n print(\"The download has been completed.\")\nelse:\n print(\"Data has already been downloaded.\")\n```\n\n\n```python\n# @title Set Up Textual ImageNet labels\ndict_map={0: 'tench, Tinca tinca',\n 1: 'goldfish, Carassius auratus',\n 2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',\n 3: 'tiger shark, Galeocerdo cuvieri',\n 4: 'hammerhead, hammerhead shark',\n 5: 'electric ray, crampfish, numbfish, torpedo',\n 6: 'stingray',\n 7: 'cock',\n 8: 'hen',\n 9: 'ostrich, Struthio camelus',\n 10: 'brambling, Fringilla montifringilla',\n 11: 'goldfinch, Carduelis carduelis',\n 12: 'house finch, linnet, Carpodacus mexicanus',\n 13: 'junco, snowbird',\n 14: 'indigo bunting, indigo finch, indigo bird, Passerina cyanea',\n 15: 'robin, American robin, Turdus migratorius',\n 16: 'bulbul',\n 17: 'jay',\n 18: 'magpie',\n 19: 'chickadee',\n 20: 'water ouzel, dipper',\n 21: 'kite',\n 22: 'bald eagle, American eagle, Haliaeetus leucocephalus',\n 23: 'vulture',\n 24: 'great grey owl, great gray owl, Strix nebulosa',\n 25: 'European fire salamander, Salamandra salamandra',\n 26: 'common newt, Triturus vulgaris',\n 27: 'eft',\n 28: 'spotted salamander, Ambystoma maculatum',\n 29: 'axolotl, mud puppy, Ambystoma mexicanum',\n 30: 'bullfrog, Rana catesbeiana',\n 31: 'tree frog, tree-frog',\n 32: 'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',\n 33: 'loggerhead, loggerhead turtle, Caretta caretta',\n 34: 'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea',\n 35: 'mud turtle',\n 36: 'terrapin',\n 37: 'box turtle, box tortoise',\n 38: 'banded gecko',\n 39: 'common iguana, iguana, Iguana iguana',\n 40: 'American chameleon, anole, Anolis carolinensis',\n 41: 'whiptail, whiptail lizard',\n 42: 'agama',\n 43: 'frilled lizard, Chlamydosaurus kingi',\n 44: 'alligator lizard',\n 45: 'Gila monster, Heloderma suspectum',\n 46: 'green lizard, Lacerta viridis',\n 47: 'African chameleon, Chamaeleo chamaeleon',\n 48: 'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis',\n 49: 'African crocodile, Nile crocodile, Crocodylus niloticus',\n 50: 'American alligator, Alligator mississipiensis',\n 51: 'triceratops',\n 52: 'thunder snake, worm snake, Carphophis amoenus',\n 53: 'ringneck snake, ring-necked snake, ring snake',\n 54: 'hognose snake, puff adder, sand viper',\n 55: 'green snake, grass snake',\n 56: 'king snake, kingsnake',\n 57: 'garter snake, grass snake',\n 58: 'water snake',\n 59: 'vine snake',\n 60: 'night snake, Hypsiglena torquata',\n 61: 'boa constrictor, Constrictor constrictor',\n 62: 'rock python, rock snake, Python sebae',\n 63: 'Indian cobra, Naja naja',\n 64: 'green mamba',\n 65: 'sea snake',\n 66: 'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',\n 67: 'diamondback, diamondback rattlesnake, Crotalus adamanteus',\n 68: 'sidewinder, horned rattlesnake, Crotalus cerastes',\n 69: 'trilobite',\n 70: 'harvestman, daddy longlegs, Phalangium opilio',\n 71: 'scorpion',\n 72: 'black and gold garden spider, Argiope aurantia',\n 73: 'barn spider, Araneus cavaticus',\n 74: 'garden spider, Aranea diademata',\n 75: 'black widow, Latrodectus mactans',\n 76: 'tarantula',\n 77: 'wolf spider, hunting spider',\n 78: 'tick',\n 79: 'centipede',\n 80: 'black grouse',\n 81: 'ptarmigan',\n 82: 'ruffed grouse, partridge, Bonasa umbellus',\n 83: 'prairie chicken, prairie grouse, prairie fowl',\n 84: 'peacock',\n 85: 'quail',\n 86: 'partridge',\n 87: 'African grey, African gray, Psittacus erithacus',\n 88: 'macaw',\n 89: 'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',\n 90: 'lorikeet',\n 91: 'coucal',\n 92: 'bee eater',\n 93: 'hornbill',\n 94: 'hummingbird',\n 95: 'jacamar',\n 96: 'toucan',\n 97: 'drake',\n 98: 'red-breasted merganser, Mergus serrator',\n 99: 'goose',\n 100: 'black swan, Cygnus atratus',\n 101: 'tusker',\n 102: 'echidna, spiny anteater, anteater',\n 103: 'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus',\n 104: 'wallaby, brush kangaroo',\n 105: 'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus',\n 106: 'wombat',\n 107: 'jellyfish',\n 108: 'sea anemone, anemone',\n 109: 'brain coral',\n 110: 'flatworm, platyhelminth',\n 111: 'nematode, nematode worm, roundworm',\n 112: 'conch',\n 113: 'snail',\n 114: 'slug',\n 115: 'sea slug, nudibranch',\n 116: 'chiton, coat-of-mail shell, sea cradle, polyplacophore',\n 117: 'chambered nautilus, pearly nautilus, nautilus',\n 118: 'Dungeness crab, Cancer magister',\n 119: 'rock crab, Cancer irroratus',\n 120: 'fiddler crab',\n 121: 'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica',\n 122: 'American lobster, Northern lobster, Maine lobster, Homarus americanus',\n 123: 'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish',\n 124: 'crayfish, crawfish, crawdad, crawdaddy',\n 125: 'hermit crab',\n 126: 'isopod',\n 127: 'white stork, Ciconia ciconia',\n 128: 'black stork, Ciconia nigra',\n 129: 'spoonbill',\n 130: 'flamingo',\n 131: 'little blue heron, Egretta caerulea',\n 132: 'American egret, great white heron, Egretta albus',\n 133: 'bittern',\n 134: 'crane',\n 135: 'limpkin, Aramus pictus',\n 136: 'European gallinule, Porphyrio porphyrio',\n 137: 'American coot, marsh hen, mud hen, water hen, Fulica americana',\n 138: 'bustard',\n 139: 'ruddy turnstone, Arenaria interpres',\n 140: 'red-backed sandpiper, dunlin, Erolia alpina',\n 141: 'redshank, Tringa totanus',\n 142: 'dowitcher',\n 143: 'oystercatcher, oyster catcher',\n 144: 'pelican',\n 145: 'king penguin, Aptenodytes patagonica',\n 146: 'albatross, mollymawk',\n 147: 'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus',\n 148: 'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',\n 149: 'dugong, Dugong dugon',\n 150: 'sea lion',\n 151: 'Chihuahua',\n 152: 'Japanese spaniel',\n 153: 'Maltese dog, Maltese terrier, Maltese',\n 154: 'Pekinese, Pekingese, Peke',\n 155: 'Shih-Tzu',\n 156: 'Blenheim spaniel',\n 157: 'papillon',\n 158: 'toy terrier',\n 159: 'Rhodesian ridgeback',\n 160: 'Afghan hound, Afghan',\n 161: 'basset, basset hound',\n 162: 'beagle',\n 163: 'bloodhound, sleuthhound',\n 164: 'bluetick',\n 165: 'black-and-tan coonhound',\n 166: 'Walker hound, Walker foxhound',\n 167: 'English foxhound',\n 168: 'redbone',\n 169: 'borzoi, Russian wolfhound',\n 170: 'Irish wolfhound',\n 171: 'Italian greyhound',\n 172: 'whippet',\n 173: 'Ibizan hound, Ibizan Podenco',\n 174: 'Norwegian elkhound, elkhound',\n 175: 'otterhound, otter hound',\n 176: 'Saluki, gazelle hound',\n 177: 'Scottish deerhound, deerhound',\n 178: 'Weimaraner',\n 179: 'Staffordshire bullterrier, Staffordshire bull terrier',\n 180: 'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier',\n 181: 'Bedlington terrier',\n 182: 'Border terrier',\n 183: 'Kerry blue terrier',\n 184: 'Irish terrier',\n 185: 'Norfolk terrier',\n 186: 'Norwich terrier',\n 187: 'Yorkshire terrier',\n 188: 'wire-haired fox terrier',\n 189: 'Lakeland terrier',\n 190: 'Sealyham terrier, Sealyham',\n 191: 'Airedale, Airedale terrier',\n 192: 'cairn, cairn terrier',\n 193: 'Australian terrier',\n 194: 'Dandie Dinmont, Dandie Dinmont terrier',\n 195: 'Boston bull, Boston terrier',\n 196: 'miniature schnauzer',\n 197: 'giant schnauzer',\n 198: 'standard schnauzer',\n 199: 'Scotch terrier, Scottish terrier, Scottie',\n 200: 'Tibetan terrier, chrysanthemum dog',\n 201: 'silky terrier, Sydney silky',\n 202: 'soft-coated wheaten terrier',\n 203: 'West Highland white terrier',\n 204: 'Lhasa, Lhasa apso',\n 205: 'flat-coated retriever',\n 206: 'curly-coated retriever',\n 207: 'golden retriever',\n 208: 'Labrador retriever',\n 209: 'Chesapeake Bay retriever',\n 210: 'German short-haired pointer',\n 211: 'vizsla, Hungarian pointer',\n 212: 'English setter',\n 213: 'Irish setter, red setter',\n 214: 'Gordon setter',\n 215: 'Brittany spaniel',\n 216: 'clumber, clumber spaniel',\n 217: 'English springer, English springer spaniel',\n 218: 'Welsh springer spaniel',\n 219: 'cocker spaniel, English cocker spaniel, cocker',\n 220: 'Sussex spaniel',\n 221: 'Irish water spaniel',\n 222: 'kuvasz',\n 223: 'schipperke',\n 224: 'groenendael',\n 225: 'malinois',\n 226: 'briard',\n 227: 'kelpie',\n 228: 'komondor',\n 229: 'Old English sheepdog, bobtail',\n 230: 'Shetland sheepdog, Shetland sheep dog, Shetland',\n 231: 'collie',\n 232: 'Border collie',\n 233: 'Bouvier des Flandres, Bouviers des Flandres',\n 234: 'Rottweiler',\n 235: 'German shepherd, German shepherd dog, German police dog, alsatian',\n 236: 'Doberman, Doberman pinscher',\n 237: 'miniature pinscher',\n 238: 'Greater Swiss Mountain dog',\n 239: 'Bernese mountain dog',\n 240: 'Appenzeller',\n 241: 'EntleBucher',\n 242: 'boxer',\n 243: 'bull mastiff',\n 244: 'Tibetan mastiff',\n 245: 'French bulldog',\n 246: 'Great Dane',\n 247: 'Saint Bernard, St Bernard',\n 248: 'Eskimo dog, husky',\n 249: 'malamute, malemute, Alaskan malamute',\n 250: 'Siberian husky',\n 251: 'dalmatian, coach dog, carriage dog',\n 252: 'affenpinscher, monkey pinscher, monkey dog',\n 253: 'basenji',\n 254: 'pug, pug-dog',\n 255: 'Leonberg',\n 256: 'Newfoundland, Newfoundland dog',\n 257: 'Great Pyrenees',\n 258: 'Samoyed, Samoyede',\n 259: 'Pomeranian',\n 260: 'chow, chow chow',\n 261: 'keeshond',\n 262: 'Brabancon griffon',\n 263: 'Pembroke, Pembroke Welsh corgi',\n 264: 'Cardigan, Cardigan Welsh corgi',\n 265: 'toy poodle',\n 266: 'miniature poodle',\n 267: 'standard poodle',\n 268: 'Mexican hairless',\n 269: 'timber wolf, grey wolf, gray wolf, Canis lupus',\n 270: 'white wolf, Arctic wolf, Canis lupus tundrarum',\n 271: 'red wolf, maned wolf, Canis rufus, Canis niger',\n 272: 'coyote, prairie wolf, brush wolf, Canis latrans',\n 273: 'dingo, warrigal, warragal, Canis dingo',\n 274: 'dhole, Cuon alpinus',\n 275: 'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',\n 276: 'hyena, hyaena',\n 277: 'red fox, Vulpes vulpes',\n 278: 'kit fox, Vulpes macrotis',\n 279: 'Arctic fox, white fox, Alopex lagopus',\n 280: 'grey fox, gray fox, Urocyon cinereoargenteus',\n 281: 'tabby, tabby cat',\n 282: 'tiger cat',\n 283: 'Persian cat',\n 284: 'Siamese cat, Siamese',\n 285: 'Egyptian cat',\n 286: 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',\n 287: 'lynx, catamount',\n 288: 'leopard, Panthera pardus',\n 289: 'snow leopard, ounce, Panthera uncia',\n 290: 'jaguar, panther, Panthera onca, Felis onca',\n 291: 'lion, king of beasts, Panthera leo',\n 292: 'tiger, Panthera tigris',\n 293: 'cheetah, chetah, Acinonyx jubatus',\n 294: 'brown bear, bruin, Ursus arctos',\n 295: 'American black bear, black bear, Ursus americanus, Euarctos americanus',\n 296: 'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',\n 297: 'sloth bear, Melursus ursinus, Ursus ursinus',\n 298: 'mongoose',\n 299: 'meerkat, mierkat',\n 300: 'tiger beetle',\n 301: 'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',\n 302: 'ground beetle, carabid beetle',\n 303: 'long-horned beetle, longicorn, longicorn beetle',\n 304: 'leaf beetle, chrysomelid',\n 305: 'dung beetle',\n 306: 'rhinoceros beetle',\n 307: 'weevil',\n 308: 'fly',\n 309: 'bee',\n 310: 'ant, emmet, pismire',\n 311: 'grasshopper, hopper',\n 312: 'cricket',\n 313: 'walking stick, walkingstick, stick insect',\n 314: 'cockroach, roach',\n 315: 'mantis, mantid',\n 316: 'cicada, cicala',\n 317: 'leafhopper',\n 318: 'lacewing, lacewing fly',\n 319: \"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk\",\n 320: 'damselfly',\n 321: 'admiral',\n 322: 'ringlet, ringlet butterfly',\n 323: 'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',\n 324: 'cabbage butterfly',\n 325: 'sulphur butterfly, sulfur butterfly',\n 326: 'lycaenid, lycaenid butterfly',\n 327: 'starfish, sea star',\n 328: 'sea urchin',\n 329: 'sea cucumber, holothurian',\n 330: 'wood rabbit, cottontail, cottontail rabbit',\n 331: 'hare',\n 332: 'Angora, Angora rabbit',\n 333: 'hamster',\n 334: 'porcupine, hedgehog',\n 335: 'fox squirrel, eastern fox squirrel, Sciurus niger',\n 336: 'marmot',\n 337: 'beaver',\n 338: 'guinea pig, Cavia cobaya',\n 339: 'sorrel',\n 340: 'zebra',\n 341: 'hog, pig, grunter, squealer, Sus scrofa',\n 342: 'wild boar, boar, Sus scrofa',\n 343: 'warthog',\n 344: 'hippopotamus, hippo, river horse, Hippopotamus amphibius',\n 345: 'ox',\n 346: 'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',\n 347: 'bison',\n 348: 'ram, tup',\n 349: 'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis',\n 350: 'ibex, Capra ibex',\n 351: 'hartebeest',\n 352: 'impala, Aepyceros melampus',\n 353: 'gazelle',\n 354: 'Arabian camel, dromedary, Camelus dromedarius',\n 355: 'llama',\n 356: 'weasel',\n 357: 'mink',\n 358: 'polecat, fitch, foulmart, foumart, Mustela putorius',\n 359: 'black-footed ferret, ferret, Mustela nigripes',\n 360: 'otter',\n 361: 'skunk, polecat, wood pussy',\n 362: 'badger',\n 363: 'armadillo',\n 364: 'three-toed sloth, ai, Bradypus tridactylus',\n 365: 'orangutan, orang, orangutang, Pongo pygmaeus',\n 366: 'gorilla, Gorilla gorilla',\n 367: 'chimpanzee, chimp, Pan troglodytes',\n 368: 'gibbon, Hylobates lar',\n 369: 'siamang, Hylobates syndactylus, Symphalangus syndactylus',\n 370: 'guenon, guenon monkey',\n 371: 'patas, hussar monkey, Erythrocebus patas',\n 372: 'baboon',\n 373: 'macaque',\n 374: 'langur',\n 375: 'colobus, colobus monkey',\n 376: 'proboscis monkey, Nasalis larvatus',\n 377: 'marmoset',\n 378: 'capuchin, ringtail, Cebus capucinus',\n 379: 'howler monkey, howler',\n 380: 'titi, titi monkey',\n 381: 'spider monkey, Ateles geoffroyi',\n 382: 'squirrel monkey, Saimiri sciureus',\n 383: 'Madagascar cat, ring-tailed lemur, Lemur catta',\n 384: 'indri, indris, Indri indri, Indri brevicaudatus',\n 385: 'Indian elephant, Elephas maximus',\n 386: 'African elephant, Loxodonta africana',\n 387: 'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',\n 388: 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',\n 389: 'barracouta, snoek',\n 390: 'eel',\n 391: 'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch',\n 392: 'rock beauty, Holocanthus tricolor',\n 393: 'anemone fish',\n 394: 'sturgeon',\n 395: 'gar, garfish, garpike, billfish, Lepisosteus osseus',\n 396: 'lionfish',\n 397: 'puffer, pufferfish, blowfish, globefish',\n 398: 'abacus',\n 399: 'abaya',\n 400: \"academic gown, academic robe, judge's robe\",\n 401: 'accordion, piano accordion, squeeze box',\n 402: 'acoustic guitar',\n 403: 'aircraft carrier, carrier, flattop, attack aircraft carrier',\n 404: 'airliner',\n 405: 'airship, dirigible',\n 406: 'altar',\n 407: 'ambulance',\n 408: 'amphibian, amphibious vehicle',\n 409: 'analog clock',\n 410: 'apiary, bee house',\n 411: 'apron',\n 412: 'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin',\n 413: 'assault rifle, assault gun',\n 414: 'backpack, back pack, knapsack, packsack, rucksack, haversack',\n 415: 'bakery, bakeshop, bakehouse',\n 416: 'balance beam, beam',\n 417: 'balloon',\n 418: 'ballpoint, ballpoint pen, ballpen, Biro',\n 419: 'Band Aid',\n 420: 'banjo',\n 421: 'bannister, banister, balustrade, balusters, handrail',\n 422: 'barbell',\n 423: 'barber chair',\n 424: 'barbershop',\n 425: 'barn',\n 426: 'barometer',\n 427: 'barrel, cask',\n 428: 'barrow, garden cart, lawn cart, wheelbarrow',\n 429: 'baseball',\n 430: 'basketball',\n 431: 'bassinet',\n 432: 'bassoon',\n 433: 'bathing cap, swimming cap',\n 434: 'bath towel',\n 435: 'bathtub, bathing tub, bath, tub',\n 436: 'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon',\n 437: 'beacon, lighthouse, beacon light, pharos',\n 438: 'beaker',\n 439: 'bearskin, busby, shako',\n 440: 'beer bottle',\n 441: 'beer glass',\n 442: 'bell cote, bell cot',\n 443: 'bib',\n 444: 'bicycle-built-for-two, tandem bicycle, tandem',\n 445: 'bikini, two-piece',\n 446: 'binder, ring-binder',\n 447: 'binoculars, field glasses, opera glasses',\n 448: 'birdhouse',\n 449: 'boathouse',\n 450: 'bobsled, bobsleigh, bob',\n 451: 'bolo tie, bolo, bola tie, bola',\n 452: 'bonnet, poke bonnet',\n 453: 'bookcase',\n 454: 'bookshop, bookstore, bookstall',\n 455: 'bottlecap',\n 456: 'bow',\n 457: 'bow tie, bow-tie, bowtie',\n 458: 'brass, memorial tablet, plaque',\n 459: 'brassiere, bra, bandeau',\n 460: 'breakwater, groin, groyne, mole, bulwark, seawall, jetty',\n 461: 'breastplate, aegis, egis',\n 462: 'broom',\n 463: 'bucket, pail',\n 464: 'buckle',\n 465: 'bulletproof vest',\n 466: 'bullet train, bullet',\n 467: 'butcher shop, meat market',\n 468: 'cab, hack, taxi, taxicab',\n 469: 'caldron, cauldron',\n 470: 'candle, taper, wax light',\n 471: 'cannon',\n 472: 'canoe',\n 473: 'can opener, tin opener',\n 474: 'cardigan',\n 475: 'car mirror',\n 476: 'carousel, carrousel, merry-go-round, roundabout, whirligig',\n 477: \"carpenter's kit, tool kit\",\n 478: 'carton',\n 479: 'car wheel',\n 480: 'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM',\n 481: 'cassette',\n 482: 'cassette player',\n 483: 'castle',\n 484: 'catamaran',\n 485: 'CD player',\n 486: 'cello, violoncello',\n 487: 'cellular telephone, cellular phone, cellphone, cell, mobile phone',\n 488: 'chain',\n 489: 'chainlink fence',\n 490: 'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour',\n 491: 'chain saw, chainsaw',\n 492: 'chest',\n 493: 'chiffonier, commode',\n 494: 'chime, bell, gong',\n 495: 'china cabinet, china closet',\n 496: 'Christmas stocking',\n 497: 'church, church building',\n 498: 'cinema, movie theater, movie theatre, movie house, picture palace',\n 499: 'cleaver, meat cleaver, chopper',\n 500: 'cliff dwelling',\n 501: 'cloak',\n 502: 'clog, geta, patten, sabot',\n 503: 'cocktail shaker',\n 504: 'coffee mug',\n 505: 'coffeepot',\n 506: 'coil, spiral, volute, whorl, helix',\n 507: 'combination lock',\n 508: 'computer keyboard, keypad',\n 509: 'confectionery, confectionary, candy store',\n 510: 'container ship, containership, container vessel',\n 511: 'convertible',\n 512: 'corkscrew, bottle screw',\n 513: 'cornet, horn, trumpet, trump',\n 514: 'cowboy boot',\n 515: 'cowboy hat, ten-gallon hat',\n 516: 'cradle',\n 517: 'crane',\n 518: 'crash helmet',\n 519: 'crate',\n 520: 'crib, cot',\n 521: 'Crock Pot',\n 522: 'croquet ball',\n 523: 'crutch',\n 524: 'cuirass',\n 525: 'dam, dike, dyke',\n 526: 'desk',\n 527: 'desktop computer',\n 528: 'dial telephone, dial phone',\n 529: 'diaper, nappy, napkin',\n 530: 'digital clock',\n 531: 'digital watch',\n 532: 'dining table, board',\n 533: 'dishrag, dishcloth',\n 534: 'dishwasher, dish washer, dishwashing machine',\n 535: 'disk brake, disc brake',\n 536: 'dock, dockage, docking facility',\n 537: 'dogsled, dog sled, dog sleigh',\n 538: 'dome',\n 539: 'doormat, welcome mat',\n 540: 'drilling platform, offshore rig',\n 541: 'drum, membranophone, tympan',\n 542: 'drumstick',\n 543: 'dumbbell',\n 544: 'Dutch oven',\n 545: 'electric fan, blower',\n 546: 'electric guitar',\n 547: 'electric locomotive',\n 548: 'entertainment center',\n 549: 'envelope',\n 550: 'espresso maker',\n 551: 'face powder',\n 552: 'feather boa, boa',\n 553: 'file, file cabinet, filing cabinet',\n 554: 'fireboat',\n 555: 'fire engine, fire truck',\n 556: 'fire screen, fireguard',\n 557: 'flagpole, flagstaff',\n 558: 'flute, transverse flute',\n 559: 'folding chair',\n 560: 'football helmet',\n 561: 'forklift',\n 562: 'fountain',\n 563: 'fountain pen',\n 564: 'four-poster',\n 565: 'freight car',\n 566: 'French horn, horn',\n 567: 'frying pan, frypan, skillet',\n 568: 'fur coat',\n 569: 'garbage truck, dustcart',\n 570: 'gasmask, respirator, gas helmet',\n 571: 'gas pump, gasoline pump, petrol pump, island dispenser',\n 572: 'goblet',\n 573: 'go-kart',\n 574: 'golf ball',\n 575: 'golfcart, golf cart',\n 576: 'gondola',\n 577: 'gong, tam-tam',\n 578: 'gown',\n 579: 'grand piano, grand',\n 580: 'greenhouse, nursery, glasshouse',\n 581: 'grille, radiator grille',\n 582: 'grocery store, grocery, food market, market',\n 583: 'guillotine',\n 584: 'hair slide',\n 585: 'hair spray',\n 586: 'half track',\n 587: 'hammer',\n 588: 'hamper',\n 589: 'hand blower, blow dryer, blow drier, hair dryer, hair drier',\n 590: 'hand-held computer, hand-held microcomputer',\n 591: 'handkerchief, hankie, hanky, hankey',\n 592: 'hard disc, hard disk, fixed disk',\n 593: 'harmonica, mouth organ, harp, mouth harp',\n 594: 'harp',\n 595: 'harvester, reaper',\n 596: 'hatchet',\n 597: 'holster',\n 598: 'home theater, home theatre',\n 599: 'honeycomb',\n 600: 'hook, claw',\n 601: 'hoopskirt, crinoline',\n 602: 'horizontal bar, high bar',\n 603: 'horse cart, horse-cart',\n 604: 'hourglass',\n 605: 'iPod',\n 606: 'iron, smoothing iron',\n 607: \"jack-o'-lantern\",\n 608: 'jean, blue jean, denim',\n 609: 'jeep, landrover',\n 610: 'jersey, T-shirt, tee shirt',\n 611: 'jigsaw puzzle',\n 612: 'jinrikisha, ricksha, rickshaw',\n 613: 'joystick',\n 614: 'kimono',\n 615: 'knee pad',\n 616: 'knot',\n 617: 'lab coat, laboratory coat',\n 618: 'ladle',\n 619: 'lampshade, lamp shade',\n 620: 'laptop, laptop computer',\n 621: 'lawn mower, mower',\n 622: 'lens cap, lens cover',\n 623: 'letter opener, paper knife, paperknife',\n 624: 'library',\n 625: 'lifeboat',\n 626: 'lighter, light, igniter, ignitor',\n 627: 'limousine, limo',\n 628: 'liner, ocean liner',\n 629: 'lipstick, lip rouge',\n 630: 'Loafer',\n 631: 'lotion',\n 632: 'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system',\n 633: \"loupe, jeweler's loupe\",\n 634: 'lumbermill, sawmill',\n 635: 'magnetic compass',\n 636: 'mailbag, postbag',\n 637: 'mailbox, letter box',\n 638: 'maillot',\n 639: 'maillot, tank suit',\n 640: 'manhole cover',\n 641: 'maraca',\n 642: 'marimba, xylophone',\n 643: 'mask',\n 644: 'matchstick',\n 645: 'maypole',\n 646: 'maze, labyrinth',\n 647: 'measuring cup',\n 648: 'medicine chest, medicine cabinet',\n 649: 'megalith, megalithic structure',\n 650: 'microphone, mike',\n 651: 'microwave, microwave oven',\n 652: 'military uniform',\n 653: 'milk can',\n 654: 'minibus',\n 655: 'miniskirt, mini',\n 656: 'minivan',\n 657: 'missile',\n 658: 'mitten',\n 659: 'mixing bowl',\n 660: 'mobile home, manufactured home',\n 661: 'Model T',\n 662: 'modem',\n 663: 'monastery',\n 664: 'monitor',\n 665: 'moped',\n 666: 'mortar',\n 667: 'mortarboard',\n 668: 'mosque',\n 669: 'mosquito net',\n 670: 'motor scooter, scooter',\n 671: 'mountain bike, all-terrain bike, off-roader',\n 672: 'mountain tent',\n 673: 'mouse, computer mouse',\n 674: 'mousetrap',\n 675: 'moving van',\n 676: 'muzzle',\n 677: 'nail',\n 678: 'neck brace',\n 679: 'necklace',\n 680: 'nipple',\n 681: 'notebook, notebook computer',\n 682: 'obelisk',\n 683: 'oboe, hautboy, hautbois',\n 684: 'ocarina, sweet potato',\n 685: 'odometer, hodometer, mileometer, milometer',\n 686: 'oil filter',\n 687: 'organ, pipe organ',\n 688: 'oscilloscope, scope, cathode-ray oscilloscope, CRO',\n 689: 'overskirt',\n 690: 'oxcart',\n 691: 'oxygen mask',\n 692: 'packet',\n 693: 'paddle, boat paddle',\n 694: 'paddlewheel, paddle wheel',\n 695: 'padlock',\n 696: 'paintbrush',\n 697: \"pajama, pyjama, pj's, jammies\",\n 698: 'palace',\n 699: 'panpipe, pandean pipe, syrinx',\n 700: 'paper towel',\n 701: 'parachute, chute',\n 702: 'parallel bars, bars',\n 703: 'park bench',\n 704: 'parking meter',\n 705: 'passenger car, coach, carriage',\n 706: 'patio, terrace',\n 707: 'pay-phone, pay-station',\n 708: 'pedestal, plinth, footstall',\n 709: 'pencil box, pencil case',\n 710: 'pencil sharpener',\n 711: 'perfume, essence',\n 712: 'Petri dish',\n 713: 'photocopier',\n 714: 'pick, plectrum, plectron',\n 715: 'pickelhaube',\n 716: 'picket fence, paling',\n 717: 'pickup, pickup truck',\n 718: 'pier',\n 719: 'piggy bank, penny bank',\n 720: 'pill bottle',\n 721: 'pillow',\n 722: 'ping-pong ball',\n 723: 'pinwheel',\n 724: 'pirate, pirate ship',\n 725: 'pitcher, ewer',\n 726: \"plane, carpenter's plane, woodworking plane\",\n 727: 'planetarium',\n 728: 'plastic bag',\n 729: 'plate rack',\n 730: 'plow, plough',\n 731: \"plunger, plumber's helper\",\n 732: 'Polaroid camera, Polaroid Land camera',\n 733: 'pole',\n 734: 'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria',\n 735: 'poncho',\n 736: 'pool table, billiard table, snooker table',\n 737: 'pop bottle, soda bottle',\n 738: 'pot, flowerpot',\n 739: \"potter's wheel\",\n 740: 'power drill',\n 741: 'prayer rug, prayer mat',\n 742: 'printer',\n 743: 'prison, prison house',\n 744: 'projectile, missile',\n 745: 'projector',\n 746: 'puck, hockey puck',\n 747: 'punching bag, punch bag, punching ball, punchball',\n 748: 'purse',\n 749: 'quill, quill pen',\n 750: 'quilt, comforter, comfort, puff',\n 751: 'racer, race car, racing car',\n 752: 'racket, racquet',\n 753: 'radiator',\n 754: 'radio, wireless',\n 755: 'radio telescope, radio reflector',\n 756: 'rain barrel',\n 757: 'recreational vehicle, RV, R.V.',\n 758: 'reel',\n 759: 'reflex camera',\n 760: 'refrigerator, icebox',\n 761: 'remote control, remote',\n 762: 'restaurant, eating house, eating place, eatery',\n 763: 'revolver, six-gun, six-shooter',\n 764: 'rifle',\n 765: 'rocking chair, rocker',\n 766: 'rotisserie',\n 767: 'rubber eraser, rubber, pencil eraser',\n 768: 'rugby ball',\n 769: 'rule, ruler',\n 770: 'running shoe',\n 771: 'safe',\n 772: 'safety pin',\n 773: 'saltshaker, salt shaker',\n 774: 'sandal',\n 775: 'sarong',\n 776: 'sax, saxophone',\n 777: 'scabbard',\n 778: 'scale, weighing machine',\n 779: 'school bus',\n 780: 'schooner',\n 781: 'scoreboard',\n 782: 'screen, CRT screen',\n 783: 'screw',\n 784: 'screwdriver',\n 785: 'seat belt, seatbelt',\n 786: 'sewing machine',\n 787: 'shield, buckler',\n 788: 'shoe shop, shoe-shop, shoe store',\n 789: 'shoji',\n 790: 'shopping basket',\n 791: 'shopping cart',\n 792: 'shovel',\n 793: 'shower cap',\n 794: 'shower curtain',\n 795: 'ski',\n 796: 'ski mask',\n 797: 'sleeping bag',\n 798: 'slide rule, slipstick',\n 799: 'sliding door',\n 800: 'slot, one-armed bandit',\n 801: 'snorkel',\n 802: 'snowmobile',\n 803: 'snowplow, snowplough',\n 804: 'soap dispenser',\n 805: 'soccer ball',\n 806: 'sock',\n 807: 'solar dish, solar collector, solar furnace',\n 808: 'sombrero',\n 809: 'soup bowl',\n 810: 'space bar',\n 811: 'space heater',\n 812: 'space shuttle',\n 813: 'spatula',\n 814: 'speedboat',\n 815: \"spider web, spider's web\",\n 816: 'spindle',\n 817: 'sports car, sport car',\n 818: 'spotlight, spot',\n 819: 'stage',\n 820: 'steam locomotive',\n 821: 'steel arch bridge',\n 822: 'steel drum',\n 823: 'stethoscope',\n 824: 'stole',\n 825: 'stone wall',\n 826: 'stopwatch, stop watch',\n 827: 'stove',\n 828: 'strainer',\n 829: 'streetcar, tram, tramcar, trolley, trolley car',\n 830: 'stretcher',\n 831: 'studio couch, day bed',\n 832: 'stupa, tope',\n 833: 'submarine, pigboat, sub, U-boat',\n 834: 'suit, suit of clothes',\n 835: 'sundial',\n 836: 'sunglass',\n 837: 'sunglasses, dark glasses, shades',\n 838: 'sunscreen, sunblock, sun blocker',\n 839: 'suspension bridge',\n 840: 'swab, swob, mop',\n 841: 'sweatshirt',\n 842: 'swimming trunks, bathing trunks',\n 843: 'swing',\n 844: 'switch, electric switch, electrical switch',\n 845: 'syringe',\n 846: 'table lamp',\n 847: 'tank, army tank, armored combat vehicle, armoured combat vehicle',\n 848: 'tape player',\n 849: 'teapot',\n 850: 'teddy, teddy bear',\n 851: 'television, television system',\n 852: 'tennis ball',\n 853: 'thatch, thatched roof',\n 854: 'theater curtain, theatre curtain',\n 855: 'thimble',\n 856: 'thresher, thrasher, threshing machine',\n 857: 'throne',\n 858: 'tile roof',\n 859: 'toaster',\n 860: 'tobacco shop, tobacconist shop, tobacconist',\n 861: 'toilet seat',\n 862: 'torch',\n 863: 'totem pole',\n 864: 'tow truck, tow car, wrecker',\n 865: 'toyshop',\n 866: 'tractor',\n 867: 'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi',\n 868: 'tray',\n 869: 'trench coat',\n 870: 'tricycle, trike, velocipede',\n 871: 'trimaran',\n 872: 'tripod',\n 873: 'triumphal arch',\n 874: 'trolleybus, trolley coach, trackless trolley',\n 875: 'trombone',\n 876: 'tub, vat',\n 877: 'turnstile',\n 878: 'typewriter keyboard',\n 879: 'umbrella',\n 880: 'unicycle, monocycle',\n 881: 'upright, upright piano',\n 882: 'vacuum, vacuum cleaner',\n 883: 'vase',\n 884: 'vault',\n 885: 'velvet',\n 886: 'vending machine',\n 887: 'vestment',\n 888: 'viaduct',\n 889: 'violin, fiddle',\n 890: 'volleyball',\n 891: 'waffle iron',\n 892: 'wall clock',\n 893: 'wallet, billfold, notecase, pocketbook',\n 894: 'wardrobe, closet, press',\n 895: 'warplane, military plane',\n 896: 'washbasin, handbasin, washbowl, lavabo, wash-hand basin',\n 897: 'washer, automatic washer, washing machine',\n 898: 'water bottle',\n 899: 'water jug',\n 900: 'water tower',\n 901: 'whiskey jug',\n 902: 'whistle',\n 903: 'wig',\n 904: 'window screen',\n 905: 'window shade',\n 906: 'Windsor tie',\n 907: 'wine bottle',\n 908: 'wing',\n 909: 'wok',\n 910: 'wooden spoon',\n 911: 'wool, woolen, woollen',\n 912: 'worm fence, snake fence, snake-rail fence, Virginia fence',\n 913: 'wreck',\n 914: 'yawl',\n 915: 'yurt',\n 916: 'web site, website, internet site, site',\n 917: 'comic book',\n 918: 'crossword puzzle, crossword',\n 919: 'street sign',\n 920: 'traffic light, traffic signal, stoplight',\n 921: 'book jacket, dust cover, dust jacket, dust wrapper',\n 922: 'menu',\n 923: 'plate',\n 924: 'guacamole',\n 925: 'consomme',\n 926: 'hot pot, hotpot',\n 927: 'trifle',\n 928: 'ice cream, icecream',\n 929: 'ice lolly, lolly, lollipop, popsicle',\n 930: 'French loaf',\n 931: 'bagel, beigel',\n 932: 'pretzel',\n 933: 'cheeseburger',\n 934: 'hotdog, hot dog, red hot',\n 935: 'mashed potato',\n 936: 'head cabbage',\n 937: 'broccoli',\n 938: 'cauliflower',\n 939: 'zucchini, courgette',\n 940: 'spaghetti squash',\n 941: 'acorn squash',\n 942: 'butternut squash',\n 943: 'cucumber, cuke',\n 944: 'artichoke, globe artichoke',\n 945: 'bell pepper',\n 946: 'cardoon',\n 947: 'mushroom',\n 948: 'Granny Smith',\n 949: 'strawberry',\n 950: 'orange',\n 951: 'lemon',\n 952: 'fig',\n 953: 'pineapple, ananas',\n 954: 'banana',\n 955: 'jackfruit, jak, jack',\n 956: 'custard apple',\n 957: 'pomegranate',\n 958: 'hay',\n 959: 'carbonara',\n 960: 'chocolate sauce, chocolate syrup',\n 961: 'dough',\n 962: 'meat loaf, meatloaf',\n 963: 'pizza, pizza pie',\n 964: 'potpie',\n 965: 'burrito',\n 966: 'red wine',\n 967: 'espresso',\n 968: 'cup',\n 969: 'eggnog',\n 970: 'alp',\n 971: 'bubble',\n 972: 'cliff, drop, drop-off',\n 973: 'coral reef',\n 974: 'geyser',\n 975: 'lakeside, lakeshore',\n 976: 'promontory, headland, head, foreland',\n 977: 'sandbar, sand bar',\n 978: 'seashore, coast, seacoast, sea-coast',\n 979: 'valley, vale',\n 980: 'volcano',\n 981: 'ballplayer, baseball player',\n 982: 'groom, bridegroom',\n 983: 'scuba diver',\n 984: 'rapeseed',\n 985: 'daisy',\n 986: \"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum\",\n 987: 'corn',\n 988: 'acorn',\n 989: 'hip, rose hip, rosehip',\n 990: 'buckeye, horse chestnut, conker',\n 991: 'coral fungus',\n 992: 'agaric',\n 993: 'gyromitra',\n 994: 'stinkhorn, carrion fungus',\n 995: 'earthstar',\n 996: 'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa',\n 997: 'bolete',\n 998: 'ear, spike, capitulum',\n 999: 'toilet tissue, toilet paper, bathroom tissue'}\n```\n\n\n```python\n# @title Map Imagenette Labels to Imagenet Labels\ndir_to_imagenet_index = {\n 'n03888257': 1,\n 'n03425413': 571,\n 'n03394916': 566,\n 'n03000684': 491,\n 'n02102040': 217,\n 'n03445777': 574,\n 'n03417042': 569,\n 'n03028079': 497,\n 'n02979186': 482,\n 'n01440764': 701\n }\n\ndir_index_to_imagenet_label = {}\nordered_dirs = sorted(list(dir_to_imagenet_index.keys()))\n\nfor dir_index, dir_name in enumerate(ordered_dirs):\n dir_index_to_imagenet_label[dir_index] = dir_to_imagenet_index[dir_name]\n```\n\n\n```python\n# @title Prepare Imagenette Data\nval_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\nimagenette_val = ImageFolder('imagenette2-320/val', transform=val_transform)\n\ntrain_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\nimagenette_train = ImageFolder('imagenette2-320/train',\n transform=train_transform)\nrandom.seed(SEED)\nrandom_indices = random.sample(range(len(imagenette_train)), 400)\nimagenette_train_subset = torch.utils.data.Subset(imagenette_train,\n random_indices)\n\n\n\n\n# Subset to only one tenth of the data for faster runtime\nrandom_indices = random.sample(range(len(imagenette_val)), int(len(imagenette_val) * .1))\nimagenette_val = torch.utils.data.Subset(imagenette_val, random_indices)\n```\n\n\n```python\n# To preserve reproducibility\ng_seed = torch.Generator()\ng_seed.manual_seed(SEED)\n\nimagenette_train_loader = torch.utils.data.DataLoader(imagenette_train_subset,\n batch_size=16,\n shuffle=True,\n num_workers=2,\n worker_init_fn=seed_worker,\n generator=g_seed\n )\n\nimagenette_val_loader = torch.utils.data.DataLoader(imagenette_val,\n batch_size=16,\n shuffle=False,\n num_workers=2,\n worker_init_fn=seed_worker,\n generator=g_seed)\n\ndataiter = iter(imagenette_val_loader)\nimages, labels = dataiter.next()\n\n# show images\nplt.figure(figsize=(8, 8))\nplt.imshow(make_grid(images, nrow=4).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n\n```python\n# @title eval_imagenette function\ndef eval_imagenette(resnet, data_loader, dataset_length, device):\n resnet.eval()\n with torch.no_grad():\n loss_sum = 0\n total_1_correct = 0\n total_5_correct = 0\n total = dataset_length\n for batch in tqdm.notebook.tqdm(data_loader):\n images, labels = batch\n\n # Map the imagenette labels onto the network's output\n for i, label in enumerate(labels):\n labels[i] = dir_index_to_imagenet_label[label.item()]\n\n images = images.to(device)\n labels = labels.to(device)\n output = resnet(images)\n\n # Calculate top-5 accuracy\n # Implementation from https://github.com/bearpaw/pytorch-classification/blob/cc9106d598ff1fe375cc030873ceacfea0499d77/utils/eval.py\n batch_size = labels.size(0)\n\n _, predictions = output.topk(5, 1, True, True)\n predictions = predictions.t()\n\n top_k_correct = predictions.eq(labels.view(1, -1).expand_as(predictions))\n top_k_correct = top_k_correct.sum()\n\n predictions = torch.argmax(output, dim=1)\n top_1_correct = torch.sum(predictions == labels)\n total_1_correct += top_1_correct\n total_5_correct += top_k_correct\n\n top_1_acc = total_1_correct / total\n top_5_acc = total_5_correct / total\n\n return top_1_acc, top_5_acc\n```\n\n\n```python\n# @title Imagenette Train Loop\n\ndef imagenette_train_loop(model, optimizer, train_loader, loss_fn, device):\n for epoch in tqdm.notebook.tqdm(range(5)):\n # Set model to use the imagenette classifier head\n model.train()\n # Train on a batch of images\n for imagenette_batch in train_loader:\n images, labels = imagenette_batch\n\n # Convert labels from imagenette indices to imagenet labels\n for i, label in enumerate(labels):\n labels[i] = dir_index_to_imagenet_label[label.item()]\n\n images = images.to(device)\n labels = labels.to(device)\n output = model(images)\n optimizer.zero_grad()\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n return model\n```\n\nThis cell creates a ResNet model pretrained on [ImageNet](http://www.image-net.org/), a 1000 class image prediction dataset. The model is then trained to make predictions on [Imagenette](https://github.com/fastai/imagenette), a small subset of ImageNet classes that is useful for demonstrations and prototyping.\n\n\n```python\n# Original network\ntop_1_accuracies = []\ntop_5_accuracies = []\n\n# Instantiate a pretrained resnet model\nset_seed(seed=SEED)\nresnet = torchvision.models.resnet18(pretrained=True).to(DEVICE)\nresnet_opt = torch.optim.Adam(resnet.parameters(), lr=1e-4)\nloss_fn = nn.CrossEntropyLoss()\n\nimagenette_train_loop(resnet,\n resnet_opt,\n imagenette_train_loader,\n loss_fn,\n device=DEVICE)\n\ntop_1_acc, top_5_acc = eval_imagenette(resnet,\n imagenette_val_loader,\n len(imagenette_val),\n device=DEVICE)\ntop_1_accuracies.append(top_1_acc.item())\ntop_5_accuracies.append(top_5_acc.item())\n```\n\n## Coding Exercise 4.1: Use the ResNet model\n\nComplete the function below that runs a batch of images through the trained ResNet and returns the Top 5 class predictions and their probabilities. Note that the ResNet model returns unnormalized logits$^\\dagger$. To obtain probabilities, you need to normalize the logits using softmax.\n\n
\n\n$^\\dagger$ $ \\text{logit}(p) = \\sigma^{-1}(p) = \\text{log} \\left( \\frac{p}{1-p} \\right), \\, \\text{for} \\, p \\in (0,1)$, where $\\sigma(\\cdot)$ is the sigmoid function, i.e., $\\sigma(z) = 1/(1+e^{-z})$. For more information see [here](http://machinelearningmechanic.com/deep_learning/2019/09/04/cross-entropy-loss-derivative.html).\n\n\n```python\ndef predict_top5(images, device, seed):\n \"\"\"\n Args:\n images: torch Tensor with dimensionality B x C x H x W\n (batch size x number of channels x height x width)\n device: STRING\n `cuda` if GPU is available, else `cpu`.\n Output:\n top5_probs: torch Tensor (B, 5) with top 5 class probabilities\n top5_names: list of top 5 class names (B, 5)\n \"\"\"\n ####################################################################\n # Fill in all missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Predict top 5\")\n ####################################################################\n set_seed(seed=seed)\n\n B = images.size(0)\n with torch.no_grad():\n # Run images through model\n images = ...\n output = ...\n # The model output is unnormalized. To get probabilities, run a softmax on it.\n probs = ...\n # Fetch output from GPU and convert to numpy array\n probs = ...\n\n # Get top 5 predictions\n _, top5_idcs = output.topk(5, 1, True, True)\n top5_idcs = top5_idcs.t().cpu().numpy()\n top5_probs = probs[torch.arange(B), top5_idcs]\n\n # Convert indices to class names\n top5_names = []\n for b in range(B):\n temp = [dict_map[key].split(',')[0] for key in top5_idcs[:, b]]\n top5_names.append(temp)\n\n return top5_names, top5_probs\n\n\n# add event to airtable\natform.add_event('Coding Exercise 4.1: Use the ResNet model')\n\n# get batch of images\ndataiter = iter(imagenette_val_loader)\nimages, labels = dataiter.next()\n\n## Uncomment to test your function and retrieve top 5 predictions\n# top5_names, top5_probs = predict_top5(images, DEVICE, SEED)\n# print(top5_names[1])\n```\n\n\n```python\n# to_remove solution\ndef predict_top5(images, device, seed):\n \"\"\"\n Args:\n images: torch Tensor with dimensionality B x C x H x W\n (batch size x number of channels x height x width)\n device: STRING\n `cuda` if GPU is available, else `cpu`.\n Output:\n top5_probs: torch Tensor (B, 5) with top 5 class probabilities\n top5_names: list of top 5 class names (B, 5)\n \"\"\"\n set_seed(seed=seed)\n\n B = images.size(0)\n with torch.no_grad():\n # Run images through model\n images = images.to(device)\n output = resnet(images)\n # The model output is unnormalized. To get probabilities, run a softmax on it.\n probs = torch.nn.functional.softmax(output, dim=1)\n # Fetch output from GPU and convert to numpy array\n probs = probs.cpu().numpy()\n\n # Get top 5 predictions\n _, top5_idcs = output.topk(5, 1, True, True)\n top5_idcs = top5_idcs.t().cpu().numpy()\n top5_probs = probs[torch.arange(B), top5_idcs]\n\n # Convert indices to class names\n top5_names = []\n for b in range(B):\n temp = [dict_map[key].split(',')[0] for key in top5_idcs[:, b]]\n top5_names.append(temp)\n\n return top5_names, top5_probs\n\n\n# add event to airtable\natform.add_event('Coding Exercise 4.1: Use the ResNet model')\n\n# get batch of images\ndataiter = iter(imagenette_val_loader)\nimages, labels = dataiter.next()\n\n## Uncomment to test your function and retrieve top 5 predictions\ntop5_names, top5_probs = predict_top5(images, DEVICE, SEED)\nprint(top5_names[1])\n```\n\n```\nRandom seed 2021 has been set.\n['gas pump', 'chain saw', 'jinrikisha', 'French horn', 'laptop']\n```\n\n\n```python\n# visualize probabilities of top 5 predictions\nfig, ax = plt.subplots(5, 2, figsize=(10, 20))\n\nfor i in range(5):\n ax[i, 0].imshow(np.moveaxis(images[i].numpy(), 0, -1))\n ax[i, 0].axis('off')\n\n ax[i, 1].bar(np.arange(5), top5_probs[:, i])\n ax[i, 1].set_xticks(np.arange(5))\n ax[i, 1].set_xticklabels(top5_names[i], rotation=30)\n\nfig.tight_layout()\nplt.show()\n```\n\n## Out-of-distribution examples\n\nThe code below runs two out-of-distribution examples through the trained ResNet. Look at the predictions and discuss, why the model might fail to make accurate predictions on these images. \n\n\n```python\nloc = 'https://raw.githubusercontent.com/NeuromatchAcademy/course-content-dl/main/tutorials/W2D2_ModernConvnets/static/'\n\nfname1 = 'bonsai-svg-5.png'\nresponse = requests.get(loc + fname1)\nimage = Image.open(BytesIO(response.content)).resize((256, 256))\ndata = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.\n\nfname2 = 'Pokémon_Pikachu_art.png'\nresponse = requests.get(loc + fname2)\nimage = Image.open(BytesIO(response.content)).resize((256, 256))\ndata2 = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.\n\nimages = torch.stack([data, data2]).permute(0, 3, 1, 2)\n```\n\n\n```python\n# retrieve top 5 predictions\ntop5_names, top5_probs = predict_top5(images, DEVICE, SEED)\n```\n\n\n```python\n# visualize probabilities of top 5 predictions\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\nfor i in range(2):\n ax[i, 0].imshow(np.moveaxis(images[i].numpy(), 0, -1))\n ax[i, 0].axis('off')\n\n ax[i, 1].bar(np.arange(5), top5_probs[:, i])\n ax[i, 1].set_xticks(np.arange(5))\n ax[i, 1].set_xticklabels(top5_names[i], rotation=30)\n\nfig.tight_layout()\nplt.show()\n```\n\n---\n# Section 5: Inception + ResNeXt\n\n*Time estimate: ~27mins*\n\n\n```python\n# @title Video 5: Improving efficiency: Inceptrion and ResNeXt\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Zq4y1W7Px\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"TDHn7X1wNQ4\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 5: Improving efficiency: Inceptrion and ResNeXt')\n\ndisplay(out)\n```\n\n## ResNet vs ResNeXt\n\n\n\n[Xie et al., 2016](https://arxiv.org/abs/1611.05431)\n\n\n## Interactive Demo 5: ResNet vs. ResNeXt\n\nThe widgets below calculate the number of parameters in a ResNet (top) and the parameters in a ResNeXt (bottom). We assume that the number of input and output channels (or feature maps) is the same (labeled \"Channels in+out\" in the widget). We refer to the number of channels after the first and the second layer of one block of either ResNet or ResNeXt as \"bottleneck channels\".\n\nThe sliders are currently in the position that is displayed in the figure above. The goal of the following tasks is to investigate the difference in expressiveness and numbers of parameters in ResNet and ResNeXt.\n\n\n```python\n# @title Parameter Calculator\n# @markdown Run this cell to enable the widget\nfrom IPython.display import display as dis\n\ndef calculate_parameters_resnet(d_in, resnet_channels):\n # ResNet math: Implement how parameters scale\n d_out = d_in\n resnet_parameters = d_in*resnet_channels + 3*3*resnet_channels*resnet_channels + resnet_channels*d_out\n\n print('ResNet parameters: {}'.format(resnet_parameters))\n return None\n\n\ndef calculate_parameters_resnext(d_in, resnext_channels, num_paths):\n # ResNet math: Implement how parameters scale\n d_out = d_in\n d = resnext_channels\n\n resnext_parameters = (d_in*d + 3*3*d*d + d*d_out)*num_paths\n\n print('ResNeXt parameters: {}'.format(resnext_parameters))\n return None\n\n\nlabels = ['ResNet', 'ResNeXt']\ndescriptions_resnet = ['Channels in+out', 'Bottleneck channels']\ndescriptions_resnext = ['Channels in+out', 'Bottleneck channels',\n 'Number of paths (cardinality)']\nlbox_resnet = widgets.VBox([widgets.Label(description) for description in descriptions_resnet])\nlbox_resnext = widgets.VBox([widgets.Label(description) for description in descriptions_resnext])\n\nd_in = widgets.FloatLogSlider(\n value=256,\n base=2,\n min=1, # max exponent of base\n max=10, # min exponent of base\n step=1, # exponent step\n)\nresnet_channels = widgets.FloatLogSlider(\n value=64,\n base=2,\n min=5, # max exponent of base\n max=10, # min exponent of base\n step=1, # exponent step\n)\nresnext_channels = widgets.FloatLogSlider(\n value=4,\n base=2,\n min=1, # max exponent of base\n max=10, # min exponent of base\n step=1, # exponent step\n)\nnum_paths = widgets.FloatLogSlider(\n value=32,\n base=2,\n min=0, # max exponent of base\n max=7, # min exponent of base\n step=1, # exponent step\n)\n\nrbox_resnet = widgets.VBox([d_in, resnet_channels])\nrbox_resnext = widgets.VBox([d_in, resnext_channels, num_paths])\nui_resnet = widgets.HBox([lbox_resnet, rbox_resnet])\nui_resnet_labeled = widgets.VBox(\n [widgets.HTML(value=\"\" + labels[0] + \"\"), ui_resnet],\n layout=widgets.Layout(border='1px solid black'))\nui_resnext = widgets.HBox([lbox_resnext, rbox_resnext])\nui_resnext_labeled = widgets.VBox(\n [widgets.HTML(value=\"\" + labels[1] + \"\"), ui_resnext],\n layout=widgets.Layout(border='1px solid black'))\nui = widgets.VBox([ui_resnet_labeled, ui_resnext_labeled])\n\nout_resnet = widgets.interactive_output(calculate_parameters_resnet,\n {'d_in':d_in,\n 'resnet_channels':resnet_channels})\n\nout_resnext = widgets.interactive_output(calculate_parameters_resnext,\n {'d_in':d_in,\n 'resnext_channels':resnext_channels,\n 'num_paths':num_paths})\n\nd1 = dis(ui, out_resnet, out_resnext)\n```\n\n## Think! 5: ResNet vs. ResNeXt\n\nIn the figure above, both networks – ResNet and ResNeXt – have a similar number of parameters. \n\n1. How many channels are there in the bottleneck of the two networks, respectively?\n1. How are these channels connected to each other from the first to the second layer in the blocks of the two networks, respectively? \n1. What does it mean for the expressiveness of the two models relative to each other?\n\n\n```python\n# @title Student Response\nfrom ipywidgets import widgets\n\n\ntext=widgets.Textarea(\n value='Type your answer here and click on `Submit!`',\n placeholder='Type something',\n description='',\n disabled=False\n)\n\nbutton = widgets.Button(description=\"Submit!\")\n\ndisplay(text,button)\n\ndef on_button_clicked(b):\n atform.add_answer('q4', text.value)\n print(\"Submission successful!\")\n\n\nbutton.on_click(on_button_clicked)\n```\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n1. The ResNeXt has 32 * 4 = 128 channels in the bottleneck, whereas the ResNet has only 64.\n\n2. In ResNet all 64 output channels of the first layer are connected to all 64 output channels of the second layer.\nIn ResNeXt, channels are connected only within paths, i.e. in groups of 4.\n\n3. ResNeXt contains more channels in the bottleneck (potentially more expressive),\n but each of them \"sees\" only a subset of the previous layer's output (potentially less expressive).\n The former tends to outweigh the latter, which is why the ResNeXt architecture tends to outperform the\n vanilla ResNet architecture.\n\"\"\"\n```\n\nNow we want to look at the number of parameters.\n* How does the difference in number of parameters change if we fix the number of channels in the bottleneck of both ResNet and ResNeXt to be 64, but vary the number of paths in ResNeXt? (8 paths with 8 channels each would be one such example)\n* Which number of paths results in the biggest parameter savings?\n\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n -- if number of paths=1 and channels per path=64 -> same architecture as ResNet, no parameter saving\n -- if number of paths=8 and channels per path=8 -> around half the number of parameters\n -- if number of paths=32 and channels per path=2 -> biggest parameter saving the more paths, the more saving\n\"\"\"\n```\n\n---\n# Section 6: Depthwise separable convolutions\n\n*Time estimate: ~23mins*\n\n\n```python\n# @title Video 6: Improving efficiency: MobileNet\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1D44y127fS\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"kdbGpn1JfmU\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 6: Improving efficiency: MobileNet')\n\ndisplay(out)\n```\n\n## Section 6.1: Depthwise separable convolutions\n\nAnother way to reduce the computational cost of large models is the use of depthwise separable convolutions ([introduced here](https://www.di.ens.fr/data/publications/papers/phd_sifre.pdf)). Depthwise separable convolutions are the key component making [MobileNets](https://arxiv.org/abs/1704.04861) efficient.\n\n\n\n### Coding Exercise 6.1: Calculation of parameters\n\nFill in the calculation of the parameters of regular convolution and depthwise separable convolution in the function below.\nAbove you can see the example given in the video for you to check if your calculation is correct.\n\n\n```python\ndef convolution_math(in_channels, filter_size, out_channels):\n \"\"\"\n Convolution math: Implement how parameters scale as a function of feature maps\n and filter size in convolution vs depthwise separable convolution.\n\n Args:\n in_channels : number of input channels\n filter_size : size of the filter\n out_channels : number of output channels\n \"\"\"\n ####################################################################\n # Fill in all missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Convolution math\")\n ####################################################################\n # calculate the number of parameters for regular convolution\n conv_parameters = ...\n # calculate the number of parameters for depthwise separable convolution\n depthwise_conv_parameters = ...\n\n print(f\"Depthwise separable: {depthwise_conv_parameters} parameters\")\n print(f\"Regular convolution: {conv_parameters} parameters\")\n\n return None\n\n\n# add event to airtable\natform.add_event('Coding Exercise 6.1: Calculation of parameters')\n\n## Uncomment to test your function\n# convolution_math(in_channels=4, filter_size=3, out_channels=2)\n```\n\n\n```python\n# to_remove solution\ndef convolution_math(in_channels, filter_size, out_channels):\n \"\"\"\n Convolution math: Implement how parameters scale as a function of feature maps\n and filter size in convolution vs depthwise separable convolution.\n\n Args:\n in_channels : number of input channels\n filter_size : size of the filter\n out_channels : number of output channels\n \"\"\"\n # calculate the number of parameters for regular convolution\n conv_parameters = in_channels * filter_size * filter_size * out_channels\n # calculate the number of parameters for depthwise separable convolution\n depthwise_conv_parameters = in_channels * filter_size * filter_size + in_channels * out_channels\n\n print(f\"Depthwise separable: {depthwise_conv_parameters} parameters\")\n print(f\"Regular convolution: {conv_parameters} parameters\")\n\n return None\n\n\n# add event to airtable\natform.add_event('Coding Exercise 6.1: Calculation of parameters')\n\n## Uncomment to test your function\nconvolution_math(in_channels=4, filter_size=3, out_channels=2)\n```\n\n```\nDepthwise separable: 44 parameters\nRegular convolution: 72 parameters\n```\n\n### Think! 6.1: How do parameter savings depend the on number of input feature maps, 4 vs. 64?\n\n\n```python\n# @title Student Response\nfrom ipywidgets import widgets\n\n\ntext=widgets.Textarea(\n value='Type your answer here and click on `Submit!`',\n placeholder='Type something',\n description='',\n disabled=False\n)\n\nbutton = widgets.Button(description=\"Submit!\")\n\ndisplay(text,button)\n\ndef on_button_clicked(b):\n atform.add_answer('q5', text.value)\n print(\"Submission successful!\")\n\n\nbutton.on_click(on_button_clicked)\n```\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nThe more input features the more parameter saving\n 4: 28 less params\n 64: 448 less params\n\"\"\";\n```\n\n---\n# Section 7: Transfer Learning\n\n*Time estimate: ~24mins*\n\n\n```python\n# @title Video 7: Transfer Learning\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1z54y1E714\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"Qr5l-an5ac4\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 7: Transfer Learning')\n\ndisplay(out)\n```\n\nThe most common way large image models are trained in practice is via transfer learning. One first pretrains a network on a large classification dataset like ImageNet, then uses the weights of this network as initialization for training (\"fine-tuning\") that network on your task of choice. \n\nWhile training a network twice sounds like a strange thing to do, the model ends up training faster on the target dataset and often outperforms training \"from scratch\". There are also other benefits such as [robustness to noise](https://arxiv.org/pdf/1901.09960.pdf) that are the subject of [active research](https://arxiv.org/abs/2008.11687).\n\nIn this section we will demonstrate transfer learning by taking a model trained on ImageNet and teaching it to classify Pokemon.\n\n## Section 7.1: Download and prepare the data\n\n\n```python\n# @title Download Data\nimport zipfile, io\n\n# original link: https://github.com/ben-heil/cis_522_data.git\nurl = 'https://osf.io/u4njm/download'\n\nfname = 'small_pokemon_dataset'\n\nif not os.path.exists(fname+'zip'):\n print(\"Data is being downloaded...\")\n r = requests.get(url, stream=True)\n z = zipfile.ZipFile(io.BytesIO(r.content))\n z.extractall()\n print(\"The download has been completed.\")\nelse:\n print(\"Data has already been downloaded.\")\n```\n\n\n```python\n# List the different Pokemon\nos.listdir(\"small_pokemon_dataset/\")\n```\n\n\n```python\n# @title Determine number of classes\nnum_classes = 0\nfor folders in os.listdir('small_pokemon_dataset/'):\n num_classes += 1\nprint(f\"{num_classes} types of Pokemon\")\n```\n\n\n```python\n# @title Display Example Images\ntrain_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\npokemon_dataset = ImageFolder('small_pokemon_dataset',\n transform=train_transform)\n\nimage_count = len(pokemon_dataset)\ntrain_indices = []\ntest_indices = []\nfor i in range(image_count):\n # Put ten percent of the images in the test set\n if random.random() < .1:\n test_indices.append(i)\n else:\n train_indices.append(i)\n\npokemon_test_set = torch.utils.data.Subset(pokemon_dataset, test_indices)\npokemon_train_set = torch.utils.data.Subset(pokemon_dataset, train_indices)\n\npokemon_train_loader = torch.utils.data.DataLoader(pokemon_train_set,\n batch_size=16,\n shuffle=True,)\npokemon_test_loader = torch.utils.data.DataLoader(pokemon_test_set,\n batch_size=16)\n\ndataiter = iter(pokemon_train_loader)\nimages, labels = dataiter.next()\n\n# show images\nplt.imshow(make_grid(images, nrow=4).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n## Section 7.2: Fine-tuning a ResNet\n\nIt is common in computer vision to take a large model trained on a large dataset (often ImageNet), replace the classification layer and fine-tune the entire network to perform a different task. \n\nHere we'll be using a pre-trained ResNet model to classify types of Pokemon.\n\n\n```python\nresnet = torchvision.models.resnet18(pretrained=True)\nnum_ftrs = resnet.fc.in_features\n# reset final fully connected layer, number of classes = types of Pokemon = 9\nresnet.fc = nn.Linear(num_ftrs, num_classes)\nresnet.to(DEVICE)\noptimizer = torch.optim.Adam(resnet.parameters(), lr=1e-4)\nloss_fn = nn.CrossEntropyLoss()\n```\n\n\n```python\n# @title Finetune ResNet\n\npretrained_accs = []\nfor epoch in tqdm.tqdm(range(10)):\n # Train loop\n for batch in pokemon_train_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n optimizer.zero_grad()\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n # Eval loop\n with torch.no_grad():\n loss_sum = 0\n total_correct = 0\n total = len(pokemon_test_set)\n for batch in pokemon_test_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss_sum += loss.item()\n\n predictions = torch.argmax(output, dim=1)\n\n num_correct = torch.sum(predictions == labels)\n total_correct += num_correct\n\n # Plot accuracy\n pretrained_accs.append(total_correct / total)\n plt.plot(pretrained_accs)\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Pokemon prediction accuracy')\n IPython.display.clear_output(wait=True)\n IPython.display.display(plt.gcf())\n plt.close()\n```\n\n## Section 7.3: Train only classification layer\n\nAnother possible way to make use of transfer learning is to take a pre-trained model and replace the last layer, the classification layer (sometimes also called the \"linear readout\"). Instead of fine-tuning the whole model as before, we train only the classification layer.\n\n\n```python\nresnet = torchvision.models.resnet18(pretrained=True)\nfor param in resnet.parameters():\n param.requires_grad = False\nnum_ftrs = resnet.fc.in_features\n# reset final fully connected layer\nresnet.fc = nn.Linear(num_ftrs, num_classes)\nresnet.to(DEVICE)\noptimizer = torch.optim.Adam(resnet.fc.parameters(), lr=1e-2)\nloss_fn = nn.CrossEntropyLoss()\n```\n\n\n```python\n# @title Finetune readout of ResNet\nlinreadout_accs = []\nfor epoch in range(10):\n # Train loop\n for batch in pokemon_train_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n optimizer.zero_grad()\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n # Eval loop\n with torch.no_grad():\n loss_sum = 0\n total_correct = 0\n total = len(pokemon_test_set)\n for batch in pokemon_test_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss_sum += loss.item()\n\n predictions = torch.argmax(output, dim=1)\n\n num_correct = torch.sum(predictions == labels)\n total_correct += num_correct\n\n # Plot accuracy\n linreadout_accs.append(total_correct / total)\n plt.plot(linreadout_accs)\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Pokemon prediction accuracy')\n IPython.display.clear_output(wait=True)\n IPython.display.display(plt.gcf())\n plt.close()\n```\n\n## Section 7.4: Training ResNet from scratch\n\nAs a baseline and for comparison reasons we will also train the ResNet \"from scratch\" – that is: initialize the weights randomly and train the entire network exclusively on the Pokemon dataset.\n\n\n```python\nresnet = torchvision.models.resnet18(pretrained=False)\nnum_ftrs = resnet.fc.in_features\n# reset final fully connected layer\nresnet.fc = nn.Linear(num_ftrs, num_classes)\nresnet.to(DEVICE)\noptimizer = torch.optim.Adam(resnet.parameters(), lr=1e-4)\n\nloss_fn = nn.CrossEntropyLoss()\n```\n\n\n```python\n# @title Train ResNet from scratch\nscratch_accs = []\nfor epoch in tqdm.tqdm(range(10)):\n # Train loop\n for batch in pokemon_train_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n optimizer.zero_grad()\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n\n # Eval loop\n with torch.no_grad():\n loss_sum = 0\n total_correct = 0\n total = len(pokemon_test_set)\n for batch in pokemon_test_loader:\n images, labels = batch\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n output = resnet(images)\n loss = loss_fn(output, labels)\n loss_sum += loss.item()\n\n predictions = torch.argmax(output, dim=1)\n\n num_correct = torch.sum(predictions == labels)\n total_correct += num_correct\n\n scratch_accs.append(total_correct / total)\n plt.plot(scratch_accs)\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.title('Pokemon prediction accuracy')\n\n IPython.display.clear_output(wait=True)\n IPython.display.display(plt.gcf())\n plt.close()\n```\n\n## Section 7.5: Head to Head Comparison\nStarting from a randomly initialized network works less well, especially in the case of small datsets. Note that the model converges more slowly and less evenly.\n\n\n```python\n# @title Plot Accuracies\nplt.plot(pretrained_accs, label='Pretrained: fine-tuning')\nplt.plot(linreadout_accs, label='Pretrained: linear Readout')\nplt.plot(scratch_accs, label='Trained from Scratch')\nplt.title('Pokemon prediction accuracy')\nplt.legend()\nplt.show()\n```\n\n### Exercise 7.5.1\n\nFirst, we compare the Pretrained ResNet with the ResNet trained from scratch. Why might pretrained models outperform models trained from scratch? In what cases would you expect them to be worse?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n1. The closer your pretraining and target data domains are, the better pretraining will work\n2. The more pretraining data you have, the better pretraining will work\n3. The better your model is able to take advantage of your pretraining data (that is to say\n the larger your model is asResNetsuming you have enough data), the better pretraing will work\n\nPretraining isn't necessarily always a benefit though. If you source domain is very different from\nthe domain you're trying to predict, your models might learn unhelpful features.\n\nAdditionally, if you have a lot of training data in your target domain, pretraining data might\ncause your model to converge to a local minimum (this process is referred to as ossification in\nthe Scaling Laws for Transfer paper cited in the Further Reading section)\n\"\"\";\n```\n\n### Exercise 7.5.2\n\nSecond, take a look at the different transfer learning methods - fine-tuning the whole network and training only the classification layer. Why might fine-tuning the whole network outperform training only the classification layer? What are the benefits of training only the classification layer? In what cases would you expect a similar performance of both methods?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\n1. More weights are adjusted to the pretraining domain.\n2. Since only one layer is trained, the training procedure is faster/less computationally expensive.\n3. If your pretraining and target data domains are close.\n\"\"\";\n```\n\n## Further Reading\nSupervised pretraining as you've seen here is useful, but there are several other ways of using outside data to improve your models. The ones that are particularly popular right now are self-supervised techniques like [contrastive learning](https://arxiv.org/pdf/2002.05709.pdf).\n\nThere is also a [recent paper](https://arxiv.org/abs/2102.01293) that seeks to quantify the relationship between model size, pretraining dataset size, training dataset size, and performance.\n\n---\n# Summary\n\nIn this tutorial, you have learned about the modern Convnets (CNNs), their architecture, and operating principles. Also, you are now familiar with the notion of *Transfer Learning*, and you have learned when to apply it. If you have time left, you will learn more about the speed vs. accuracy trade-off. In the next tutorial, we will see the modern convnets in a facial recognition task.\n\n\n```python\n# @title Video 8: Summary and Outlook\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1So4y1D7Ev\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"sjj0-7i6XfE\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 8: Summary and Outlook')\n\ndisplay(out)\n```\n\n\n```python\n# @title Airtable Submission Link\nfrom IPython import display as IPydisplay\nIPydisplay.HTML(\n f\"\"\"\n
\n \n \n
\"\"\" )\n```\n\n---\n# Bonus: Speed-Accuracy Trade-Off / Different Backbones\n\n*Time estimate: ~ 21mins*\n\n\n```python\n# @title Video 9: Speed-accuracy trade-off\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1v64y1z7PT\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"9p4gD-QnbIQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 8: Speed-accuracy trade-off')\n\ndisplay(out)\n```\n\nAs the models got larger and the number of connections increased so did the computational costs involved. In the modern era of image processing, there is a tradeoff between model performance and computational cost. Models can reach extremely high performance on many problems, but achieving state of the art results requires [huge amounts of compute power](https://arxiv.org/pdf/1810.00736.pdf).\n\n\n\n\n## Bonus Coding Exercise: Compare accuracy and training speed of different models\n\nThe goal is to load three pretrained models and fine-tune them.\n`models` is a dictionary where the keys are the names of the models and the values are the corresponding model objects.\nCurrently the names are *ResNet18, AlexNet* and *VGG-19*.\nFor a start, load these models from torchvision.models and make sure they are pretrained.\n\nIf you want to try other models, just change the dictionary, or if you want to even try out more than three models, just add them to the dictionary and add their learning rates in the array below.\n\n\n```python\n# load three pretrained models from torchvision.models\n# [these are just examples, other models are possible as well]\nmodel1 = ...\nmodel2 = ...\nmodel3 = ...\n\nmodels = {'...': model1, '...': model2, '...-19': model3}\nlearning_rates = [1e-4, 1e-4, 1e-4]\n\ntimes, top_1_accuracies = [], []\n```\n\n\n```python\n# to_remove solution\n# load three pretrained models from torchvision.models\n# [these are just examples, other models are possible as well]\nmodel1 = torchvision.models.resnet18(pretrained=True)\nmodel2 = torchvision.models.alexnet(pretrained=True)\nmodel3 = torchvision.models.vgg19(pretrained=True)\n\nmodels = {'ResNet18': model1, 'AlexNet': model2, 'VGG-19': model3}\nlearning_rates = [1e-4, 1e-4, 1e-4]\n\ntimes, top_1_accuracies = [], []\n```\n\n\n```python\n# @title Imagenette Train Loop\ndef train_loop(model, optimizer, train_loader, loss_fn, device):\n\n times = []\n model.to(device)\n for epoch in tqdm.notebook.tqdm(range(5)):\n model.train()\n t_start = time.time()\n # Train on a batch of images\n for imagenette_batch in train_loader:\n images, labels = imagenette_batch\n\n # Convert labels from imagenette indices to imagenet labels\n for i, label in enumerate(labels):\n labels[i] = dir_index_to_imagenet_label[label.item()]\n\n images = images.to(device)\n labels = labels.to(device)\n output = model(images)\n optimizer.zero_grad()\n loss = loss_fn(output, labels)\n loss.backward()\n optimizer.step()\n if torch.cuda.is_available():\n torch.cuda.synchronize()\n\n times += [time.time() - t_start]\n\n return np.mean(times)\n```\n\n\n```python\nfor (name, model), lr in zip(models.items(), learning_rates):\n\n print(name, lr)\n\n model.to(DEVICE)\n model.aux_logits = False # only important for googlenet\n\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n loss_fn = nn.CrossEntropyLoss()\n\n model_time = train_loop(model, optimizer, imagenette_train_loader, loss_fn,\n DEVICE)\n times.append(model_time)\n\n top_1_acc, _ = eval_imagenette(model, imagenette_val_loader,\n len(imagenette_val), device=DEVICE)\n top_1_accuracies.append(top_1_acc.item())\n```\n\n\n```python\n# @title Plot accuracies vs. training speed\ndef get_parameter_count(model):\n return sum([torch.numel(p) for p in model.parameters()])\n\n\ndef plot_acc_speed(times, accs, models):\n ti = [t*1000 for t in times]\n for i, model in enumerate(list(models.keys())):\n scale = get_parameter_count(models[model])*1e-6\n plt.scatter(ti[i], accs[i], s=scale, label=model)\n plt.grid(True)\n plt.xlabel('speed [ms]')\n plt.ylabel('accuracy')\n plt.title('Accuracy vs. speed')\n plt.legend()\n\n\nplot_acc_speed(times, top_1_accuracies, models)\n```\n\n## Bonus Exercise 1\n\nLook at the plot above.\nIt shows the training speed vs. the accuracy of the models you chose.\nThe training speed is measured as the mean time the training takes per epoch.\nThe size of the marker visualizes the number of parameters of the model.\n\nWhich model seems to be the best for this task and why?\nExplain your conclusion based on speed, accuracy and number of parameters.\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nGiven the 3 suggested models, the ResNet is the best model because it has the highest accuracy by being\nalmost as fast as AlexNet and having less parameters.\n\"\"\";\n```\n\n### Bonus Exercise 2\n\nHow does the speed correlate with the accuracy? Are faster models also more accurate?\n\n\n```python\n# to_remove explanation\n\n\"\"\"\nAlso depends on the models they chose.\nFor example, if we compare VGG with ResNet the ResNet is both faster and more accurate.\nAlexNet is a bit faster than ResNet but not as accurate.\n\"\"\";\n```\n", "meta": {"hexsha": "3b9908407a797efacff5d0bab1c06e9958c3be02", "size": 140014, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W2D2_ModernConvnets/W2D2_Tutorial1.ipynb", "max_stars_repo_name": "tmachnitzki/course-content-dl", "max_stars_repo_head_hexsha": "d84b06d42338f294c8a3d293c4f631ac33769518", "max_stars_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/W2D2_ModernConvnets/W2D2_Tutorial1.ipynb", "max_issues_repo_name": "tmachnitzki/course-content-dl", "max_issues_repo_head_hexsha": "d84b06d42338f294c8a3d293c4f631ac33769518", "max_issues_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/W2D2_ModernConvnets/W2D2_Tutorial1.ipynb", "max_forks_repo_name": "tmachnitzki/course-content-dl", "max_forks_repo_head_hexsha": "d84b06d42338f294c8a3d293c4f631ac33769518", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7774465971, "max_line_length": 534, "alphanum_fraction": 0.5649435056, "converted": true, "num_tokens": 27681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34876783486490914}} {"text": "# Primitive model of electrolytes: NaCl in continuum solvent\n\nIn this example we explore the possibility for setting a background dielectric constant for simulating (soft) particles in an implicit solvent.\n\n- Can $\\epsilon_r$ be set for PME/Ewald? Nothing found in the documentation so far except for scaling charges\n- Use a custom nonbonded ff instead?\n- GBSA forces are automatically added when a `` section is encountered in .xml file\n- For ideas for rigid bodies, see openmm forum: https://simtk.org/forums/viewtopic.php?f=161&t=5841&p=14836&hilit=rigid#p14836\n\n\n```python\n%matplotlib inline\nfrom __future__ import print_function\nfrom simtk.openmm import app\nimport simtk.openmm as mm\nfrom simtk import unit\nfrom sys import stdout, exit\nimport numpy as np\nimport math\nimport mdtraj as mdtraj\n\ncutoff = 50*unit.angstrom\ntemperature = 300*unit.kelvin\nuseMinimize = False\nepsilon_r = 80.\nsteps_eq = 5000\nsteps_production = 4e5\n\npdb = app.PDBFile('nacl.pdb')\nforcefield = app.ForceField('cg.xml')\n\nsystem = forcefield.createSystem(pdb.topology, nonbondedMethod=app.Ewald, \n nonbondedCutoff=cutoff, ewaldErrorTolerance=0.1)\n\n# scale charges\ndef scaleCharges(system, scale=1.0):\n \"\"\"\n Scale charges in all appropriate force classes of system. This can\n be used to simulate a system with a different background dielectric\n by setting scale=1/sqrt(epsilon_r), for example.\n \"\"\"\n for force in system.getForces():\n if 'getParticleParameters' in dir(force):\n for i in range(force.getNumParticles()):\n charge, sigma, epsilon = force.getParticleParameters(i)\n force.setParticleParameters(i, scale*charge, sigma, epsilon)\n if 'getExceptionParameters' in dir(force):\n for i in range(force.getNumExceptions()):\n p1, p2, chargeProd, sigma, epsilon = force.getExceptionParameters(i)\n force.setExceptionParameters(i, p1, p2, chargeProd*(scale**2), sigma, epsilon)\n \nscaleCharges(system, scale=1/math.sqrt(epsilon_r))\n\n# set dielectric constant (no effect on pairwise-interactions)\nfor i in system.getForces():\n if isinstance(i, mm.NonbondedForce):\n i.setReactionFieldDielectric(epsilon_r)\n print ('RF dielectric = ', i.getReactionFieldDielectric())\n \nintegrator = mm.LangevinIntegrator(\n temperature,\n 1.0/unit.picoseconds, \n 20.0*unit.femtoseconds)\n\nintegrator.setConstraintTolerance(0.00001)\n\nsimulation = app.Simulation(pdb.topology, system, integrator)\nsimulation.context.setPositions(pdb.positions)\n\nif useMinimize:\n print('Minimizing...')\n simulation.minimizeEnergy()\n\nprint('Equilibrating...')\nsimulation.context.setVelocitiesToTemperature(300*unit.kelvin)\nsimulation.step(steps_eq)\n\nsteps_total = steps_eq + steps_production\nsimulation.reporters.append(mdtraj.reporters.HDF5Reporter('trajectory.h5', 100))\nsimulation.reporters.append(app.PDBReporter('trajectory.pdb', 1000))\nsimulation.reporters.append(app.StateDataReporter(stdout, int(steps_total/10), step=True, \n potentialEnergy=True, temperature=True, progress=True, remainingTime=False, \n speed=True, totalSteps=steps_total, volume=True, separator='\\t'))\n\nprint('Production...')\nsimulation.step(steps_production)\n\nprint('Done!')\n```\n\n RF dielectric = 80.0\n Equilibrating...\n Production...\n #\"Progress (%)\"\t\"Step\"\t\"Potential Energy (kJ/mole)\"\t\"Temperature (K)\"\t\"Box Volume (nm^3)\"\t\"Speed (ns/day)\"\n 10.0%\t40500\t-9.41419052737\t389.559018631\t1000.0\t0\n 20.0%\t81000\t-5.38719238931\t323.348955062\t1000.0\t5.51e+03\n 30.0%\t121500\t-13.2359821502\t358.396576464\t1000.0\t5.5e+03\n 40.0%\t162000\t-10.0617166891\t256.047483629\t1000.0\t5.49e+03\n 50.0%\t202500\t-9.76001213709\t312.319746817\t1000.0\t5.39e+03\n 60.0%\t243000\t-10.6731361359\t308.124138624\t1000.0\t5.41e+03\n 70.0%\t283500\t-9.8400834653\t432.585410388\t1000.0\t5.42e+03\n 80.0%\t324000\t-17.2790620144\t255.991047233\t1000.0\t5.43e+03\n 90.0%\t364500\t-14.271373764\t273.278255592\t1000.0\t5.43e+03\n 100.0%\t405000\t-19.5669405017\t305.142845317\t1000.0\t5.43e+03\n Done!\n\n\n### Plot and compare with Debye-Hückel\n\nCalculate the radial distribution function, $g(r)=\\exp\\left(-w(r)/k_BT\\right)$, between Na+ and Cl- and compare\nthe result with the Debye-Hückel potential for the interaction free energy between two ions in an aqueous salt solution,\n\n\\begin{equation}\nw(r) / k_BT = \\frac{\\lambda_Bz_1z_2}{r}e^{-r/\\lambda_D}\n\\end{equation}\n\nwhere\n$\\lambda_B=e^2/4\\pi\\epsilon_0\\epsilon_rk_BT$ and\n$\\lambda_D=(4\\pi\\lambda_B\\sum \\rho_iz_i^2)^{-1/2}$ are the Bjerrum and Debye lengths, respectively. $\\rho_i$ is the number density of the $i$th ion.\n\n\n```python\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# volume, conc., bjerrum & debye length\nepsilon_0 = 8.8541878176e-12*unit.farad/unit.meter\nN = simulation.system.getNumParticles()\nV = simulation.topology.getUnitCellDimensions()[0]**3\nlB = (unit.elementary_charge**2 /\n (4*math.pi*epsilon_0*epsilon_r*unit.BOLTZMANN_CONSTANT_kB*temperature))\\\n .in_units_of(unit.nanometer)\nlD = 1/unit.sqrt(4*math.pi*lB*N/V)\n\nprint('Salt concentration = ', 0.5*(N/unit.AVOGADRO_CONSTANT_NA/V).in_units_of(unit.molar))\nprint('Bjerrum length = ', lB)\nprint('Debye length = ', lD)\n\n# open trajectory and plot rdf\nsimulation.reporters[0].close()\ntraj = mdtraj.load('trajectory.h5')\nr,g = mdtraj.compute_rdf(traj, traj.topology.select_pairs('name Na', 'name Cl'),\\\n r_range=[0.2,5], bin_width=0.025)\nr=r*unit.nanometer\n\n# plot simulated Na-Cl pmf (red) vs. Debye-Huckel (blue)\nplt.xlabel('$r$/nm')\nplt.ylabel('$w(r)/k_BT$')\nplt.plot(r, -np.log(g), 'r.')\nplt.plot(r, -lB / r * np.exp( -r/lD ), 'b-')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "71364f705d5ef072f4f5d0084ef8b67736f8f6cd", "size": 22875, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "continuum_nacl/nacl.ipynb", "max_stars_repo_name": "mlund/openmm-examples", "max_stars_repo_head_hexsha": "4e0cd1d040511946a67fdd286936525843eb0b80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-13T09:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-13T09:59:54.000Z", "max_issues_repo_path": "continuum_nacl/nacl.ipynb", "max_issues_repo_name": "mlund/openmm-examples", "max_issues_repo_head_hexsha": "4e0cd1d040511946a67fdd286936525843eb0b80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "continuum_nacl/nacl.ipynb", "max_forks_repo_name": "mlund/openmm-examples", "max_forks_repo_head_hexsha": "4e0cd1d040511946a67fdd286936525843eb0b80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 93.75, "max_line_length": 14136, "alphanum_fraction": 0.8118907104, "converted": true, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3487603565866375}} {"text": "##### Copyright 2018 The TensorFlow Probability Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\"); { display-mode: \"form\" }\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Gaussian Process Regression in TensorFlow Probability\n\n\n \n \n \n \n
\n View on TensorFlow.org\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nIn this colab, we explore Gaussian process regression using\nTensorFlow and TensorFlow Probability. We generate some noisy observations from\nsome known functions and fit GP models to those data. We then sample from the GP\nposterior and plot the sampled function values over grids in their domains.\n\n\n## Background\nLet $\\mathcal{X}$ be any set. A *Gaussian process*\n(GP) is a collection of random variables indexed by $\\mathcal{X}$ such that if\n$\\{X_1, \\ldots, X_n\\} \\subset \\mathcal{X}$ is any finite subset, the marginal density\n$p(X_1 = x_1, \\ldots, X_n = x_n)$ is multivariate Gaussian. Any Gaussian\ndistribution is completely specified by its first and second central moments\n(mean and covariance), and GP's are no exception. We can specify a GP completely\nin terms of its mean function $\\mu : \\mathcal{X} \\to \\mathbb{R}$ and covariance function\n$k : \\mathcal{X} \\times \\mathcal{X} \\to \\mathbb{R}$. Most of the expressive power of GP's is encapsulated\nin the choice of covariance function. For various reasons, the covariance\nfunction is also referred to as a *kernel function*. It is required only to be\nsymmetric and positive-definite (see [Ch. 4 of Rasmussen & Williams](\nhttp://www.gaussianprocess.org/gpml/chapters/RW4.pdf)). Below we make use of the\nExponentiatedQuadratic covariance kernel. Its form is\n\n$$\nk(x, x') := \\sigma^2 \\exp \\left( \\frac{\\|x - x'\\|^2}{\\lambda^2} \\right)\n$$\n\nwhere $\\sigma^2$ is called the 'amplitude' and $\\lambda$ the *length scale*.\nThe kernel parameters can be selected via a maximum likelihood optimization\nprocedure.\n\nA full sample from a GP comprises a real-valued function over the entire space\n$\\mathcal{X}$ and is in practice impractical to realize; often one chooses a set of\npoints at which to observe a sample and draws function values at these points.\nThis is achieved by sampling from an appropriate (finite-dimensional)\nmulti-variate Gaussian.\n\nNote that, according to the above definition, any finite-dimensional\nmultivariate Gaussian distribution is also a Gaussian process. Usually, when\none refers to a GP, it is implicit that the index set is some $\\mathbb{R}^n$\nand we will indeed make this assumption here.\n\nA common application of Gaussian processes in machine learning is Gaussian\nprocess regression. The idea is that we wish to estimate an unknown function\ngiven noisy observations $\\{y_1, \\ldots, y_N\\}$ of the function at a finite\nnumber of points $\\{x_1, \\ldots x_N\\}.$ We imagine a generative process\n\n$$\n\\begin{align}\nf \\sim \\: & \\textsf{GaussianProcess}\\left(\n \\text{mean_fn}=\\mu(x),\n \\text{covariance_fn}=k(x, x')\\right) \\\\\ny_i \\sim \\: & \\textsf{Normal}\\left(\n \\text{loc}=f(x_i),\n \\text{scale}=\\sigma\\right), i = 1, \\ldots, N\n\\end{align}\n$$\n\nAs noted above, the sampled function is impossible to compute, since we would\nrequire its value at an infinite number of points. Instead, one considers a\nfinite sample from a multivariate Gaussian.\n\n$$\n \\begin{gather}\n \\begin{bmatrix}\n f(x_1) \\\\\n \\vdots \\\\\n f(x_N)\n \\end{bmatrix}\n \\sim\n \\textsf{MultivariateNormal} \\left( \\:\n \\text{loc}=\n \\begin{bmatrix}\n \\mu(x_1) \\\\\n \\vdots \\\\\n \\mu(x_N)\n \\end{bmatrix} \\:,\\:\n \\text{scale}=\n \\begin{bmatrix}\n k(x_1, x_1) & \\cdots & k(x_1, x_N) \\\\\n \\vdots & \\ddots & \\vdots \\\\\n k(x_N, x_1) & \\cdots & k(x_N, x_N) \\\\\n \\end{bmatrix}^{1/2}\n \\: \\right)\n \\end{gather} \\\\\n y_i \\sim \\textsf{Normal} \\left(\n \\text{loc}=f(x_i),\n \\text{scale}=\\sigma\n \\right)\n$$\n\nNote the exponent $\\frac{1}{2}$ on the covariance matrix: this denotes a\nCholesky decomposition. Comptuing the Cholesky is necessary because the MVN is\na location-scale family distribution. Unfortunately the Cholesky decomposition\nis computationally expensive, taking $O(N^3)$ time and $O(N^2)$ space. Much of\nthe GP literature is focused on dealing with this seemingly innocuous little\nexponent.\n\nIt is common to take the prior mean function to be constant, often zero. Also,\nsome notational conventions are convenient. One often writes $\\mathbf{f}$ for the\nfinite vector of sampled function values. A number of interesting notations are\nused for the covariance matrix resulting from the application of $k$ to pairs of\ninputs. Following [(Quiñonero-Candela, 2005)][QuinoneroCandela2005], we note\nthat the components of the matrix are covariances of function values at\nparticular input points. Thus we can denote the covariance matrix as $K_{AB}$\nwhere $A$ and $B$ are some indicators of the collection of function values along\nthe given matrix dimensions.\n\n[QuinoneroCandela2005]: http://www.jmlr.org/papers/volume6/quinonero-candela05a/quinonero-candela05a.pdf\n\nFor example, given observed data $(\\mathbf{x}, \\mathbf{y})$ with implied latent function\nvalues $\\mathbf{f}$, we can write\n\n$$\nK_{\\mathbf{f},\\mathbf{f}} = \\begin{bmatrix}\n k(x_1, x_1) & \\cdots & k(x_1, x_N) \\\\\n \\vdots & \\ddots & \\vdots \\\\\n k(x_N, x_1) & \\cdots & k(x_N, x_N) \\\\\n\\end{bmatrix}\n$$\n\nSimilarly, we can mix sets of inputs, as in\n\n$$\nK_{\\mathbf{f},*} = \\begin{bmatrix}\n k(x_1, x^*_1) & \\cdots & k(x_1, x^*_T) \\\\\n \\vdots & \\ddots & \\vdots \\\\\n k(x_N, x^*_1) & \\cdots & k(x_N, x^*_T) \\\\\n\\end{bmatrix}\n$$\n\nwhere we suppose there are $N$ training inputs, and $T$ test inputs. The above\ngenerative process may then be written compactly as\n\n$$\n\\begin{align}\n\\mathbf{f} \\sim \\: & \\textsf{MultivariateNormal} \\left(\n \\text{loc}=\\mathbf{0},\n \\text{scale}=K_{\\mathbf{f},\\mathbf{f}}^{1/2}\n \\right) \\\\\ny_i \\sim \\: & \\textsf{Normal} \\left(\n \\text{loc}=f_i,\n \\text{scale}=\\sigma \\right), i = 1, \\ldots, N\n\\end{align}\n$$\n\nThe sampling operation in the first line yields a finite set of $N$ function\nvalues from a multivariate Gaussian -- *not an entire function as in the above\nGP draw notation*. The second line describes a collection of $N$ draws from\n*univariate* Gaussians centered at the various function values, with fixed\nobservation noise $\\sigma^2$.\n\nWith the above generative model in place, we can proceed to consider the\nposterior inference problem. This yields a posterior distribution over function\nvalues at a new set of test points, conditioned on the observed noisy data from\nthe process above.\n\nWith the above notation in place, we can compactly write the posterior\npredictive distribution over future (noisy) observations conditional on\ncorresponding inputs and training data as follows (for more details, see §2.2 of\n[Rasmussen & Williams](http://www.gaussianprocess.org/gpml/)). \n\n$$\n\\mathbf{y}^* \\mid \\mathbf{x}^*, \\mathbf{x}, \\mathbf{y} \\sim \\textsf{Normal} \\left(\n \\text{loc}=\\mathbf{\\mu}^*,\n \\text{scale}=(\\Sigma^*)^{1/2}\n\\right),\n$$\n\nwhere\n\n$$\n\\mathbf{\\mu}^* = K_{*,\\mathbf{f}}\\left(K_{\\mathbf{f},\\mathbf{f}} + \\sigma^2 I \\right)^{-1} \\mathbf{y}\n$$\n\nand\n\n$$\n\\Sigma^* = K_{*,*} - K_{*,\\mathbf{f}}\n \\left(K_{\\mathbf{f},\\mathbf{f}} + \\sigma^2 I \\right)^{-1} K_{\\mathbf{f},*}\n$$\n\n## Imports\n\n\n```\nimport time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow.compat.v2 as tf\nimport tensorflow_probability as tfp\ntfb = tfp.bijectors\ntfd = tfp.distributions\ntfk = tfp.math.psd_kernels\ntf.enable_v2_behavior()\n\nfrom mpl_toolkits.mplot3d import Axes3D\n%pylab inline\n# Configure plot defaults\nplt.rcParams['axes.facecolor'] = 'white'\nplt.rcParams['grid.color'] = '#666666'\n%config InlineBackend.figure_format = 'png'\n```\n\n Populating the interactive namespace from numpy and matplotlib\n\n\n## Example: Exact GP Regression on Noisy Sinusoidal Data\nHere we generate training data from a noisy sinusoid, then sample a bunch of\ncurves from the posterior of the GP regression model. We use\n[Adam](https://arxiv.org/abs/1412.6980) to optimize the kernel hyperparameters\n(we minimize the negative log likelihood of the data under the prior). We\nplot the training curve, followed by the true function and the posterior\nsamples.\n\n\n```\ndef sinusoid(x):\n return np.sin(3 * np.pi * x[..., 0])\n\ndef generate_1d_data(num_training_points, observation_noise_variance):\n \"\"\"Generate noisy sinusoidal observations at a random set of points.\n\n Returns:\n observation_index_points, observations\n \"\"\"\n index_points_ = np.random.uniform(-1., 1., (num_training_points, 1))\n index_points_ = index_points_.astype(np.float64)\n # y = f(x) + noise\n observations_ = (sinusoid(index_points_) +\n np.random.normal(loc=0,\n scale=np.sqrt(observation_noise_variance),\n size=(num_training_points)))\n return index_points_, observations_\n```\n\n\n```\n# Generate training data with a known noise level (we'll later try to recover\n# this value from the data).\nNUM_TRAINING_POINTS = 100\nobservation_index_points_, observations_ = generate_1d_data(\n num_training_points=NUM_TRAINING_POINTS,\n observation_noise_variance=.1)\n```\n\nWe'll put priors on the kernel hyperparameters, and write the joint distribution of the hyperparameters and observed data using `tfd.JointDistributionNamed`.\n\n\n```\ndef build_gp(amplitude, length_scale, observation_noise_variance):\n \"\"\"Defines the conditional dist. of GP outputs, given kernel parameters.\"\"\"\n\n # Create the covariance kernel, which will be shared between the prior (which we\n # use for maximum likelihood training) and the posterior (which we use for\n # posterior predictive sampling)\n kernel = tfk.ExponentiatedQuadratic(amplitude, length_scale)\n\n # Create the GP prior distribution, which we will use to train the model\n # parameters.\n return tfd.GaussianProcess(\n kernel=kernel,\n index_points=observation_index_points_,\n observation_noise_variance=observation_noise_variance)\n\ngp_joint_model = tfd.JointDistributionNamed({\n 'amplitude': tfd.LogNormal(loc=0., scale=np.float64(1.)),\n 'length_scale': tfd.LogNormal(loc=0., scale=np.float64(1.)),\n 'observation_noise_variance': tfd.LogNormal(loc=0., scale=np.float64(1.)),\n 'observations': build_gp,\n})\n```\n\nWe can sanity-check our implementation by verifying that we can sample from the prior, and compute the log-density of a sample.\n\n\n```\nx = gp_joint_model.sample()\nlp = gp_joint_model.log_prob(x)\n\nprint(\"sampled {}\".format(x))\nprint(\"log_prob of sample: {}\".format(lp))\n```\n\n sampled {'observation_noise_variance': , 'length_scale': , 'amplitude': , 'observations': }\n log_prob of sample: -194.96442183797524\n\n\nNow let's optimize to find the parameter values with highest posterior probability. We'll define a variable for each parameter, and constrain their values to be positive.\n\n\n```\n# Create the trainable model parameters, which we'll subsequently optimize.\n# Note that we constrain them to be strictly positive.\n\nconstrain_positive = tfb.Shift(np.finfo(np.float64).tiny)(tfb.Exp())\n\namplitude_var = tfp.util.TransformedVariable(\n initial_value=1.,\n bijector=constrain_positive,\n name='amplitude',\n dtype=np.float64)\n\nlength_scale_var = tfp.util.TransformedVariable(\n initial_value=1.,\n bijector=constrain_positive,\n name='length_scale',\n dtype=np.float64)\n\nobservation_noise_variance_var = tfp.util.TransformedVariable(\n initial_value=1.,\n bijector=constrain_positive,\n name='observation_noise_variance_var',\n dtype=np.float64)\n\ntrainable_variables = [v.trainable_variables[0] for v in \n [amplitude_var,\n length_scale_var,\n observation_noise_variance_var]]\n```\n\nTo condition the model on our observed data, we'll define a `target_log_prob` function, which takes the (still to be inferred) kernel hyperparameters.\n\n\n```\ndef target_log_prob(amplitude, length_scale, observation_noise_variance):\n return gp_joint_model.log_prob({\n 'amplitude': amplitude,\n 'length_scale': length_scale,\n 'observation_noise_variance': observation_noise_variance,\n 'observations': observations_\n })\n```\n\n\n```\n# Now we optimize the model parameters.\nnum_iters = 1000\noptimizer = tf.optimizers.Adam(learning_rate=.01)\n\n# Use `tf.function` to trace the loss for more efficient evaluation.\n@tf.function(autograph=False, jit_compile=False)\ndef train_model():\n with tf.GradientTape() as tape:\n loss = -target_log_prob(amplitude_var, length_scale_var,\n observation_noise_variance_var)\n grads = tape.gradient(loss, trainable_variables)\n optimizer.apply_gradients(zip(grads, trainable_variables))\n return loss\n\n# Store the likelihood values during training, so we can plot the progress\nlls_ = np.zeros(num_iters, np.float64)\nfor i in range(num_iters):\n loss = train_model()\n lls_[i] = loss\n\nprint('Trained parameters:')\nprint('amplitude: {}'.format(amplitude_var._value().numpy()))\nprint('length_scale: {}'.format(length_scale_var._value().numpy()))\nprint('observation_noise_variance: {}'.format(observation_noise_variance_var._value().numpy()))\n```\n\n Trained parameters:\n amplitude: 0.9176153445125278\n length_scale: 0.18444082442910079\n observation_noise_variance: 0.0880273312850989\n\n\n\n```\n# Plot the loss evolution\nplt.figure(figsize=(12, 4))\nplt.plot(lls_)\nplt.xlabel(\"Training iteration\")\nplt.ylabel(\"Log marginal likelihood\")\nplt.show()\n```\n\n\n```\n# Having trained the model, we'd like to sample from the posterior conditioned\n# on observations. We'd like the samples to be at points other than the training\n# inputs.\npredictive_index_points_ = np.linspace(-1.2, 1.2, 200, dtype=np.float64)\n# Reshape to [200, 1] -- 1 is the dimensionality of the feature space.\npredictive_index_points_ = predictive_index_points_[..., np.newaxis]\n\noptimized_kernel = tfk.ExponentiatedQuadratic(amplitude_var, length_scale_var)\ngprm = tfd.GaussianProcessRegressionModel(\n kernel=optimized_kernel,\n index_points=predictive_index_points_,\n observation_index_points=observation_index_points_,\n observations=observations_,\n observation_noise_variance=observation_noise_variance_var,\n predictive_noise_variance=0.)\n\n# Create op to draw 50 independent samples, each of which is a *joint* draw\n# from the posterior at the predictive_index_points_. Since we have 200 input\n# locations as defined above, this posterior distribution over corresponding\n# function values is a 200-dimensional multivariate Gaussian distribution!\nnum_samples = 50\nsamples = gprm.sample(num_samples)\n```\n\n\n```\n# Plot the true function, observations, and posterior samples.\nplt.figure(figsize=(12, 4))\nplt.plot(predictive_index_points_, sinusoid(predictive_index_points_),\n label='True fn')\nplt.scatter(observation_index_points_[:, 0], observations_,\n label='Observations')\nfor i in range(num_samples):\n plt.plot(predictive_index_points_, samples[i, :], c='r', alpha=.1,\n label='Posterior Sample' if i == 0 else None)\nleg = plt.legend(loc='upper right')\nfor lh in leg.legendHandles: \n lh.set_alpha(1)\nplt.xlabel(r\"Index points ($\\mathbb{R}^1$)\")\nplt.ylabel(\"Observation space\")\nplt.show()\n```\n\n*Note: if you run the above code several times, sometimes it looks great and\nother times it looks terrible! The maximum likelihood training of the parameters\nis quite sensitive and sometimes converges to poor models. The best approach\nis to use MCMC to marginalize the model hyperparameters.*\n\n## Marginalizing hyperparameters with HMC\n\nInstead of optimizing the hyperparameters, let's try integrating them out with Hamiltonian Monte Carlo. We'll first define and run a sampler to approximately draw from the posterior distribution over kernel hyperparameters, given the observations.\n\n\n```\nnum_results = 100\nnum_burnin_steps = 50\n\nsampler = tfp.mcmc.TransformedTransitionKernel(\n tfp.mcmc.NoUTurnSampler(\n target_log_prob_fn=target_log_prob,\n step_size=tf.cast(0.1, tf.float64)),\n bijector=[constrain_positive, constrain_positive, constrain_positive])\n\nadaptive_sampler = tfp.mcmc.DualAveragingStepSizeAdaptation(\n inner_kernel=sampler,\n num_adaptation_steps=int(0.8 * num_burnin_steps),\n target_accept_prob=tf.cast(0.75, tf.float64))\n\ninitial_state = [tf.cast(x, tf.float64) for x in [1., 1., 1.]]\n```\n\n\n```\n# Speed up sampling by tracing with `tf.function`.\n@tf.function(autograph=False, jit_compile=False)\ndef do_sampling():\n return tfp.mcmc.sample_chain(\n kernel=adaptive_sampler,\n current_state=initial_state,\n num_results=num_results,\n num_burnin_steps=num_burnin_steps,\n trace_fn=lambda current_state, kernel_results: kernel_results)\n\nt0 = time.time()\nsamples, kernel_results = do_sampling()\nt1 = time.time()\nprint(\"Inference ran in {:.2f}s.\".format(t1-t0))\n```\n\n Inference ran in 9.00s.\n\n\nLet's sanity-check the sampler by examining the hyperparameter traces. \n\n\n```\n(amplitude_samples,\n length_scale_samples,\n observation_noise_variance_samples) = samples\n\nf = plt.figure(figsize=[15, 3])\nfor i, s in enumerate(samples):\n ax = f.add_subplot(1, len(samples) + 1, i + 1)\n ax.plot(s)\n```\n\nNow instead of constructing a single GP with the optimized hyperparameters, we construct the *posterior predictive distribution* as a mixture of GPs, each defined by a sample from the posterior distribution over hyperparameters. This approximately integrates over the posterior parameters via Monte Carlo sampling to compute the marginal predictive distribution at unobserved locations.\n\n\n```\n# The sampled hyperparams have a leading batch dimension, `[num_results, ...]`,\n# so they construct a *batch* of kernels.\nbatch_of_posterior_kernels = tfk.ExponentiatedQuadratic(\n amplitude_samples, length_scale_samples)\n\n# The batch of kernels creates a batch of GP predictive models, one for each\n# posterior sample.\nbatch_gprm = tfd.GaussianProcessRegressionModel(\n kernel=batch_of_posterior_kernels,\n index_points=predictive_index_points_,\n observation_index_points=observation_index_points_,\n observations=observations_,\n observation_noise_variance=observation_noise_variance_samples,\n predictive_noise_variance=0.)\n\n# To construct the marginal predictive distribution, we average with uniform\n# weight over the posterior samples.\npredictive_gprm = tfd.MixtureSameFamily(\n mixture_distribution=tfd.Categorical(logits=tf.zeros([num_results])),\n components_distribution=batch_gprm)\n\nnum_samples = 50\nsamples = predictive_gprm.sample(num_samples)\n```\n\n\n```\n# Plot the true function, observations, and posterior samples.\nplt.figure(figsize=(12, 4))\nplt.plot(predictive_index_points_, sinusoid(predictive_index_points_),\n label='True fn')\nplt.scatter(observation_index_points_[:, 0], observations_,\n label='Observations')\nfor i in range(num_samples):\n plt.plot(predictive_index_points_, samples[i, :], c='r', alpha=.1,\n label='Posterior Sample' if i == 0 else None)\nleg = plt.legend(loc='upper right')\nfor lh in leg.legendHandles: \n lh.set_alpha(1)\nplt.xlabel(r\"Index points ($\\mathbb{R}^1$)\")\nplt.ylabel(\"Observation space\")\nplt.show()\n```\n\nAlthough the differences are subtle in this case, in general, we would expect the posterior predictive distribution to generalize better (give higher likelihood to held-out data) than just using the most likely parameters as we did above.\n", "meta": {"hexsha": "2a86903c1e83c0cb03a8e7dda444de47dcaef50a", "size": 274886, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tensorflow_probability/examples/jupyter_notebooks/Gaussian_Process_Regression_In_TFP.ipynb", "max_stars_repo_name": "jakee417/probability-1", "max_stars_repo_head_hexsha": "ae7117f37ac441bc7a888167ea23e5e620c5bcde", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3670, "max_stars_repo_stars_event_min_datetime": "2018-02-14T03:29:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T01:19:52.000Z", "max_issues_repo_path": "tensorflow_probability/examples/jupyter_notebooks/Gaussian_Process_Regression_In_TFP.ipynb", "max_issues_repo_name": "jakee417/probability-1", "max_issues_repo_head_hexsha": "ae7117f37ac441bc7a888167ea23e5e620c5bcde", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1395, "max_issues_repo_issues_event_min_datetime": "2018-02-24T02:28:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:12:06.000Z", "max_forks_repo_path": "tensorflow_probability/examples/jupyter_notebooks/Gaussian_Process_Regression_In_TFP.ipynb", "max_forks_repo_name": "jakee417/probability-1", "max_forks_repo_head_hexsha": "ae7117f37ac441bc7a888167ea23e5e620c5bcde", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1135, "max_forks_repo_forks_event_min_datetime": "2018-02-14T01:51:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:24:11.000Z", "avg_line_length": 303.0716648291, "max_line_length": 90774, "alphanum_fraction": 0.913349534, "converted": true, "num_tokens": 6108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6513548714339144, "lm_q1q2_score": 0.3485389681825762}} {"text": "```python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 27 17:17:43 2018\n\nBlinker analysis\n\n@author: Viva Horowitz\n\"\"\"\n\nimport numpy as np\nimport matplotlib as mpl\nmpl.rcParams.update(mpl.rcParamsDefault) # default params\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport datetime\nimport seaborn as sns\nimport numpy as np\nsns.set(style='ticks')\nsns.set_context('poster')\nfrom __future__ import division # division should return float\n\n%pylab inline\n\nprint(np.__version__)\nprint(mpl.__version__)\nprint(pd.__version__)\nprint(sns.__version__)\n\n# ** set for each dataset\ndatadate = '2018-05-25'\ndatafolder = r'O:\\User\\Viva\\data\\2018-05-25_blinking-statistics'\nfilename = 'GoodBlinker_5-25-2018.txt'\nanalysisfolder = r'O:\\User\\Viva\\analysis\\blinker_analysis'\n\nos.chdir(datafolder)\n\ntname = 'Time (s)'\nPLname = 'PL Intensity (kCts/s)'\ndata = pd.read_csv(filename,\n skiprows=1,\n header=None,\n sep='\\t',\n names=['Time (s)','PL Intensity (kCts/s)'],\n usecols=[0,1])\ndata = data.set_index(tname)\nprint(data.head())\nrebincount = 0\n\ndata.plot(linewidth=0.3)\nplt.ylabel('photoluminescence (kCts/s)')\nplt.show()\n\nfilename = filename.replace('\\\\','-')\norigfilename = filename\nos.chdir(analysisfolder)\ntoday = datetime.date.isoformat(datetime.date.today())\nif not os.path.exists('taken-' + datadate):\n os.makedirs('taken-' + datadate)\nos.chdir('taken-' + datadate)\n\nprint('today: '+today)\nos.getcwd()\n```\n\n\n```python\nfig1,axPL = plt.subplots()\n#axPL.plot(data, 'k')\n#axPL.legend.remove()\ndata.plot(marker='.',linestyle='None',legend=False, ax=axPL, color='k', alpha=.1)\ndata.plot(legend=False, linewidth=0.5, alpha=0.2, ax=axPL, color='k')\nplt.ylabel('photoluminescence (kCts/s)')\nplt.xlabel(tname)\n\nplt.title(filename)\n\nsns.despine()\nplt.savefig(today + ',' + filename+',blinking.pdf', bbox_inches='tight')\nplt.savefig(today + ',' + filename+',blinking.png', bbox_inches='tight', dpi=200)\n\nplt.show()\n\ndef arangebylength(start, step, length):\n return np.arange(start = start, stop=start+step*(length-.5), step = step )\n\n# rebin: combine two rows into one.\ndef rebindata(data, colname=PLname, indexname = tname):\n first = 1 # this is a value that indicates if we're on the first (=1) or the second (-1) of a pair of two bins\n rebinvals = []\n\n for value in data[colname]:\n if first == 1:\n prevval = value\n else:\n # calculate average of the two bins\n combined = (prevval + value) /2.0 \n rebinvals.append(combined)\n del prevval\n first = -1 * first\n \n timesetting = data.index[1]-data.index[0]\n rebintimes = arangebylength(start =0, step = timesetting*2, length = len(rebinvals) )\n rebinneddata = pd.DataFrame(data = rebinvals, index = rebintimes, columns =[colname])\n rebinneddata.index.name=indexname\n return rebinneddata\n\n# The data was collected at a particular rate\ntimesetting = data.index[1]-data.index[0]\nfps = 1/timesetting\nprint('Collection rate: ' + str(fps) + ' Hz')\nprint('Time bin size: ' + str(timesetting) + ' sec')\n```\n\n\n```python\n# *** run this an appropriate number of times, can skip if not rebinning\n\nn = 0 # number of times to rebin.\n\nfor i in range(n):\n data = rebindata(data)\n rebincount = rebincount + 1\n print(rebincount)\n\ntimesetting = data.index[1]-data.index[0]\nfps = 1/timesetting\nprint('Effective collection rate: ' + str(fps) + ' Hz')\nprint('Time bin size: ' + str(timesetting) + ' sec')\nfilename = origfilename + ', ' + str(fps) + ' Hz'\n\n\nfig1,axPL = plt.subplots()\n#axPL.plot(data, 'k')\n#axPL.legend.remove()\ndata.plot(marker='.',linestyle='None',legend=False, ax=axPL, color='k', alpha=.1)\ndata.plot(legend=False, linewidth=0.5, alpha=0.2, ax=axPL, color='k')\nplt.ylabel('photoluminescence (kCts/s)')\nplt.xlabel(tname)\n\nplt.title(filename)\n\nsns.despine()\n#plt.savefig(today + ',' + filename+',blinking.pdf', bbox_inches='tight')\n#plt.savefig(today + ',' + filename+',blinking.png', bbox_inches='tight', dpi=200)\n\nplt.show()\n```\n\n\n```python\nbinsequence = np.arange(data.min(), data.max(), fps/200)# ** adjust bins as needed. Higher denominator: more bins\nprint (str(len(binsequence)) + ' bins')\n\n#data.hist(bins= binsequence)\nsns.distplot(data, bins=binsequence, kde=False, rug=False, kde_kws={'bw':.5, 'label':'KDE'}, norm_hist=False); # must norm if KDE\nplt.xlabel('photoluminescence (kCts/s)')\n#plt.locator_params(axis='x', nbins=10)\nax = plt.gca()\n\n# ** Need to pick an appropriate threshold between on and off for each dataset\nuthreshold = 15.2\nlthreshold = uthreshold-2.5\n\nax.axvline(x=uthreshold, color='k')\nax.axvline(x=lthreshold, color = 'k')\n#ax.tick_params(axis='x',which='minor',bottom='on')\n#ax.xaxis.set_minor_locator(minorLocator)\n\nplt.title(filename)\nplt.ylabel('Occurrences')\nsns.despine()\n\n#plt.savefig(today + ',' + filename+',PLhistogram.pdf', bbox_inches='tight')\n#plt.savefig(today + ',' + filename+',PLhistogram.png', bbox_inches='tight', dpi=200)\n\nplt.show()\n```\n\n\n```python\n# With an uthreshold and an lthreshold\n# This code has an in between status where it won't be counted as remaining in the state \n# but it won't be counted in the other state, either. \n# This seems like the most straightforward way to deal with (rare) cases in between.\n# Other options are shown.\n\n\nthreshdata = data[PLname].clip(upper=uthreshold, lower=lthreshold)\n\n\nfig2,[axPL,axhist] = plt.subplots(nrows=1, ncols=2, figsize=(10,5), sharey=True, gridspec_kw = {'width_ratios':[4,2]})\ndata.plot(marker='.',linestyle='None',legend=False, alpha=0.1, ax=axPL, color='k')\ndata.plot(legend=False, linewidth=0.5, alpha=0.2, ax=axPL, color='k')\nthreshdata.plot(legend=False, ax=axPL)\naxPL.set_ylabel('photoluminescence (kCts/s)')\naxPL.set_xlabel(tname)\nplt.suptitle(filename)\nsns.despine()\nplt.tight_layout() \n\nsns.distplot(data, bins=binsequence, kde=True, rug=False, ax=axhist, vertical=True, color='k',\n kde_kws={'bw':.5});\n# kde_kws={'bw':.5, 'label':'Kernal density\\nestimate (KDE)'});\n#axhist.set_xlabel('photoluminescence (kCts/s)')\naxhist.set_xlabel('Occurrences (normed)')\naxhist.axhline(y=uthreshold)\naxhist.axhline(y=lthreshold)\n\nplt.savefig(today + ',' + filename+',blinkingandthreshold.pdf', bbox_inches='tight')\nplt.savefig(today + ',' + filename+',blinkingandthreshold.png', bbox_inches='tight', dpi=200)\n\nplt.show();\n```\n\n\n```python\n# Main method: in between status where it won't be counted as remaining in the state \n# but it won't be counted in the other state, either.\ndowntimes2= threshdata[threshdata != uthreshold].index\nuptimes2=threshdata[threshdata != lthreshold].index\n\n#print(uptimes2)\n#print(downtimes2)\n\n# Alternate option (not used)\nuptimes= threshdata[threshdata == uthreshold].index\ndowntimes=threshdata[threshdata == lthreshold].index\n\n#print(uptimes)\n#print(downtimes)\n\n# We can compare the two ways of interpreting blinks.\n# There is a discrepancy at about 22 seconds between the two interpretations. \n# It's a matter of whether we consider it stayed off or \n# if we consider that it came up enough to have ended the off blink and began another.\n# I tend to think it ended one and began another in this case, so I'm going to use uptimesep2 as my off duration.\n\n# subtracting each time from the last time we had the same state gives the amount of time it was not in that state.\n# Therefore the separation between up times is in fact the duration of time off.\nuptimesep = uptimes[1:] - uptimes[:-1]\nuptimesep2 = uptimes2[1:] - uptimes2[:-1]\n\n\"\"\"\nplt.plot(uptimes[:-1],uptimesep, '.-')\nplt.plot(uptimes2[:-1],uptimesep2, '-')\nplt.ylim(ymin=3*timesetting)\n#plt.axis('equal')\nplt.xlabel(tname)\nplt.ylabel('duration of blink off (s)')\nplt.figure()\ndata.plot()\nplt.show()\n\"\"\"\n\n# We can compare the two ways of interpreting blinks. It looks like they mostly agree.\n\ndowntimesep = downtimes[1:] - downtimes[:-1]\ndowntimesep2 = downtimes2[1:] - downtimes2[:-1]\n\n\"\"\"\nplt.plot(downtimes[:-1],downtimesep,'.-')\nplt.plot(downtimes2[:-1],downtimesep2,'-')\nplt.ylim(ymin=3*timesetting)\n#plt.axis('equal')\nplt.xlabel(tname)\nplt.ylabel('duration of blink on (s)')\n#plt.figure()\ndata.plot()\nplt.show()\n\"\"\"\n\n# I chose to use downtimesep2 and uptimesep2, as detailed above.\n\nontimes = filter(lambda a: a > 1.5*timesetting, downtimesep2) # requires python 2\nofftimes = filter(lambda a: a > 1.5*timesetting, uptimesep2)\n\n# save analyzed data: bright state duration\nontimesdf = pd.DataFrame(ontimes, columns=[\"Bright state duration (s)\"])\nontimesdf.to_csv(filename+' uptimes.csv', index=False, header=True)\nprint('Uptimes saved to: ')\nprint(os.path.join(os.getcwd(), filename+ ' uptimes.csv'))\n# save analyzed data: dim state duration\nofftimesdf = pd.DataFrame(offtimes, columns=[\"Dim state duration (s)\"])\nofftimesdf.to_csv(filename+' downtimes.csv', index=False, header=True)\nprint('Downtimes saved to: ')\nprint(os.path.join(os.getcwd(), filename+ ' downtimes.csv'))\n## to open: \n# ontimesdf = pd.read_csv(filename+' ontimes.csv'\n# offtimesdf = pd.read_csv(filename+' downtimes.csv')\n# # convert to list or else the rest of the code won't work.\n# ontimes = list(ontimesdf['Bright state duration (s)'])\n# offtimes = list(offtimesdf[\"Dim state duration (s)\"])\n\n## https://stackoverflow.com/questions/32765333/how-do-i-replicate-this-matlab-function-in-numpy/32765547#32765547\ndef histc(X, bins):\n map_to_bins = np.digitize(X,bins)\n r = np.zeros(bins.shape)\n for i in map_to_bins:\n r[i-1] += 1\n return [r, map_to_bins]\n\ndef CDF(S):\n M = len(S); # size of array = number of elements\n sorteddata = sort(S); # ascending sort is CDF, descending sort is 1-CDF\n cum_prob = [elem/M for elem in range(M)] # probability integrated from 0 to sorteddata.\n cum_prob2 = [1-p for p in cum_prob] # probability integrated from sorteddata to inf\n return sorteddata,cum_prob2\n\ndef nonlinearhistc(X,bins, thresh=3, verbose = True):\n map_to_bins = np.digitize(X,bins)\n r = np.zeros(bins.shape)\n for i in map_to_bins:\n r[i-1] += 1\n if verbose:\n print r \n #print bins\n ## normalize by bin width\n probability = np.zeros(bins.shape)\n area = 0;\n thinbincount = 0\n for i in range(len(bins)-1):\n if r[i]<=1:\n thinbincount += 1;\n thisbinwidth = bins[i+1] - bins[i]\n probability[i] = r[i]/thisbinwidth\n area += probability[i]*thisbinwidth;\n \n if thinbincount > thresh:\n print(\"Warning: too many bins for data, thinbincount=\" + str(thinbincount))\n elif verbose:\n print(\"thinbincount=\" + str(thinbincount))\n ## normalize area.\n normedprobability = [eachprobability / area for eachprobability in probability]\n return normedprobability, map_to_bins\n\ndef correlationpair(sequence):\n pairs = [(sequence[i], sequence[i+1]) for i in range(len(sequence)-1)]\n x = [sequence[i] for i in range(len(sequence)-1)]\n y = [sequence[i+1] for i in range(len(sequence)-1)]\n return x,y\n\n```\n\n Uptimes saved to: \n O:\\User\\Viva\\analysis\\blinker_analysis\\taken-2018-05-25\\GoodBlinker_5-25-2018.txt, 100.0 Hz uptimes.csv\n Downtimes saved to: \n O:\\User\\Viva\\analysis\\blinker_analysis\\taken-2018-05-25\\GoodBlinker_5-25-2018.txt, 100.0 Hz downtimes.csv\n\n\n\n```python\nontimesprev, ontimescurrent = correlationpair(ontimes)\nofftimesprev, offtimescurrent = correlationpair(offtimes)\nfigure(figsize(3,3))\nplt.scatter(ontimesprev, ontimescurrent, alpha=.5, label=\"bright\", s=20)\nplt.scatter(offtimesprev, offtimescurrent, alpha=.5, label=\"dim\", s=20)\npylab.axis('equal')\nylim(ymin=0, ymax = 2)\nxlim(xmin=0, xmax = 2)\nax = plt.gca()\n#ax.set_xscale('log')\n#ax.set_yscale('log')\nax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\nxlabel('Previous state duration (s)')\nylabel('Current state duration (s)');\n```\n\n\n```python\n# ** Choose a nice number of bins to see how the data look.\n# It's better to have as many bins as possible before the first empty bin.\n\nnumonbins = 60\nnumoffbins = 60\n\n#plt.hist(ontimes, bins=numonbins, histtype='step', linewidth=1)\nsns.distplot(ontimes, bins=numonbins, kde=False, rug=True, \n hist_kws={\"histtype\": \"step\", \"linewidth\": 1, \"alpha\": 1, \"color\": \"k\"});\nplt.xlabel('Bright state duration (s)')\nplt.ylabel('Occurrences')\nax = plt.gca()\nax.set_yscale('symlog', linthreshy=1)\nax.set_xscale('log')\nsns.despine()\nplt.show()\n#plt.hist(offtimes, bins=numoffbins, histtype='step', linewidth=1)\nsns.distplot(offtimes, bins=numoffbins, kde=False, rug=True, \n hist_kws={\"histtype\": \"step\", \"linewidth\": 1, \"alpha\": 1, \"color\": \"k\"});\nplt.xlabel('Dim state duration (s)')\nplt.ylabel('Occurrences')\nax = plt.gca()\nax.set_yscale('symlog', linthreshy=1)\nax.set_xscale('log')\nsns.despine()\nplt.show()\n```\n\n\n```python\n# logarithmic bins.\n\n## ** choose number of bins\nnumonbins_log = 10\nnumoffbins_log = 10\n\nsmall = 1e-4\nonbins=np.logspace(np.log10(min(ontimes)-small),np.log10(max(ontimes)+small), numonbins_log)\noffbins = np.logspace(np.log10(min(offtimes)-small),np.log10(max(offtimes)+small), numoffbins_log)\n\nonfitx = np.logspace(np.log10(min(ontimes)),np.log10(max(ontimes)), numonbins_log*10)\nofffitx = np.logspace(np.log10(min(offtimes)),np.log10(max(offtimes)), numoffbins_log*10)\n\n#plt.hist(ontimes, bins=numonbins, histtype='step', linewidth=1)\nsns.distplot(ontimes, bins=onbins, kde=False, rug=True, \n hist_kws={\"histtype\": \"step\", \"linewidth\": 1, \"alpha\": 1, \"color\": \"k\"});\nplt.xlabel('Bright state duration (s)')\nplt.ylabel('Occurrences')\nax = plt.gca()\nxlim(xmin=1e-2)\n#ax.set_yscale('symlog', linthreshy=1)\nax.set_xscale('log')\nsns.despine()\ntitle('Log bins, unnormalized' )\n\nonprobs, _ = nonlinearhistc(ontimes, onbins) \noffprobs, _ = nonlinearhistc(offtimes, offbins) \n \nplt.figure()\nplot(onbins,onprobs, '.-', label=\"Bright state\");\nplot(offbins,offprobs, '.-', label=\"Dim state\");\n\ngca().set_yscale('log')\ngca().set_xscale('log')\ntitle('normalized log bins')\nplt.xlabel('State duration (s)')\nplt.ylabel('Probability');\nlegend();\n\nfigure()\nsortedontimes,CDFontimes=CDF(ontimes)\nsortedofftimes,CDFofftimes=CDF(offtimes)\nloglog(sortedontimes,CDFontimes, '.-', label='Bright state');\nloglog(sortedofftimes,CDFofftimes, '.-', label='Dim state');\nxlabel('State duration (s)');\nylabel('Cumulative distribution function');\nlegend();\n```\n\n\n```python\nfrom scipy.optimize import curve_fit\nimport scipy\nimport sympy\nprint(scipy.__version__)\nprint(sympy.__version__)\n# need at least version 14.0 of scipy.\n\ndef expfit(t, A, tau):\n return (A * np.exp(t/(-tau)))\n\n# integral from t to infinity of expfit\ndef CDFexp(t, A, tau):\n return A*tau*np.exp(-t/tau)\n\ndef powlaw(t, C, m):\n return C * t**(-m)\n\n# integral from t to infinity of powlaw\ndef CDFpowlaw(t,C,m):\n return (C/(m-1)) * t**(-(m-1)) # https://arxiv.org/pdf/cond-mat/0412004.pdf\n\n# truncated power law from https://www.nature.com/articles/srep08898\ndef truncpow(t,C,m,tau):\n return(C * np.exp(t/(-tau)) * t**(-m))\n\n# integral from t to infinity of truncpow, assuming m<1\ndef CDFtruncpow(t,C,m,tau):\n \"\"\"I (Viva) calculated this in Mathematica\"\"\"\n return (C*(t**(-m))*(t * sympy.N(sympy.expint(m, t/tau))\n + (t**m (1/tau)**m - (t/tau)**m) * tau * scipy.special.gamma(1-m)))\n\n# Trying to find good guess\n#onparamexp[1]=-.8\n#onfitexp = 30 * np.exp(centeredonbins/(onparamexp[1]))\n```\n\n 0.17.1\n 1.1.1\n\n\n\n```python\nshowexpfit = False\nshowpowfit = True\n\n### ==== FITS ====\n\n# on time exponential fit, not truncated\nonparamexp, onpcovexp = curve_fit(expfit, onbins, onprobs,p0 = (30, 2))\nonfitexp = expfit(onfitx,onparamexp[0],onparamexp[1])\n\n# on time power law fit, not truncated\nonparampow, onpcovpow = curve_fit(powlaw, onbins, onprobs,p0 = (2, 1))\nonfitpow = powlaw(onfitx,onparampow[0],onparampow[1])\n\n# on time power law fit to CDF\nonparampow_fromCDF, onpcovpow_fromCDF = curve_fit(CDFpowlaw, sortedontimes,CDFontimes,p0 = onparampow)\nonfitpow_fromCDF = powlaw(onfitx,onparampow_fromCDF[0],onparampow_fromCDF[1])\nonfitpowCDF = CDFpowlaw(onfitx,onparampow_fromCDF[0],onparampow_fromCDF[1])\n\n# off time exponential fit, not truncated\noffparamexp, offpcovexp = curve_fit(expfit, offbins, offprobs,p0 = (30, 2))\nofffitexp = expfit(offfitx,offparamexp[0],offparamexp[1])\n\n# off time power law fit, not truncated\noffparampow, offpcovpow = curve_fit(powlaw, offbins, offprobs,p0 = (2, 1))\nofffitpow = powlaw(offfitx,offparampow[0],offparampow[1])\n\n# off time power law fit to CDF\noffparampow_fromCDF, offpcovpow_fromCDF = curve_fit(CDFpowlaw, sortedofftimes,CDFofftimes,p0 = offparampow)\nofffitpow_fromCDF = powlaw(offfitx,offparampow_fromCDF[0],offparampow_fromCDF[1])\nofffitpowCDF = CDFpowlaw(offfitx,offparampow_fromCDF[0],offparampow_fromCDF[1])\n\n### === display fits ===\n\nfig,ax1 = plt.subplots()\nax1.plot(offbins,offprobs,'.-', label='data')\nplt.xlabel('Dim state duration (s)')\nplt.ylabel('Probability')\n#ax1.set_yscale('symlog', linthreshy=1)\nif showexpfit:\n ax1.plot(offfitx,offfitexp, label='exponential fit')\nif showpowfit:\n ax1.plot(offfitx, offfitpow, label= 'power law fit')\n ax1.plot(offfitx, offfitpow_fromCDF, label= 'power law fit (from CDF)')\nplt.title(filename)\nplt.legend()\nplt.show()\n\nfig,ax1 = plt.subplots()\nax1.plot(offbins,offprobs,'.-', label='data')\nplt.xlabel('Dim state duration (s)')\nplt.ylabel('Probability')\n#ax1.set_yscale('symlog', linthreshy=1)\nif showexpfit:\n ax1.plot(offfitx,offfitexp, label='exponential fit')\nif showpowfit:\n ax1.plot(offfitx, offfitpow, label= 'power law fit')\n ax1.plot(offfitx, offfitpow_fromCDF, label= 'power law fit (from CDF)')\nplt.title(filename)\nplt.legend()\nax1.set_yscale('log', linthreshy=1)\nplt.show()\n\nfig,ax1 = plt.subplots()\nax1.plot(offbins,offprobs,'.-', label='data')\nplt.xlabel('Dim state duration (s)')\nplt.ylabel('Probability')\n#ax1.set_yscale('log')\nif showexpfit:\n ax1.plot(offfitx,offfitexp, label='exponential fit')\nif showpowfit:\n ax1.plot(offfitx, offfitpow, label= 'power law fit')\n ax1.plot(offfitx, offfitpow_fromCDF, label= 'power law fit (from CDF)')\nplt.title(filename)\nplt.legend()\nax1.set_yscale('log')\nax1.set_xscale('log')\nplt.show()\n\nfigure() # display CDF\nsortedontimes,CDFontimes=CDF(ontimes)\nsortedofftimes,CDFofftimes=CDF(offtimes)\nloglog(sortedontimes,CDFontimes, '.-', label='Bright state');\nif showpowfit:\n plot(onfitx,onfitpowCDF, label='Bright state power law fit')\nloglog(sortedofftimes,CDFofftimes, '.-', label='Dim state');\nif showpowfit:\n plot(offfitx, offfitpowCDF, label='Dim state power law fit')\nxlabel('State duration (s)');\nylabel('1-CDF')\ntitle(filename + '\\nCumulative distribution function');\nlegend();\n\nfigure() # display CDF\nloglog(sortedontimes,[1-c for c in CDFontimes], '.-', label='Bright state');\nif showpowfit:\n plot(onfitx,[1-p for p in onfitpowCDF], label='Bright state power law fit')\nloglog(sortedofftimes,[1-c for c in CDFofftimes], '.-', label='Dim state');\nif showpowfit:\n plot(offfitx, [1-p for p in offfitpowCDF], label='Dim state power law fit')\nxlabel('State duration (s)');\nylabel('CDF')\ntitle(filename + '\\nCumulative distribution function');\nlegend();\n\n\n# === BRIGHT STATE fit params ===\nfigure(figsize=(1,6))\nplt.imshow(abs(onpcovexp), cmap=\"gray\", interpolation=\"nearest\", vmin=0)\nplt.colorbar()\nplt.title('Covariance matrix, exp fit, bright state, absolute values')\nplt.show()\nprint(\"It's ok to use the uncertainties below as long as there aren't strong on-diagonal values.\")\n\nfigure(figsize=(1,6))\nplt.imshow(abs(onpcovexp), cmap=\"gray\", interpolation=\"nearest\", vmin=0)\nplt.colorbar()\nplt.title('Covariance matrix, pow fit, bright state, absolute values')\nplt.show()\nprint(\"It's ok to use the uncertainties below as long as there aren't strong on-diagonal values.\")\n\nprint 'Exponential fit:'\nprint 'on Coefficient A_bright = ' + str(onparamexp[0]) + ' ± ' + str(np.sqrt(onpcovexp[0,0]))\nprint 'time constant tau_bright = ' + str(onparamexp[1]) + ' ± ' + str(np.sqrt(onpcovexp[1,1])) + ' sec'\n\nprint 'Power law:'\nprint 'on Coefficient C_bright = ' + str(onparampow[0]) + ' ± ' + str(np.sqrt(onpcovpow[0,0]))\nprint 'logarithmic slope m_bright = ' + str(onparampow[1]) + ' ± ' + str(np.sqrt(onpcovpow[1,1]))\n\nprint 'Power law (from CDF):'\nprint 'on Coefficient C_bright = ' + str(onparampow_fromCDF[0]) + ' ± ' + str(np.sqrt(onpcovpow_fromCDF[0,0]))\nprint 'logarithmic slope m_bright = ' + str(onparampow_fromCDF[1]) + ' ± ' + str(np.sqrt(onpcovpow_fromCDF[1,1]))\n\n# === DIM STATE fit params ===\nfigure(figsize=(1,6))\nplt.imshow(abs(offpcovexp), cmap=\"gray\", interpolation=\"nearest\", vmin=0)\nplt.colorbar()\nplt.title('Covariance matrix, exp fit, dim state, absolute values')\nplt.show()\nprint(\"It's ok to use the uncertainties below as long as there aren't strong off-diagonal values.\")\n\nfigure(figsize=(1,6))\nplt.imshow(abs(offpcovexp), cmap=\"gray\", interpolation=\"nearest\", vmin=0)\nplt.colorbar()\nplt.title('Covariance matrix, pow fit, dim state, absolute values')\nplt.show()\nprint(\"It's ok to use the uncertainties below as long as there aren't strong off-diagonal values.\")\n\nprint 'Exponential fit:'\nprint 'off Coefficient A_dim = ' + str(offparamexp[0]) + ' ± ' + str(np.sqrt(offpcovexp[0,0]))\nprint 'time constant tau_dim = ' + str(offparamexp[1]) + ' ± ' + str(np.sqrt(offpcovexp[1,1])) + ' sec'\n\nprint 'Power law:'\nprint 'off Coefficient C_dim = ' + str(offparampow[0]) + ' ± ' + str(np.sqrt(offpcovpow[0,0]))\nprint 'logarithmic slope m_dim = ' + str(offparampow[1]) + ' ± ' + str(np.sqrt(offpcovpow[1,1]))\n\nprint 'Power law (from CDF):'\nprint 'off Coefficient C_dim = ' + str(offparampow_fromCDF[0]) + ' ± ' + str(np.sqrt(offpcovpow_fromCDF[0,0]))\nprint 'logarithmic slope m_dim = ' + str(offparampow_fromCDF[1]) + ' ± ' + str(np.sqrt(offpcovpow_fromCDF[1,1]))\n\n```\n\n\n```python\n# Save figures\n\n# mpl.rcParams['figure.dpi'] = 200\n\nfont = {'size' : 22}\nplt.rc('font', **font)\n\n# display off blinks\nfig,ax1 = plt.subplots()\nax1.loglog(offbins,offprobs,'o-', label=\"Dim state\")\nplt.xlabel('Dim state duration (s)')\nplt.ylabel('Probability')\nax1.loglog(offfitx,offfitpow_fromCDF, label=\"dim state power law\")\n\n#ploteveryfig(fig,ax1,today + ',' + filename+',offblinks' + infostr,offfitx,offfitpow_fromCDF, save=True)\n\n# On blinks\n#fig,ax1 = plt.subplots()\nax1.loglog(onbins,onprobs,'o-', label=\"Bright state\")\nplt.xlabel('State duration (s)')\nplt.ylabel('Probability')\nplt.title(filename)\nsns.despine()\nax1.loglog(onfitx,onfitpow_fromCDF, label=\"bright state power law\")\nlegend()\n#ploteveryfig(fig,ax1,today + ',' + filename+',onblinks' + infostr,onfitx,onfitpow_fromCDF, save=True)\n\n\nprint os.getcwd()\nsavename = today + ',' + filename + ',powfitfromCDF,loglog'\nprint savename\nsavefig(savename + '.pdf', bbox_inches='tight', dpi=200)\nsavefig(savename + '.png', bbox_inches='tight', dpi=200)\nplt.show()\n\nprint 'Bright state: Power law (from CDF):'\nprint 'Coefficient C_bright = ' + str(onparampow_fromCDF[0]) + ' ± ' + str(np.sqrt(onpcovpow_fromCDF[0,0]))\nprint 'logarithmic slope m_bright = ' + str(onparampow_fromCDF[1]) + ' ± ' + str(np.sqrt(onpcovpow_fromCDF[1,1]))\n\nprint 'Dim state: Power law (from CDF):'\nprint 'Coefficient C_dim = ' + str(offparampow_fromCDF[0]) + ' ± ' + str(np.sqrt(offpcovpow_fromCDF[0,0]))\nprint 'logarithmic slope m_dim = ' + str(offparampow_fromCDF[1]) + ' ± ' + str(np.sqrt(offpcovpow_fromCDF[1,1]))\n```\n\n\n```python\nfrom collections import OrderedDict\nfrom IPython.display import display\n\nonsavename = today + ',' + filename + ',powfitfromCDF,on.csv'\noffsavename = today + ',' + filename + ',powfitfromCDF,off.csv'\n\nonparamsdf = pd.DataFrame(OrderedDict([('file', filename),\n ('C',onparampow_fromCDF[0]), \n ('C_unc', np.sqrt(onpcovpow_fromCDF[0,0])), \n ('m', onparampow_fromCDF[1]), \n ('m_unc',np.sqrt(onpcovpow_fromCDF[1,1]))]), index = [0])\ndisplay(onparamsdf)\nonparamsdf.to_csv(onsavename)\nprint onsavename\n\noffparamsdf = pd.DataFrame(OrderedDict([('file', filename),\n ('C',offparampow_fromCDF[0]), \n ('C_unc', np.sqrt(offpcovpow_fromCDF[0,0])), \n ('m', offparampow_fromCDF[1]), \n ('m_unc',np.sqrt(offpcovpow_fromCDF[1,1]))]), index = [0])\ndisplay(offparamsdf)\noffparamsdf.to_csv(offsavename)\nprint offsavename\n\nos.getcwd()\n```\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
fileCC_uncmm_unc
0GoodBlinker_5-25-2018.txt, 100.0 Hz0.0981060.0023971.2818840.014401
\n
\n\n\n 2018-07-02,GoodBlinker_5-25-2018.txt, 100.0 Hz,powfitfromCDF,on.csv\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
fileCC_uncmm_unc
0GoodBlinker_5-25-2018.txt, 100.0 Hz0.0877270.0020081.3234890.018702
\n
\n\n\n 2018-07-02,GoodBlinker_5-25-2018.txt, 100.0 Hz,powfitfromCDF,off.csv\n\n\n\n\n\n 'O:\\\\User\\\\Viva\\\\analysis\\\\blinker_analysis\\\\taken-2018-05-25'\n\n\n\n\n```python\nprint 'Exp [A, tau]'\nprint offparamexp\nprint onparamexp\n\nprint 'Pow [C, m]'\nprint offparampow\nprint onparampow\n\nprint 'Pow,CDF [C, m]'\nprint offparampow_fromCDF\nprint onparampow_fromCDF\n```\n\n Exp [A, tau]\n [ 1.28149292e+02 9.39423437e-03]\n [ 4.32624449e+01 1.31303199e-02]\n Pow [C, m]\n [ 4.69026177e-04 2.65442277e+00]\n [ 1.29556031e-03 2.27207987e+00]\n Pow,CDF [C, m]\n [ 0.0877272 1.32348887]\n [ 0.09810592 1.28188407]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "95ee1a802167218d1d8ad038e1a4fc478adbf5b7", "size": 799367, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "blinker_analysis_with_fit.ipynb", "max_stars_repo_name": "vivarose/blinker_analysis", "max_stars_repo_head_hexsha": "cd77c337094a27d60253afb0d7830874ecb6f439", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "blinker_analysis_with_fit.ipynb", "max_issues_repo_name": "vivarose/blinker_analysis", "max_issues_repo_head_hexsha": "cd77c337094a27d60253afb0d7830874ecb6f439", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blinker_analysis_with_fit.ipynb", "max_forks_repo_name": "vivarose/blinker_analysis", "max_forks_repo_head_hexsha": "cd77c337094a27d60253afb0d7830874ecb6f439", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 595.209977662, "max_line_length": 109448, "alphanum_fraction": 0.932851869, "converted": true, "num_tokens": 7994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.3482894198992061}} {"text": "# Muscle modeling\n\n> Marcos Duarte \n> Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/)) \n> Federal University of ABC, Brazil\n\nThere are two major classes of muscle models that have been used in biomechanics and motor control: the Hill-type and Huxley-type models. They differ mainly on how the contractile element is modeled. In Hill-type models, the modeling of the contractile element is phenomenological; arbitrary mathematical functions are used to reproduce experimental observations relating muscle characteristics (such as excitation/activation, muscle length and velocity) with the muscle force. In Huxley-type models, the modeling of the contractile element is mechanistic; the mathematical functions used represent the hypothesized mechanisms for the cross-bridge dynamics (Tsianos and Loeb, 2013). Huxley-type models tend to produce more realistic results than Hill-type models for certain conditions but they have a higher computational demand. For this reason, Hill-type models are more often employed in musculoskeletal modeling and simulation. \n\nHill-type muscle models are presented in several texts (e.g., Erdermir et al. 2007; He et al., 1991; McMahon, 1984; Nigg and Herzog, 2007; Robertson et al., 2013, Thelen, 2003; Tsianos and Loeb, 2013, Winters, 1990; Zajac, 1989; Zatsiorsky and Prilutsky, 2012) and implemented in many software for modeling and simulation of the musculoskeletal dynamics of human movement (e.g., the free and open source software [OpenSim](https://simtk.org/home/opensim)). \n\nNext, let's see a brief overview of a Hill-type muscle model and a basic implementation in Python. \n\n## Hill-type muscle model\n\nHill-type models are developed to reproduce the dependence of force with the length and velocity of the muscle-tendon unit and parameters are lumped and made dimensionless in order to represent different muscles with few changes in these parameters. A Hill-type model is complemented with the modeling of the activation dynamics (i.e., the temporal pattern of muscle activation and deactivation as a function of the neural excitation) to produce more realistic results. As a result, the force generated will be a function of three factors: the length and velocity of the muscle-tendon unit and its activation level $a$. \n\nA Hill-type muscle model has three components (see figure below): two for the muscle, an active contractile element (CE) and a passive elastic element (PE) in parallel with the CE, and one component for the tendon, an elastic element (SE) in series with the muscle. In some variations, a damping component is added parallel to the CE as a fourth element. A [pennation angle](http://en.wikipedia.org/wiki/Muscle_architecture) (angle of the pennate fibers with respect to the force-generating axis) is also included in the model. In a simpler approach, the muscle and tendon are assumed massless.\n\n
Figure. A Hill-type muscle model with three components: two for the muscle, an active contractile element, $\\mathsf{CE}$, and a passive elastic element in parallel, $\\mathsf{PE}$, with the $\\mathsf{CE}$, and one component for the tendon, an elastic element in series, $\\mathsf{SE}$, with the muscle. $\\mathsf{L_{MT}}$: muscle–tendon length, $\\mathsf{L_T}$: tendon length, $\\mathsf{L_M}$: muscle fiber length, $\\mathsf{F_T}$: tendon force, $\\mathsf{F_M}$: muscle force, and $α$: pennation angle.
\n\nLet's now revise the models of a Hill-type muscle with three components and activation dynamics by two references: \n 1. [Thelen (2003)](http://simtk-confluence.stanford.edu:8080/display/OpenSim/Thelen+2003+Muscle+Model) with some of the adjustments described in Millard et al. (2013). Hereafter, Thelen2003Muscle or T03.\n 2. [McLean, Su, van den Bogert (2003)](http://www.ncbi.nlm.nih.gov/pubmed/14986412). Hereafter, McLean2003Muscle or M03.\n \nFirst, let's import the necessary Python libraries and customize the environment:\n\n\n```python\nimport numpy as np\nfrom scipy.integrate import ode, odeint\n%matplotlib inline\nimport matplotlib.pyplot as plt \nimport matplotlib\nmatplotlib.rcParams['lines.linewidth'] = 3\nmatplotlib.rcParams['font.size'] = 13\nmatplotlib.rcParams['lines.markersize'] = 5\nmatplotlib.rc('axes', grid=True, labelsize=14, titlesize=16, ymargin=0.05)\nmatplotlib.rc('legend', numpoints=1, fontsize=11)\n```\n\n### Force-length relationship\n\nIn a Hill-type model, the force a muscle can generate depends on its length due to two factors: \n\n1. The active force of the contractile element (CE), which in turn depends on the spatial superposition of the actin and myosin molecules to form cross-bridges at the sarcomere. A maximum number of cross-bridges will be formed at an optimal fiber length, generating a maximum force. When a fiber is too stretched or too shortened, fewer cross-bridges will be formed, decreasing the force generated. \n2. The passive and parallel elastic element (PE), which behaves as a nonlinear spring where no force is generated below a certain length (the slack length) and force increases with the muscle elongation.\n\n#### Force-length relationship of the contractile element\n\nThelen2003Muscle represented the normalized force-length relationship of the contractile element by a Gaussian function:\n\n\\begin{equation}\n\\bar{f}_{l,CE} = exp\\left[-(\\bar{L}_M-1)^2/\\gamma\\right]\n\\label{}\n\\end{equation}\n\nwhere $\\gamma$ is a shape factor and $\\bar{L}_M$ is the muscle fiber length normalized by the optimal muscle fiber length at which maximal force can be produced, $L_{Mopt}$:\n\n\\begin{equation}\n\\bar{L}_M=\\dfrac{L_M}{L_{Mopt}}\n\\label{}\n\\end{equation}\n\nThelen2003Muscle adopted $\\gamma=0.45$. The actual force produced is obtained multiplying $\\bar{f}_{l,CE}$ by the maximum isometric muscle force, $F_{M0}$. Thelen2003Muscle assumed that the maximum isometric muscle forces for old adults were 30% lower than those used for young adults.\n\nMcLean2003Muscle represented the force-length relationship of the contractile element (not normalized) as a function of muscle length (not normalized) by a quadratic function:\n\n\\begin{equation}\nf_{l,CE} = max \\left\\{ \n \\begin{array}{l l}\n F_{Mmin} \\\\\n F_{M0}\\left[1 - \\left(\\dfrac{L_M-L_{Mopt}}{WL_{Mopt}}\\right)^2\\right]\n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nwhere $W$ is a dimensionless parameter describing the width of the force-length relationship. A minimum force level $F_{Mmin}$ is employed for numerical stability. \nMcLean2003Muscle adopted $W=1$ and $F_{Mmin}=10 N$. \n\nThe corresponding Python functions are:\n\n\n```python\ndef flce_T03(lm=1, gammal=0.45):\n \"\"\"Thelen (2003) force of the contractile element as function of muscle length.\n \n Parameters\n ----------\n lm : float, optional (default=1)\n normalized muscle fiber length\n gammal : float, optional (default=0.45)\n shape factor\n\n Returns\n -------\n fl : float\n normalized force of the muscle contractile element\n \"\"\"\n \n fl = np.exp(-(lm-1)**2/gammal)\n \n return fl\n```\n\n\n```python\ndef flce_M03(lm=1, lmopt=1, fm0=1, fmmin=0.001, wl=1):\n \"\"\"McLean (2003) force of the contractile element as function of muscle length.\n \n Parameters\n ----------\n lm : float, optional (default=1)\n muscle (fiber) length\n lmopt : float, optional (default=1)\n optimal muscle fiber length\n fm0 : float, optional (default=1)\n maximum isometric muscle force\n fmmin : float, optional (default=0.001)\n minimum muscle force\n wl : float, optional (default=1)\n shape factor of the contractile element force-length curve\n\n Returns\n -------\n fl : float\n force of the muscle contractile element\n \"\"\"\n \n fl = np.max([fmmin, fm0*(1 - ((lm - lmopt)/(wl*lmopt))**2)])\n \n return fl\n```\n\nAnd plots of these functions:\n\n\n```python\nlm = np.arange(0, 2.02, .02)\nfce_T03 = np.zeros(lm.size)\nfce_M03 = np.zeros(lm.size)\nfor i in range(len(lm)):\n fce_T03[i] = flce_T03(lm[i])\n fce_M03[i] = flce_M03(lm[i])\n```\n\n\n```python\nplt.figure(figsize=(7, 4))\nplt.plot(lm, fce_T03, 'b', label='T03')\nplt.plot(lm, fce_M03, 'g', label='M03')\nplt.xlabel('Normalized length')\nplt.ylabel('Normalized force')\nplt.legend(loc='best')\nplt.suptitle('Force-length relationship of the contractile element', y=1, fontsize=16)\nplt.show()\n```\n\nSimilar results when the same parameters are used.\n\n#### Force-length relationship of the parallel element\n\nThelen2003Muscle represents the normalized force of the parallel (passive) element of the muscle as a function of muscle length (normalized by the optimal muscle fiber length) by an exponential function:\n\n\\begin{equation}\n\\bar{F}_{PE}(\\bar{L}_M) = \\dfrac{exp\\left[k_{PE}(\\bar{L}_M-1)/\\epsilon_{M0}\\right]-1}{exp(k_{PE})-1}\n\\label{}\n\\end{equation}\n\nwhere $k_{PE}$ is an exponential shape factor and $\\epsilon_{M0}$ is the passive muscle strain due to maximum isometric force:\n\n\\begin{equation}\n\\epsilon_{M0}=\\dfrac{L_M(F_{M0})-L_{Mslack}}{L_{Mslack}}\n\\label{}\n\\end{equation}\n\nwhere $L_{Mslack}$ is the muscle slack length. Thelen2003Muscle adopted $L_{Mslack} = L_{Mopt}$. \nThelen2003Muscle adopted $k_{PE}=5$ and $\\epsilon_{M0}=0.6$ for young adults ($\\epsilon_{M0}=0.5$ for old adults). The actual force produced is obtained multiplying $\\bar{F}_{PE}$ by the maximum isometric muscle force, $F_{M0}$.\n\nMcLean2003Muscle represents the force of the parallel (passive) element of the muscle (not normalized) as a function of muscle length (not normalized) by a quadratic function:\n\n\\begin{equation} \nF_{PE}(L_M) = \\left\\{ \n \\begin{array}{l l}\n 0 \\quad & \\text{if} \\quad L_M \\leq L_{Mslack} \\\\\n k_{PE}(L_M - L_{Mslack})^2 \\quad & \\text{if} \\quad L_M > L_{Mslack}\n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nwhere $k_{PE}$ is a stiffness parameter of the parallel element such that the passive muscle force is equal to the normalized maximum isometric force of the muscle when the CE is stretched to its maximal length for active force production:\n\n\\begin{equation}\nk_{PE} = \\dfrac{F_{M0}}{(WL_{Mopt})^2}\n\\label{}\n\\end{equation}\n\nMcLean2003Muscle adopted $L_{Mslack} = L_{Mopt}$.\n\nThe corresponding Python functions are:\n\n\n```python\ndef fpelm_T03(lm=1, kpe=5, epsm0=0.6):\n \"\"\"Thelen (2003) force of the muscle parallel element as function of muscle length.\n \n Parameters\n ----------\n lm : float, optional (default=1)\n normalized muscle fiber length\n kpe : float, optional (default=5)\n exponential shape factor\n epsm0 : float, optional (default=0.6)\n passive muscle strain due to maximum isometric force\n\n Returns\n -------\n fpe : float\n normalized force of the muscle parallel (passive) element\n \"\"\"\n \n if lm < 1:\n fpe = 0\n else:\n fpe = (np.exp(kpe*(lm-1)/epsm0)-1)/(np.exp(kpe)-1)\n \n return fpe\n```\n\n\n```python\ndef fpelm_M03(lm=1, lmopt=1, fm0=1, lmslack=1, wp=1):\n \"\"\"McLean (2003) force of the muscle parallel element as function of muscle length.\n \n Parameters\n ----------\n lm : float, optional (default=1)\n muscle fiber length\n lmopt : float, optional (default=1)\n optimal muscle (fiber) length\n fm0 : float, optional (default=1)\n maximum isometric muscle force\n lmslack : float, optional (default=1)\n muscle slack length\n wp : float, optional (default=1)\n shape factor of the parallel element force-length curve\n\n Returns\n -------\n fpe : float\n force of the muscle parallel (passive) element\n \"\"\"\n \n kpe = fm0/(wp*lmopt)**2\n if lm <= lmslack:\n fpe = 0\n else:\n fpe = kpe*(lm-lmslack)**2\n \n return fpe\n```\n\nAnd plots of these functions:\n\n\n```python\nlm = np.arange(0, 2.02, .02)\nfpe_T03 = np.zeros(lm.size)\nfpe_M03 = np.zeros(lm.size)\nfor i in range(len(lm)):\n fpe_T03[i] = fpelm_T03(lm[i])\n fpe_M03[i] = fpelm_M03(lm[i])\n```\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True, figsize=(10, 4))\nax1.plot(lm[:86], fce_T03[:86], 'b', label='Active')\nax1.plot(lm[:86], fpe_T03[:86], 'r', label='Passive')\nax1.plot(lm[:86], fce_T03[:86] + fpe_T03[:86], 'g', label='Total')\nax1.text(0.1, 2.6, 'T03')\nax1.set_xlim([0, 1.7])\nax1.set_xlabel('Normalized length')\nax1.set_ylabel('Normalized force')\n#ax1.legend(loc='best')\nax2.plot(lm[:86], fce_M03[:86], 'b', label='Active')\nax2.plot(lm[:86], fpe_M03[:86], 'r', label='Passive')\nax2.plot(lm[:86], fce_M03[:86] + fpe_M03[:86], 'g', label='Total')\nax2.text(0.1, 2.6, 'M03')\nax2.set_xlim([0, 1.7])\nax2.set_xlabel('Normalized length')\nax2.legend(loc='best')\nplt.suptitle('Muscle force-length relationship', y=1, fontsize=16)\nplt.tight_layout()\nplt.show()\n```\n\nThe results are different at the maximum stretching because Thelen2003Muscle and McLean2003Muscle model differently the passive component. \nThese results were simulated for a maximum muscle activation (an activation level, $a$, of 1, where 0 is no activation). The effect of different activation levels on the total muscle force (but only the active force is affected) is shown in the next figure:\n\n\n```python\nlm = np.arange(0, 2.02, .02)\nfce_T03_als = np.zeros((lm.size, 5))\nals = [0, 0.25, 0.50, 0.75, 1.0]\nfor j, al in enumerate(als):\n for i in range(len(lm)):\n fce_T03_als[i, j] = flce_T03(lm[i])*al\n```\n\n\n```python\nfig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True, figsize=(6, 5))\nfor j, al in enumerate(als):\n ax.plot(lm[:86], fce_T03_als[:86, j] + fpe_T03[:86], label='%.2f'%al)\nax.text(0.1, 2.6, 'T03')\nax.set_xlim([0, 1.7])\nax.set_xlabel('Normalized length')\nax.set_ylabel('Normalized force')\nax.legend(loc='best', title='Activation level')\nax.set_title('Muscle force-length relationship', y=1, fontsize=16)\nplt.tight_layout()\nplt.show()\n```\n\n#### Force-length relationship of the series element (tendon)\n\nThelen2003Muscle represented the tendon force of the series element as a function of the normalized tendon length (in fact, tendon strain) by an exponential function during an initial nonlinear toe region and by a linear function thereafter:\n\n\\begin{equation}\n\\bar{F}_{SE}(\\bar{L}_T) = \\left\\{ \n \\begin{array}{l l}\n \\dfrac{\\bar{F}_{Ttoe}}{exp(k_{Ttoe})-1}\\left[exp(k_{Ttoe}\\epsilon_T/\\epsilon_{Ttoe})-1\\right] \\quad & \\text{if} \\quad \\epsilon_T \\leq \\epsilon_{Ttoe} \\\\\n k_{Tlin}(\\epsilon_T - \\epsilon_{Ttoe}) + \\bar{F}_{Ttoe} \\quad & \\text{if} \\quad \\epsilon_T > \\epsilon_{Ttoe}\n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nwhere $\\epsilon_{T}$ is the tendon strain:\n\n\\begin{equation}\n\\epsilon_{T} = \\dfrac{L_T-L_{Tslack}}{L_{Tslack}}\n\\label{}\n\\end{equation}\n\n$L_{Tslack}$ is the tendon slack length, $\\epsilon_{Ttoe}$ is the tendon strain above which the tendon exhibits linear behavior, $k_{Ttoe}$ is an exponential shape factor, and $k_{Tlin}$ is a linear scale factor. The parameters are chosen such that the tendon elongation at the normalized maximal isometric force of the muscle is 4% of the tendon length ($\\epsilon_{T0}=0.04$). \nThelen2003Muscle adopted $k_{Ttoe}=3$ and the transition from nonlinear to linear behavior occurs for normalized tendon forces greater than $\\bar{F}_{Ttoe}=0.33$. For continuity of slopes at the transition, $\\epsilon_{Ttoe}=0.609\\epsilon_{T0}$ and $k_{Tlin}=1.712/\\epsilon_{T0}$. The actual force produced is obtained multiplying $\\bar{F}_{SE}$ by the maximum isometric muscle force, $F_{M0}$.\n\nMcLean2003Muscle represented the tendon force (not normalized) of the series element as a function of the tendon length (not normalized) by the same quadratic function used for the force of the muscle passive element:\n\n\\begin{equation}\nF_{SE}(L_T) = \\left\\{ \n \\begin{array}{l l}\n 0 \\quad & \\text{if} \\quad L_T \\leq L_{Tslack} \\\\\n k_T(L_T - L_{Tslack})^2 \\quad & \\text{if} \\quad L_T > L_{Tslack}\n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nwhere $k_T$ is the tendon stiffness. The stiffness parameter $k_T$ is chosen such that the tendon elongation is 4% at the maximum isometric force, $k_T=(1/\\epsilon_{T0})^2=625$ for $F_{M0}=1$.\n\nThe corresponding Python functions are:\n\n\n```python\ndef fselt_T03(lt=1, ltslack=1, epst0=0.04, kttoe=3):\n \"\"\"Thelen (2003) force-length relationship of tendon as function of tendon length.\n \n Parameters\n ----------\n lt : float, optional (default=1)\n normalized tendon length\n ltslack : float, optional (default=1)\n normalized tendon slack length\n epst0 : float, optional (default=0.04)\n tendon strain at the maximal isometric muscle force\n kttoe : float, optional (default=3)\n linear scale factor\n\n Returns\n -------\n fse : float\n normalized force of the tendon series element\n \"\"\"\n\n epst = (lt-ltslack)/ltslack\n fttoe = 0.33\n # values from OpenSim Thelen2003Muscle\n epsttoe = .99*epst0*np.e**3/(1.66*np.e**3 - .67)\n ktlin = .67/(epst0 - epsttoe)\n #\n if epst <= 0:\n fse = 0\n elif epst <= epsttoe:\n fse = fttoe/(np.exp(kttoe)-1)*(np.exp(kttoe*epst/epsttoe)-1)\n else:\n fse = ktlin*(epst-epsttoe) + fttoe\n \n return fse\n```\n\n\n```python\ndef fselt_M03(lt, ltslack=1, fm0=1, epst0=0.04):\n \"\"\"McLean (2003) force-length relationship of tendon as function of tendon length.\n \n Parameters\n ----------\n lt : float, optional (default=1)\n tendon length\n ltslack : float, optional (default=1)\n tendon slack length\n fm0 : float, optional (default=1)\n maximum isometric muscle force\n epst0 : float, optional (default=0.04)\n tendon strain at the maximal isometric muscle force\n\n Returns\n -------\n fse : float\n force of the tendon series element\n \"\"\"\n\n kt = fm0/epst0**2\n if lt <= ltslack:\n fse = 0\n else:\n fse = kt*(lt-ltslack)**2\n \n return fse\n```\n\nAnd plots of these functions:\n\n\n```python\nlt = np.arange(1, 1.051, .001)\nfse_T03 = np.zeros(lt.size)\nfse_M03 = np.zeros(lt.size)\nfor i in range(len(lt)):\n fse_T03[i] = fselt_T03(lt[i])\n fse_M03[i] = fselt_M03(lt[i])\n```\n\n\n```python\nplt.figure(figsize=(7, 4))\nplt.plot(lt-1, fse_T03, 'b', label='T03')\nplt.plot(lt-1, fse_M03, 'g', label='M03')\nplt.plot(0.04, 1, 'ro', markersize=8)\nplt.text(0.04, 0.7, '$\\epsilon_{T0}$', fontsize=22)\nplt.xlabel('Tendon strain')\nplt.ylabel('Normalized force')\nplt.legend(loc='upper left')\nplt.suptitle('Tendon force-length relationship (series element)', y=1, fontsize=16)\nplt.show()\n```\n\nSimilar results when the same parameters are used.\n\n### Force-velocity relationship of the contractile element\n\nThe force-velocity relation of the contractile element for shortening (concentric activation) is based on the well known Hill's equation of a hyperbola describing that the product between force $F$ and velocity $V$ of the contractile element is constant (Winters, 1990; Winters, 1995):\n\n\\begin{equation}\n(F+a')(V+b') = (F_{0}+a')b'\n\\label{}\n\\end{equation}\n\nwhere $a'$, $b'$, and $F_{0}$ are constants. \n\nWe can rewrite the equation above with constants more meaningful to our modeling: \n\n\\begin{equation}\n(F_{M}+A_f F_{Mlen})(V_M+A_f V_{Mmax}) = A_f F_{Mlen}V_{Mmax}(1+A_f)\n\\label{}\n\\end{equation}\n\nwhere $F_{M}$ and $V_M$ are the contractile element force and velocity, respectively, and the three constants are: $V_{Mmax}$, the maximum unloaded velocity (when $F_{M}=0$), $F_{Mlen}$, the maximum isometric force (when $V_M=0$), and $A_f$, a shape factor which specifies the concavity of the hyperbola.\n\nBased on the equation above for the shortening phase and in Winters (1990, 1995) for the lengthening phase, Thelen2003Muscle employed the following force-velocity equation:\n\n\\begin{equation}\nV_M = (0.25+0.75a)\\,V_{Mmax}\\dfrac{\\bar{F}_M-a\\bar{f}_{l,CE}}{b}\n\\label{}\n\\end{equation}\n\nwhere\n\n\\begin{equation}\nb = \\left\\{ \n \\begin{array}{l l l}\n a\\bar{f}_{l,CE} + \\bar{F}_M/A_f \\quad & \\text{if} \\quad \\bar{F}_M \\leq a\\bar{f}_{l,CE} & \\text{(shortening)} \\\\\n \\\\\n \\dfrac{(2+2/A_f)(a\\bar{f}_{l,CE}\\bar{f}_{Mlen} - \\bar{F}_M)}{\\bar{f}_{Mlen}-1} \\quad & \\text{if} \\quad \\bar{F}_M > a\\bar{f}_{l,CE} & \\text{(lengthening)} \n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nwhere $a$ is the activation level and $\\bar{f}_{Mlen}$ is a constant for the maximum force generated at the lengthening phase (normalized by the maximum isometric force). \nThelen2003Muscle adopted $A_f=0.25$, $V_{Mmax}=10L_{Mopt}/s$, $\\bar{f}_{Mlen}=1.4$ for young adults ($V_{Mmax}=8L_{Mopt}/s$ and $\\bar{f}_{Mlen}=1.8$ for old adults). Note that the dependences of the force with the activation level and with the muscle length are already incorporated in the expression above. \n\nMcLean2013Muscle employed:\n\n\\begin{equation} \n\\bar{f}_{v,CE} = \\left\\{ \n \\begin{array}{l l l}\n \\dfrac{\\lambda(a)V_{Mmax} + V_M}{\\lambda(a)V_{Mmax} - V_M/A_f} \\quad & \\text{if} \\quad V_M \\leq 0 & \\text{(shortening)} \\\\\n \\\\\n \\dfrac{\\bar{f}_{Mlen}V_M + d_1}{V_M + d_1} \\quad & \\text{if} \\quad 0 < V_M \\leq \\gamma d_1 & \\text{(slow lengthening)} \\\\\n \\\\\n d_3 + d_2V_M \\quad & \\text{if} \\quad V_M > \\gamma d_1 & \\text{(fast lengthening)} \n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nwhere\n\n\\begin{equation}\n\\begin{array}{l l}\n \\lambda(a) = 1-e^{-3.82a} + a\\:e^{-3.82} \\\\\n \\\\\n d_1 = \\dfrac{V_{Mmax}A_f(\\bar{f}_{Mlen}-1)}{S(A_f+1)} \\\\\n \\\\\n d_2 = \\dfrac{S(A_f+1)}{V_{Mmax}A_f(\\gamma+1)^2} \\\\\n \\\\\n d_3 = \\dfrac{(\\bar{f}_{Mlen}-1)\\gamma^2}{(\\gamma+1)^2} + 1\n\\end{array}\n\\label{}\n\\end{equation}\n\nwhere $\\lambda(a)$ is a scaling factor to account for the influence of the activation level $a$ on the force-velocity relationship, $\\bar{f}_{Mlen}$ is the asymptotic (maximum) value of $\\bar{F}_M$, $S$ is a parameter to double the slope of the force-velocity curve at zero velocity, and $\\gamma$ is a dimensionless parameter to ensure the transition between the hyperbolic and linear parts of the lengthening phase. \nMcLean2013Muscle adopted $A_f=0.25$, $V_{Mmax}=10L_{Mopt}/s$, $\\bar{f}_{Mlen}=1.5$, $S=2.0$, and $\\gamma=5.67$.\n\nLet's write these expressions as Python code and visualize them:\n\n\n```python\ndef vmfce_T03(fm, flce=1, lmopt=1, a=1, vmmax=1, fmlen=1.4, af=0.25):\n \"\"\"Thelen (2003) velocity of the force-velocity relationship as function of CE force.\n \n Parameters\n ----------\n fm : float\n normalized muscle force\n flce : float, optional (default=1)\n normalized muscle force due to the force-length relationship\n lmopt : float, optional (default=1)\n optimal muscle fiber length\n a : float, optional (default=1)\n muscle activation level\n vmmax : float, optional (default=1)\n maximum muscle velocity for concentric activation\n fmlen : float, optional (default=1.4)\n normalized maximum force generated at the lengthening phase\n af : float, optional (default=0.25)\n shape factor\n\n Returns\n -------\n vm : float\n velocity of the muscle\n \"\"\"\n \n vmmax = vmmax*lmopt\n if fm <= a*flce: # isometric and concentric activation\n b = a*flce + fm/af\n else: # eccentric activation\n b = (2 + 2/af)*(a*flce*fmlen - fm)/(fmlen - 1) \n vm = (0.25 + 0.75*a)*vmmax*(fm - a*flce)/b\n \n return vm\n```\n\nLet's find an expression for contractile element force as function of muscle velocity given the equation above, i.e. we want to invert the equation. For that, let's use [Sympy](http://www.sympy.org/):\n\n\n```python\ndef fvce_T03_symb():\n # Thelen (2003) velocity of the force-velocity relationship as function of CE force\n \n from sympy import symbols, solve, collect, Eq\n a, flce, fm, af, fmlen, vmmax = symbols('a, flce, fm, af, fmlen, vmmax', positive=True)\n vm = symbols('vm', real=True)\n \n b = a*flce + fm/af\n vm_eq = Eq(vm - (0.25 + 0.75*a)*vmmax*(fm - a*flce)/b)\n sol = solve(vm_eq, fm)\n print('fm <= a*flce:\\n', collect(sol[0], vmmax),'\\n')\n \n b = (2 + 2/af)*(a*flce*fmlen - fm)/(fmlen - 1)\n vm_eq = Eq(vm - (0.25 + 0.75*a)*vmmax*(fm - a*flce)/b)\n sol = solve(vm_eq, fm)\n print('fm > a*flce:\\n', collect(sol[0], (vmmax*af, fmlen, vm)))\n\nfvce_T03_symb()\n```\n\n fm <= a*flce:\n a*af*flce*(4.0*vm + vmmax*(3.0*a + 1))/(-4.0*vm + vmmax*(3.0*a*af + af)) \n \n fm > a*flce:\n a*flce*(af*vmmax*(3.0*a*fmlen - 3.0*a + fmlen - 1) + fmlen*(8.0*af*vm + 8.0*vm))/(af*vmmax*(3.0*a*fmlen - 3.0*a + fmlen - 1) + vm*(8.0*af + 8.0))\n\n\nAnd here is the function we need to compute contractile element force as function of muscle velocity:\n\n\n```python\ndef fvce_T03(vm=0, flce=1, lmopt=1, a=1, vmmax=1, fmlen=1.4, af=0.25):\n \"\"\"Thelen (2003) force of the contractile element as function of muscle velocity.\n \n Parameters\n ----------\n vm : float, optional (default=0)\n muscle velocity\n flce : float, optional (default=1)\n normalized muscle force due to the force-length relationship\n lmopt : float, optional (default=1)\n optimal muscle fiber length\n a : float, optional (default=1)\n muscle activation level\n vmmax : float, optional (default=1)\n maximum muscle velocity for concentric activation\n fmlen : float, optional (default=1.4)\n normalized maximum force generated at the lengthening phase\n af : float, optional (default=0.25)\n shape factor\n\n Returns\n -------\n fvce : float\n normalized force of the muscle contractile element\n \"\"\"\n\n vmmax = vmmax*lmopt\n if vm <= 0: # isometric and concentric activation\n fvce = af*a*flce*(4*vm + vmmax*(3*a + 1))/(-4*vm + vmmax*af*(3*a + 1))\n else: # eccentric activation\n fvce = a*flce*(af*vmmax*(3*a*fmlen - 3*a + fmlen - 1) + 8*vm*fmlen*(af + 1))/\\\n (af*vmmax*(3*a*fmlen - 3*a + fmlen - 1) + 8*vm*(af + 1))\n \n return fvce\n```\n\nHere is the Python function for the McLean (2003) model:\n\n\n```python\ndef fvce_M03(vm=0, lmopt=1, a=1, vmmax=1, fmlen=1.5, af=0.25, s=2, gammav=5.67):\n \"\"\"McLean (2003) contractile element force as function of muscle velocity.\n \n Parameters\n ----------\n vm : float, optional (default=0)\n muscle velocity\n lmopt : float, optional (default=1)\n optimal muscle fiber length\n a : float, optional (default=1)\n muscle activation level\n vmmax : float, optional (default=1)\n maximum muscle velocity for concentric activation\n fmlen : float, optional (default=1.5)\n normalized maximum force generated at the lengthening phase\n af : float, optional (default=0.25)\n shape factor\n s : float, optional (default=2)\n to double the slope of the force-velocity curve at zero velocity\n gammav : float, optional (default=5.67)\n to ensure the smooth transition of the lengthening phase\n\n Returns\n -------\n fvce : float\n normalized force of the muscle contractile element\n \"\"\"\n\n vmmax = vmmax*lmopt\n d1 = vmmax*af*(fmlen - 1)/(s*(af + 1))\n d2 = s*(af + 1)/(vmmax*af*(gammav + 1)**2)\n d3 = (fmlen - 1)*gammav**2/(gammav + 1)**2 + 1\n lbd = 1 - np.exp(-3.82*a) + a*np.exp(-3.82)\n if vm <= 0: # isometric and concentric activation\n fvce = (lbd*vmmax + vm)/(lbd*vmmax - vm/af)\n elif 0 < vm <= gammav*d1: # slow lengthening\n fvce = (fmlen*vm + d1)/(vm + d1)\n elif vm > gammav*d1: # fast lengthening\n fvce = d3 + d2*vm\n \n return fvce\n```\n\nWe can invert this equation to get an expression for muscle velocity as function of the contractile element force:\n\n\n```python\ndef vmfce_M03(fvce=1, lmopt=1, a=1, vmmax=1, fmlen=1.5, af=0.25, s=2, gammav=5.67):\n \"\"\"McLean (2003) contractile element velocity as function of CE force.\n \n Parameters\n ----------\n fvce : float, optional (default=1)\n normalized muscle force\n lmopt : float, optional (default=1)\n optimal muscle fiber length\n a : float, optional (default=1)\n muscle activation level\n vmmax : float, optional (default=1)\n maximum muscle velocity for concentric activation\n fmlen : float, optional (default=1.5)\n normalized maximum force generated at the lengthening phase\n af : float, optional (default=0.25)\n shape factor\n s : float, optional (default=2)\n to double the slope of the force-velocity curve at zero velocity\n gammav : float, optional (default=5.67)\n to ensure the smooth transition of the lengthening phase\n\n Returns\n -------\n fvce : float\n muscle velocity\n \"\"\"\n \n vmmax = vmmax*lmopt\n d1 = vmmax*af*(fmlen - 1)/(s*(af + 1))\n d2 = s*(af + 1)/(vmmax*af*(gammav + 1)**2)\n d3 = (fmlen - 1)*gammav**2/(gammav + 1)**2 + 1\n lbd = 1 - np.exp(-3.82*a) + a*np.exp(-3.82)\n if 0 <= fvce <= 1: # isometric and concentric activation\n vm = (lbd*vmmax*(1 - fvce))/(1 + fvce/af)\n elif 1 < fvce <= gammav*d1*d2 + d3: # slow lengthening\n vm = d1*(fvce - 1)/(fmlen - fvce)\n elif fvce > gammav*d1*d2 + d3: # fast lengthening\n vm = (fvce - d3)/d2\n \n return vm\n```\n\nLet's use these functions to compute muscle force as a function of the muscle velocity considering two levels of activation:\n\n\n```python\nvm1_T03 = np.linspace(-1, 1, 201)\nfce1_T03 = np.zeros(vm1_T03.size)\nvm2_T03 = np.linspace(-.63, .63, 201)\nfce2_T03 = np.zeros(vm2_T03.size)\nfor i in range(len(vm1_T03)):\n fce1_T03[i] = fvce_T03(vm=vm1_T03[i])\n fce2_T03[i] = fvce_T03(vm=vm2_T03[i], a=0.5)\n```\n\n\n```python\nvm1_M03 = np.linspace(-1, 1, 201)\nfce1_M03 = np.zeros(vm1_M03.size)\nvm2_M03 = np.linspace(-.63, .63, 201)\nfce2_M03 = np.zeros(vm2_M03.size)\nfor i in range(len(vm1_M03)):\n fce1_M03[i] = fvce_M03(vm=vm1_M03[i])\n fce2_M03[i] = fvce_M03(vm=vm2_M03[i], a=0.5)\nfce2_M03 = fce2_M03*0.5\n```\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True, figsize=(10, 4))\nax1.plot(vm1_T03, fce1_T03, 'b', label='T03)')\nax1.plot(vm1_M03, fce1_M03, 'g', label='M03)')\nax1.set_ylabel('Normalized force')\nax1.set_xlabel('Normalized velocity')\nax1.text(-.9, 1.5, 'Activation = 1.0')\nax2.plot(vm2_T03, fce2_T03, 'b', label='T03')\nax2.plot(vm2_M03, fce2_M03, 'g', label='M03')\nax2.text(-.9, 1.5, 'Activation = 0.5')\nax2.set_xlabel('Normalized velocity')\nax2.legend(loc='best')\nplt.suptitle('Force-velocity relationship of the contractile element', y=1.05, fontsize=16)\nplt.tight_layout()\nplt.show()\n```\n\nIdentical results for the shortening phase when $a=1$ and similar results for the lengthening phase when the same parameters are used.\n\n#### Muscle power\n\nThe muscle power is the product between force and velocity:\n\n\n```python\nP_T03 = np.abs(fce1_T03*vm1_T03)\n```\n\nLet's visualize the muscle power only for the concentric phase (muscle shortening):\n\n\n```python\nplt.figure(figsize=(7, 4))\nplt.plot(vm1_T03[:101], fce1_T03[:101], 'b', label='Force')\nplt.xlabel('Normalized velocity')\nplt.ylabel('Normalized force', color='b')\n#plt.legend(loc='upper left')\nplt.gca().invert_xaxis()\nplt.gca().twinx()\nplt.plot(vm1_T03[:101], P_T03[:101], 'g', label='Power')\nplt.ylabel('Normalized power', color='g')\n#plt.legend(loc='upper right')\nplt.suptitle('Muscle power', y=1, fontsize=16)\nplt.show()\n```\n\n#### Force-length-velocity relationship\n\nLet's visualize the effects of the length and velocity on the total (active plus passive) muscle force:\n\n\n```python\nlms = np.linspace(0, 1.65, 101)\nvms = np.linspace(-1, .76, 101)\nfce_T03 = np.zeros(lms.size)\nfpe_T03 = np.zeros(lms.size)\nfm_T03 = np.zeros((lms.size, vms.size))\nfor i in range(len(lms)):\n fce_T03[i] = flce_T03(lm=lms[i])\n fpe_T03[i] = fpelm_T03(lm=lms[i]) \n for j in range(len(vms)):\n fm_T03[j, i] = fvce_T03(vm=vms[j], flce=fce_T03[i]) + fpe_T03[i]\n```\n\n\n```python\nlms = np.linspace(0, 1.65, 101)\nvms = np.linspace(-1, .76, 101)\nfce_M03 = np.zeros(lms.size)\nfpe_M03 = np.zeros(lms.size)\nfm_M03 = np.zeros((lms.size, vms.size))\nfor i in range(len(lms)):\n fce_M03[i] = flce_M03(lm=lms[i])\n fpe_M03[i] = fpelm_M03(lm=lms[i]) \n for j in range(len(vms)):\n fm_M03[j, i] = fvce_M03(vm=vms[j])*fce_M03[i] + fpe_M03[i]\n```\n\n\n```python\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef flv3dplot(ax, lm, vm, fm, model):\n # 3d plot\n lm2, vm2 = np.meshgrid(lm, vm)\n ax.plot_surface(lm2, vm2, fm, rstride=2, cstride=2, cmap=plt.cm.coolwarm,\n linewidth=.5, antialiased=True)\n ax.plot(np.ones(vms.size), vms, fm[:, np.argmax(lm>=1)], 'w', linewidth=4)\n ax.plot(lm, np.zeros(lm.size), fm[np.argmax(vm>=0),:], 'w', linewidth=4)\n ax.set_xlim3d(lm[0], lm[-1])\n ax.set_ylim3d(vm[0], vm[-1])\n #ax.set_zlim3d(np.min(fm), np.max(fm))\n ax.set_zlim3d(0, 2)\n ax.set_xlabel('Normalized length')\n ax.set_ylabel('Normalized velocity')\n ax.set_zlabel('Normalized force')\n ax.view_init(20, 225)\n ax.locator_params(nbins=6)\n ax.text(-0.4, 0.7, 2.5, model, fontsize=14)\n \nfig = plt.figure(figsize=(12, 6))\nax1 = fig.add_subplot(1, 2, 1, projection='3d')\nflv3dplot(ax1, lms, vms, fm_T03, 'T03')\nax2 = fig.add_subplot(1, 2, 2, projection='3d')\nflv3dplot(ax2, lms, vms, fm_M03, 'M03')\nplt.suptitle('Force-length-velocity relationship', y=1, fontsize=16)\nplt.tight_layout()\nplt.show()\n```\n\n### Activation dynamics\n\nActivation dynamics represents the fact that a muscle cannot instantly activate or deactivate because of the electrical and chemical processes involved and it is usually integrated with a Hill-type model. In its simplest form, the activation dynamics is generally represented as a first-order ODE. \n\nThelen2003Muscle employed the following first-order [ordinary differential equation (ODE)](http://en.wikipedia.org/wiki/Ordinary_differential_equation):\n\n\\begin{equation}\n\\frac{\\mathrm{d}a}{\\mathrm{d}t} = \\dfrac{u-a}{\\tau(a, u)}\n\\label{}\n\\end{equation}\n\nwith a lower activation bound to both activation and excitation.\n\nwhere $u$ and $a$ are the muscle excitation and activation, respectively (both are function of time), and $\\tau$ is a variable time constant to represent the activation and deactivation times, given by:\n\n\\begin{equation} \n\\tau(a, u) = \\left\\{ \n \\begin{array}{l l}\n t_{act}(0.5+1.5a) \\quad & \\text{if} \\quad u > a\\\\\n \\dfrac{t_{deact}}{(0.5+1.5a)} \\quad & \\text{if} \\quad u \\leq a\n\\end{array} \\right.\n\\label{}\n\\end{equation}\n\nThelen2003Muscle adopted activation, $t_{act}$, and deactivation, $t_{deact}$, time constants for young adults equal to 15 and 50 ms, respectively (for old adults, Thelen2003Muscle adopted 15 and 60 ms, respectively).\n\nMcLean2003Muscle expressed the activation dynamics as the following first-order ODE:\n\n\\begin{equation}\n\\dfrac{\\mathrm{d}a}{\\mathrm{d}t} = (u - a)(c_1u + c_2)\n\\label{}\n\\end{equation}\n\nwith a lower activation bound to both activation and excitation.\n\nwhere $c_1 + c_2$ is the activation rate constant (when $u = 1$), the inverse of $t_{act}$, and $c_2$ is the deactivation rate constant (when $u = 0$), the inverse of $t_{deact}$. \nMcLean2003Muscle adopted $c_1=3.3 s^{-1}$ and $c_2=16.7 s^{-1}$, resulting in time constants of 50 ms and 60 ms for activation and deactivation, respectively.\n\nIn Python, the numeric first-order ODE for the activation dynamics presented in Thelen2003Muscle can be expressed as:\n\n\n```python\ndef actdyn_T03(t, a, t_act, t_deact, u_max, u_min, t0=0, t1=1):\n \"\"\"Thelen (2003) activation dynamics, the derivative of `a` at `t`.\n\n Parameters\n ----------\n t : float\n time instant [s]\n a : float (0 <= a <= 1)\n muscle activation\n t_act : float\n activation time constant [s]\n t_deact : float\n deactivation time constant [s]\n u_max : float (0 < u_max <= 1), optional (default=1)\n maximum value for muscle excitation\n u_min : float (0 < u_min < 1), optional (default=0.01)\n minimum value for muscle excitation\n t0 : float [s], optional (default=0)\n initial time instant for muscle excitation equals to u_max\n t1 : float [s], optional (default=1)\n final time instant for muscle excitation equals to u_max\n\n Returns\n -------\n adot : float \n derivative of `a` at `t`\n \"\"\"\n\n u = excitation(t, u_max, u_min)\n if u > a:\n adot = (u - a)/(t_act*(0.5 + 1.5*a))\n else:\n adot = (u - a)/(t_deact/(0.5 + 1.5*a))\n\n return adot\n```\n\nIn Python, the numeric first-order ODE for the activation dynamics presented in McLean2003Muscle can be expressed as:\n\n\n```python\ndef actdyn_M03(t, a, t_act, t_deact, u_max=1, u_min=0.01, t0=0, t1=1):\n \"\"\"McLean (2003) activation dynamics, the derivative of `a` at `t`.\n\n Parameters\n ----------\n t : float\n time instant [s]\n a : float (0 <= a <= 1)\n muscle activation\n t_act : float\n activation time constant [s]\n t_deact : float\n deactivation time constant [s]\n u_max : float (0 < u_max <= 1), optional (default=1)\n maximum value for muscle excitation\n u_min : float (0 < u_min < 1), optional (default=0.01)\n minimum value for muscle excitation\n t0 : float [s], optional (default=0)\n initial time instant for muscle excitation equals to u_max\n t1 : float [s], optional (default=1)\n final time instant for muscle excitation equals to u_max\n\n Returns\n -------\n adot : float \n derivative of `a` at `t`\n \"\"\"\n \n c2 = 1/t_deact\n c1 = 1/t_act - c2\n u = excitation(t, u_max, u_min)\n adot = (u - a)*(c1*u + c2)\n \n return adot\n```\n\nLet's simulate the activation signal for a rectangular function as excitation signal:\n\n\n```python\ndef excitation(t, u_max=1, u_min=0.01, t0=0.1, t1=0.4):\n \"\"\"Excitation signal, a square wave.\n \n Parameters\n ----------\n t : float\n time instant [s]\n u_max : float (0 < u_max <= 1), optional (default=1)\n maximum value for muscle excitation\n u_min : float (0 < u_min < 1), optional (default=0.01)\n minimum value for muscle excitation\n t0 : float [s], optional (default=0.1)\n initial time instant for muscle excitation equals to u_max\n t1 : float [s], optional (default=0.4)\n final time instant for muscle excitation equals to u_max\n\n Returns\n -------\n u : float (0 < u <= 1)\n excitation signal\n \"\"\"\n \n u = u_min\n if t >= t0 and t <= t1:\n u = u_max\n \n return u\n```\n\nWe will solve the equation for $a$ by numerical integration using the [`scipy.integrate.ode`](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.integrate.ode.html) class of numeric integrators, particularly the `dopri5`, an explicit runge-kutta method of order (4)5 due to Dormand and Prince (a.k.a. ode45 in Matlab):\n\n\n```python\nimport warnings\ndef actdyn_ode45(fun, t0=0, t1=1, a0=0, t_act=0.015, t_deact=0.050, u_max=1, u_min=0.01):\n # Runge-Kutta (4)5 due to Dormand & Prince with variable stepsize ODE solver\n \n f = ode(fun).set_integrator('dopri5', nsteps=1, max_step=0.01, atol=1e-8) \n f.set_initial_value(a0, t0).set_f_params(t_act, t_deact, u_max, u_min)\n # suppress Fortran warning\n warnings.filterwarnings(\"ignore\", category=UserWarning)\n data = []\n while f.t < t1:\n f.integrate(t1, step=True)\n data.append([f.t, excitation(f.t, u_max, u_min), np.max([f.y, u_min])])\n warnings.resetwarnings()\n data = np.array(data)\n \n return data\n```\n\nSolving the problem for two different maximum excitation levels:\n\n\n```python\n# using the values for t_act and t_deact from Thelen2003Muscle for both models\nact1_T03 = actdyn_ode45(fun=actdyn_T03, u_max=1.0)\nact2_T03 = actdyn_ode45(fun=actdyn_T03, u_max=0.5)\nact1_M03 = actdyn_ode45(fun=actdyn_M03, u_max=1.0)\nact2_M03 = actdyn_ode45(fun=actdyn_M03, u_max=0.5)\n# using the values for t_act and t_deact from McLean2003Muscle\nact3_M03 = actdyn_ode45(fun=actdyn_M03, u_max=1.0, t_act=0.050, t_deact=0.060)\nact4_M03 = actdyn_ode45(fun=actdyn_M03, u_max=0.5, t_act=0.050, t_deact=0.060)\n```\n\nAnd the results:\n\n\n```python\nfig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True, figsize=(10, 6))\naxs[0, 0].plot(act1_T03[:, 0], act1_T03[:, 1], 'r:', label='Excitation')\naxs[0, 0].plot(act1_T03[:, 0], act1_T03[:, 2], 'b', label='T03 [15, 50] ms')\naxs[0, 0].plot(act1_M03[:, 0], act1_M03[:, 2], 'g', label='M03 [15, 50] ms')\naxs[0, 0].set_ylabel('Level')\naxs[0, 1].plot(act2_T03[:, 0], act2_T03[:, 1], 'r:', label='Excitation')\naxs[0, 1].plot(act2_T03[:, 0], act2_T03[:, 2], 'b', label='T03 [15, 50] ms')\naxs[0, 1].plot(act2_M03[:, 0], act2_M03[:, 2], 'g', label='M03 [15, 50] ms')\naxs[1, 1].set_xlabel('Time (s)')\naxs[0, 1].legend()\naxs[1, 0].plot(act1_T03[:, 0], act1_T03[:, 1], 'r:', label='Excitation')\naxs[1, 0].plot(act1_T03[:, 0], act1_T03[:, 2], 'b', label='T03 [15, 50] ms')\naxs[1, 0].plot(act3_M03[:, 0], act3_M03[:, 2], 'g', label='M03 [50, 60] ms')\naxs[1, 0].set_xlabel('Time (s)')\naxs[1, 0].set_ylabel('Level')\naxs[1, 1].plot(act2_T03[:, 0], act2_T03[:, 1], 'r:', label='Excitation')\naxs[1, 1].plot(act2_T03[:, 0], act2_T03[:, 2], 'b', label='T03 [15, 50] ms')\naxs[1, 1].plot(act4_M03[:, 0], act4_M03[:, 2], 'g', label='M03 [50, 60] ms')\naxs[1, 1].set_xlabel('Time (s)')\naxs[1, 1].legend()\nplt.suptitle('Activation dynamics', y=1, fontsize=16)\nplt.tight_layout()\nplt.show()\n```\n\nSimilar results when the same parameters are used (first row), but different bahavior when the typical values of each study are compared (second row).\n\n### Muscle modeling parameters\n\nWe have seen two types of parameters in the muscle modeling: parameters related to the mathematical functions used to model the muscle and tendon behavior and parameters related to the properties of specific muscles and tendons (e.g., maximum isometric force, optimal fiber length, pennation angle, and tendon slack). In general the first type of parameters are independent of the muscle-tendon unit being modeled (but dependent of the model!) while the second type of parameters is changed for each muscle-tendon unit (for instance, see http://isbweb.org/data/delp/ for some of these parameters).\n\n### Limitations of Hill-type muscle models\n\nAs with any modeling, Hill-type muscle models are a simplification of the reality. For instance, a typical Hill-type muscle model (as implemented here) does not capture time-dependent muscle behavior, such as force depression after quick muscle shortening, force enhancement after quick muscle lengthening, viscoelastic properties (creep and relaxation), and muscle fatigue (Zatsiorsky and Prilutsky, 2012). There are enhanced models that capture these properties but it seems their complexity are not worthy for the most common applications of human movement simulation.\n\n## Exercises\n\n1. The results presented in this text depend on the parameters used in the model. These parameters may vary because of different properties of the muscle and tendon but also because different mathematical functions may be used. \n a. Change some of the parameters and reproduce the plots shown here and discuss these results (e.g., use the parameters for different muscles from OpenSim or the data from [http://isbweb.org/data/delp/](http://isbweb.org/data/delp/)). \n b. Select another reference (e.g., Anderson, 2007) about muscle modeling that uses different mathematical functions and repeat the previous item.\n\n## References\n\n- Anderson C (2007) [Equations for Modeling the Forces Generated by Muscles and Tendons](https://docs.google.com/viewer?url=https%3A%2F%2Fsimtk.org%2Fdocman%2Fview.php%2F124%2F604%2FMuscleAndTendonForcesClayAnderson20070521.doc) ([PDF](https://drive.google.com/open?id=0BxbW72zV7WmUVUh0MldGOGZ6aHc&authuser=0)). BioE215 Physics-based Simulation of Biological Structures. \n- Erdemir A, McLean S, Herzog W, van den Bogert AJ (2007) [Model-based estimation of muscle forces exerted during movements](http://www.ncbi.nlm.nih.gov/pubmed/17070969). Clinical Biomechanics, 22, 131–154. \n- He J, Levine WS, Loeb GE (1991) [Feedback gains for correcting small perturbations to standing posture](https://drive.google.com/open?id=0BxbW72zV7WmUekRXY09GSEhUVlE&authuser=0). IEEE Transactions on Automatic Control, 36, 322–332. \n- McLean SG, Su A, van den Bogert AJ (2003) [Development and validation of a 3-D model to predict knee joint loading during dynamic movement](http://www.ncbi.nlm.nih.gov/pubmed/14986412). Journal of Biomechanical Engineering, 125, 864-74. \n- McMahon TA (1984) [Muscles, Reflexes, and Locomotion](https://archive.org/details/McMahonTAMusclesReflexesAndLocomotionPrincetonUniversityPress1984). Princeton University Press, Princeton, New Jersey. \n- Millard M, Uchida T, Seth A, Delp SL (2013) [Flexing computational muscle: modeling and simulation of musculotendon dynamics](http://www.ncbi.nlm.nih.gov/pubmed/23445050). Journal of Biomechanical Engineering, 135, 021005. \n- Nigg BM and Herzog W (2006) [Biomechanics of the Musculo-skeletal System](https://books.google.com.br/books?id=hOIeAQAAIAAJ&dq=editions:ISBN0470017678). 3rd Edition. Wiley. \n- Robertson G, Caldwell G, Hamill J, Kamen G (2013) [Research Methods in Biomechanics](http://books.google.com.br/books?id=gRn8AAAAQBAJ). 2nd Edition. Human Kinetics. \n- Thelen DG (2003) [Adjustment of muscle mechanics model parameters to simulate dynamic contractions in older adults](http://homepages.cae.wisc.edu/~thelen/pubs/jbme03.pdf). Journal of Biomechanical Engineering, 125(1):70–77.\n- Tsianos GA and Loeb GE (2013) [Muscle Physiology and Modeling](http://www.scholarpedia.org/article/Muscle_Physiology_and_Modeling). Scholarpedia, 8(10):12388. \n- Winters JM (1990) [Hill-based muscle models: a systems engineering perspective](http://link.springer.com/chapter/10.1007%2F978-1-4613-9030-5_5). In [Multiple Muscle Systems: Biomechanics and Movement Organization](http://link.springer.com/book/10.1007/978-1-4613-9030-5), edited by JM Winters and SL Woo, Springer-Verlag, New York. \n- Winters JM (1995) [An Improved Muscle-Reflex Actuator for Use in Large-Scale Neuromusculoskeletal Models](http://www.ncbi.nlm.nih.gov/pubmed/7486344). Annals of Biomedical Engineering, 23, 359–374. \n- Zajac FE (1989) [Muscle and tendon: properties, models, scaling and application to biomechanics and motor control](http://www.ncbi.nlm.nih.gov/pubmed/2676342). Critical Reviews in Biomedical Engineering 17:359-411. \n- Zatsiorsky V and Prilutsky B (2012) [Biomechanics of Skeletal Muscles](http://books.google.com.br/books?id=THXfHT8L5MEC). Human Kinetics. \n", "meta": {"hexsha": "4a7262795a0080ae970b4647d0f2b0197d019d90", "size": 679595, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/MuscleModeling.ipynb", "max_stars_repo_name": "0todd0000/BMC", "max_stars_repo_head_hexsha": "bfad103e0fc02afc662ce417bf062b4758a39897", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-05-08T20:20:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-08T20:20:51.000Z", "max_issues_repo_path": "notebooks/MuscleModeling.ipynb", "max_issues_repo_name": "0todd0000/BMC", "max_issues_repo_head_hexsha": "bfad103e0fc02afc662ce417bf062b4758a39897", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/MuscleModeling.ipynb", "max_forks_repo_name": "0todd0000/BMC", "max_forks_repo_head_hexsha": "bfad103e0fc02afc662ce417bf062b4758a39897", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 387.6754135767, "max_line_length": 319016, "alphanum_fraction": 0.9256880936, "converted": true, "num_tokens": 14438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.348289039331495}} {"text": "```python\nimport math\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\n\nimport io\nimport torchtext\nfrom torchtext.utils import download_from_url, extract_archive\nfrom torchtext.data.utils import get_tokenizer\nfrom torchtext.vocab import build_vocab_from_iterator\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning.trainer.trainer import Trainer\nfrom pytorch_lightning import seed_everything\nseed_everything(42)\n\n```\n\n\n\n\n 42\n\n\n\n# Dataset Preparation\n\nThis tutorial uses ``torchtext`` to generate Wikitext-2 dataset. The\nvocab object is built based on the train dataset and is used to numericalize\ntokens into tensors. \n\nWith the alphabet as the sequence (total length of 26)\nand a batch size of 4, we would divide the alphabet into 4 sequences of\nlength 6:\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\nThese columns are treated as independent by the model, which means that\nthe dependence of ``G`` and ``F`` can not be learned, but allows more\nefficient batch processing.\n\n# Inputa and Target\n\nFor the language modeling task, the model needs the following words as Target. For example, with a seq_len value of 2, we’d get the following two Variables.\n\n**Note:** It should be noted that the chunks are along dimension 0, consistent with the S dimension in the Transformer model. The batch dimension N is along dimension 1.\n\n\n\n\n\n\n\n```python\nclass AlarmDataset(Dataset):\n def __init__(self,data,seq_len,batch_size):\n self.length = len(data)//seq_len # how much data i have \n self.data = data\n self.seq_len = seq_len\n self.batch_size = batch_size\n \n def __getitem__(self, index: int):\n x = self.data[index*self.seq_len:(index*self.seq_len)+seq_len]\n y = self.data[1+index*self.seq_len:1+(index*self.seq_len)+seq_len]\n return x,y\n \n def __len__(self) -> int:\n return self.length\n\nclass MyDataModule(pl.LightningDataModule):\n \n def __init__(self, data_path:str, batch_size:int, seq_len:int):\n super().__init__()\n self.batch_size = batch_size\n \n url = data_path\n test_filepath, valid_filepath, train_filepath = extract_archive(download_from_url(url))\n self.tokenizer = get_tokenizer('basic_english')\n self.vocab = build_vocab_from_iterator(map(self.tokenizer,iter(io.open(train_filepath,encoding=\"utf8\"))))\n \n train_data = self.data_process(iter(io.open(train_filepath, encoding=\"utf8\")))\n val_data = self.data_process(iter(io.open(valid_filepath, encoding=\"utf8\")))\n test_data = self.data_process(iter(io.open(test_filepath, encoding=\"utf8\")))\n\n # print(train_data[0:100])\n # print([])\n \n self.train_dataset = AlarmDataset(train_data, seq_len,self.batch_size)\n self.valid_dataset = AlarmDataset(val_data,seq_len,self.batch_size)\n self.test_dataset = AlarmDataset(test_data, seq_len,self.batch_size)\n \n def data_process(self, raw_text_iter):\n data = [torch.tensor([self.vocab[token] for token in self.tokenizer(item)],dtype=torch.long) for item in raw_text_iter]\n return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))\n\n\n def setup(self, stage: None):\n return None\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(self.train_dataset, batch_size=self.batch_size, shuffle=False,num_workers=1,drop_last=True, pin_memory=True)\n \n def val_dataloader(self) -> DataLoader:\n return DataLoader(self.valid_dataset, batch_size=self.batch_size, shuffle=False,num_workers=1,drop_last=True, pin_memory=True)\n \n def test_dataloader(self):\n return DataLoader(self.test_dataset, batch_size=self.batch_size, shuffle=False,num_workers=1,drop_last=True, pin_memory=True)\n \n```\n\n# Transformer Model\n\nIn this tutorial, we train ``nn.TransformerEncoder`` model on a\nlanguage modeling task. The language modeling task is to assign a\nprobability for the likelihood of a given word (or a sequence of words)\nto follow a sequence of words. A sequence of tokens are passed to the embedding\nlayer first, followed by a positional encoding layer to account for the order\nof the word (see the next paragraph for more details). The\n``nn.TransformerEncoder`` consists of multiple layers of\n`nn.TransformerEncoderLayer `__. Along with the input sequence, a square\nattention mask is required because the self-attention layers in\n``nn.TransformerEncoder`` are only allowed to attend the earlier positions in\nthe sequence. For the language modeling task, any tokens on the future\npositions should be masked. To have the actual words, the output\nof ``nn.TransformerEncoder`` model is sent to the final Linear\nlayer, which is followed by a log-Softmax function.\n\n\n# Positional Encoding\n\n``PositionalEncoding`` module injects some information about the\nrelative or absolute position of the tokens in the sequence. The\npositional encodings have the same dimension as the embeddings so that\nthe two can be summed. Here, we use ``sine`` and ``cosine`` functions of\ndifferent frequencies.\n\n\n\n\n\n\n\n\n```python\nclass TransformerModel(pl.LightningModule):\n\n def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5, seq_len=None):\n super(TransformerModel, self).__init__()\n self.model_type = 'Transformer'\n self.ntoken = ntoken\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n encoder_layers = torch.nn.TransformerEncoderLayer(ninp, nhead, nhid, dropout)\n self.transformer_encoder = torch.nn.TransformerEncoder(encoder_layers, nlayers)\n self.encoder = torch.nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.decoder = torch.nn.Linear(ninp, ntoken)\n self.src_mask = self.generate_square_subsequent_mask(seq_len)\n self.seq_len = seq_len \n self.init_weights()\n\n def generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src, src_mask):\n src_mask = src_mask.to(self.device)\n src = self.encoder(src) * math.sqrt(self.ninp)\n src = self.pos_encoder(src)\n src_mask = src_mask.to(self.device)\n \n output = self.transformer_encoder(src, src_mask)\n output = self.decoder(output)\n \n return output\n \n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=0.001, weight_decay=0.0000001)\n return optimizer\n \n def training_step(self,batch,batch_idx):\n x,y = batch\n x = x.T\n y = y.T.reshape(-1)\n\n # print(\"Training Shape: \", x.size(),y.size())\n \n if x.size(0) != self.seq_len:\n self.src_mask = self.generate_square_subsequent_mask(x.size(0))\n \n y_hat = self(x,self.src_mask)\n\n loss = F.cross_entropy(y_hat.view(-1, self.ntoken),y)\n self.log('train_loss', loss,on_step=True, prog_bar=True, logger=True)\n self.log(\"train_ppl\",math.exp(loss.item()),on_step=True, prog_bar=True, logger=True)\n return loss\n \n def validation_step(self,batch, batch_idx):\n x,y = batch\n x = x.T\n y = y.T.reshape(-1)\n\n # print(\"Validation Shape: \", x.size(),y.size())\n\n if x.size(0) != self.seq_len:\n self.src_mask = self.generate_square_subsequent_mask(x.size(0))\n \n y_hat = self(x,self.src_mask)\n # print(\"> y-hat\",y_hat.size())\n loss = F.cross_entropy(y_hat.view(-1, self.ntoken),y)\n self.log('val_loss', loss, on_step=True, prog_bar=True, logger=True)\n self.log(\"val_ppl\",math.exp(loss.item()),on_step=True, prog_bar=True, logger=True)\n return {'val_loss':loss}\n \n def test_step(self,batch, batch_idx):\n x,y = batch\n x = x.T\n y = y.T.reshape(-1)\n\n # print(\"Validation Shape: \", x.size(),y.size())\n\n if x.size(0) != self.seq_len:\n self.src_mask = self.generate_square_subsequent_mask(x.size(0))\n \n y_hat = self(x,self.src_mask)\n # print(\"> y-hat\",y_hat.size())\n loss = F.cross_entropy(y_hat.view(-1, self.ntoken),y)\n self.log('test_loss', loss, on_step=True, prog_bar=True, logger=True)\n self.log(\"test_ppl\",math.exp(loss.item()),on_step=True, prog_bar=True, logger=True)\n return {'test_loss':loss}\n \n def training_epoch_end(self, outputs):\n avg_loss = torch.stack([d['loss'] for d in outputs]).mean()\n print(f\"> Avg Training loss = {avg_loss}\")\n \n def validation_epoch_end(self, outputs):\n # print(outputs)\n avg_loss = torch.stack([d['val_loss'] for d in outputs]).mean()\n print(f\"> Average Valid Loss = {avg_loss}\")\n \n def test_epoch_end(self, outputs):\n avg_loss = torch.stack([d['test_loss'] for d in outputs]).mean()\n print(f\"> Average Test Loss = {avg_loss}\")\n \n \nclass PositionalEncoding(torch.nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = torch.nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\n# Hyperparameters\n\n\n```python\nurl = 'https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip'\n\nbsize = 20\nseq_len = 35\ndm = MyDataModule(url,bsize,seq_len)\n\nntokens = len(dm.vocab.stoi) # the size of vocabulary\nemsize = 200 # embedding dimension\nnhid = 200 # the dimension of the feedforward network model in nn.TransformerEncoder\nnlayers = 2 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder\nnhead = 2 # the number of heads in the multiheadattention models\ndropout = 0.2 # the dropout value\n\nmodel = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout,seq_len=seq_len)\ntrainer = Trainer(gpus=1,max_epochs=1,check_val_every_n_epoch=1,deterministic=True, gradient_clip_val=0.5)\ntrainer.fit(model,dm) # traning and validation\n```\n\n 36718lines [00:01, 29608.89lines/s]\n GPU available: True, used: True\n INFO:lightning:GPU available: True, used: True\n TPU available: None, using: 0 TPU cores\n INFO:lightning:TPU available: None, using: 0 TPU cores\n LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n INFO:lightning:LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]\n \n | Name | Type | Params\n -----------------------------------------------------------\n 0 | pos_encoder | PositionalEncoding | 0 \n 1 | transformer_encoder | TransformerEncoder | 484 K \n 2 | encoder | Embedding | 5.8 M \n 3 | decoder | Linear | 5.8 M \n -----------------------------------------------------------\n 12.0 M Trainable params\n 0 Non-trainable params\n 12.0 M Total params\n INFO:lightning:\n | Name | Type | Params\n -----------------------------------------------------------\n 0 | pos_encoder | PositionalEncoding | 0 \n 1 | transformer_encoder | TransformerEncoder | 484 K \n 2 | encoder | Embedding | 5.8 M \n 3 | decoder | Linear | 5.8 M \n -----------------------------------------------------------\n 12.0 M Trainable params\n 0 Non-trainable params\n 12.0 M Total params\n\n\n\n Validation sanity check: | | 0/? [00:00 Average Valid Loss = 10.613945960998535\n\n\n\n Training: | | 0/? [00:00 Average Valid Loss = 5.521843433380127\n > Avg Training loss = 6.123049259185791\n\n\n\n\n\n 1\n\n\n\n\n```python\ntrainer.test(datamodule=dm) # testing\n# %%\n```\n\n\n Testing: | | 0/? [00:00 Average Test Loss = 5.444727897644043\n --------------------------------------------------------------------------------\n DATALOADER:0 TEST RESULTS\n {'test_loss': tensor(5.7169, device='cuda:0'),\n 'test_loss_epoch': tensor(5.4447, device='cuda:0'),\n 'test_ppl': 303.96751971676264,\n 'test_ppl_epoch': tensor(241.8977),\n 'val_loss': tensor(5.3272, device='cuda:0'),\n 'val_loss_epoch': tensor(5.5218, device='cuda:0'),\n 'val_ppl': 205.85485347893808,\n 'val_ppl_epoch': tensor(258.1052)}\n --------------------------------------------------------------------------------\n\n\n\n\n\n [{'val_loss_epoch': 5.521843910217285,\n 'val_ppl_epoch': 258.105224609375,\n 'val_loss': 5.327171325683594,\n 'val_ppl': 205.85485347893808,\n 'test_loss_epoch': 5.444727897644043,\n 'test_ppl_epoch': 241.89773559570312,\n 'test_loss': 5.716920852661133,\n 'test_ppl': 303.96751971676264}]\n\n\n", "meta": {"hexsha": "82299ea483e498bd8dac58556eacaa731f5dfdf1", "size": 20219, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "transformers/t1_pl_next_word_pred.ipynb", "max_stars_repo_name": "warisgill/ml-dl-tutorials", "max_stars_repo_head_hexsha": "bf8cd628ea8a97d02316a908cdf707211b89a7bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "transformers/t1_pl_next_word_pred.ipynb", "max_issues_repo_name": "warisgill/ml-dl-tutorials", "max_issues_repo_head_hexsha": "bf8cd628ea8a97d02316a908cdf707211b89a7bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformers/t1_pl_next_word_pred.ipynb", "max_forks_repo_name": "warisgill/ml-dl-tutorials", "max_forks_repo_head_hexsha": "bf8cd628ea8a97d02316a908cdf707211b89a7bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7229862475, "max_line_length": 584, "alphanum_fraction": 0.5411741431, "converted": true, "num_tokens": 3629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.348289039331495}} {"text": "

Unit 10

\n

Case Study 4: Object Recognition with Deep Learning

\n
\n
\n
\n

IST 718 – Big Data Analytics

\n

Daniel E. Acuna

\n

http://acuna.io

\n\n# Object recognition problem\n- A bit of neuroscience.\n- From logistic regression to neural networks.\n- The perceptron.\n- Multi-layer perceptron.\n- Training neural networks.\n- Demo with multi-layer perceptron.\n\n# The object recognition problem\n- Detect an object present in an image. \n
\n
\n\n
\n
Caltech101 dataset (year 2003)
\n
101 categories of objects, each category has 40 to 800 images
\n\n\n# A high dimensional problem\n- Each image is 300 x 200 x 3 pixels (width x height x channels.)\n - 180,000 \"raw\" features. \n \n- Relationship between raw features and classes is highly non-linear.\n - Spatial features that could appear anywhere on the image.\n - Local features (e.g., shapes) vs global features (e.g., contrast.)\n\n# A high dimensional problem (2)\n
\n
\n
\n
Credit: https://www.st-andrews.ac.uk/~www_pa/Scots_Guide/info/signals/pixels/
\n\n# A problem with logistic regression\n- We are trying to learn: \n\n$$p(y \\mid X) = \\frac{1}{1 + \\exp(-(\\theta_0 + \\sum_{j>0}{x_j\\theta_j}))}$$ \n\n- So only a linear relationship between pixels $x$ and class $y$.\n\n# Classic data science\n- Features fed into the algorithms are meaningful and provided by experts. \n\n- Machine learning algorithms only provide 1 or 2 step transformations. \n\n- Complexity of problems is relatively small.\n\n# A bit of neuroscience\n- Deep learning takes loose inspiration from how the brain works. \n\n- At an architectural level, the brain works by combining specialized neurons in hierarchies. \n\n- E.g., the visual system is organized into several areas (around 8.)\n\n
\n\n
\n\n# A bit of neuroscience (2)\n- The brain has relatively \"simple\" processing units: neurons.
\n
\n
\n
\n
Credit: http://www.intechopen.com/source/html/39067/media/image1.png
\n\n
\n\n
\n$$p(y \\mid X) = \\frac{1}{1 + \\exp(-(\\theta_0 + \\sum_{j>0}{x_j\\theta_j}))}$$ \n**
A model for the probability of an action potential!
**\n\n# Of course reality is a lot more complicated\n
\n
\n\n# Of course reality is a lot more complicated\n
\n
\n\n# The general idea of artificial neural networks\n- Simple processing units with linear or non-linear functions $f$. \n
\n
\n\n# The general idea of artificial neural networks (2)\n- Multiple units belong to layers and those layers are interconnected to other layers. \n
\n
\n\n# A highly non-linear function\n- The output now depends on nested functions: \n\n\n$$y = \\underbrace{f_3\\left(\\;\\underbrace{f_2\\left(\\;\\underbrace{f_1(x)}_{\\text{first layer}} + b_0\\right)}_{\\text{second layer}} + b_1\\right) + b_2}_{\\text{third layer (nested non-linearities)}}$$\n\n# Advantages and disadvantages of ANN\n- Pros:\n - Can fit complex non-linear relationships.\n - Easy to try different types of layers.\n - Inspired by a very effective machine (the brain!) \n \n- Cons:\n - Many parameters.\n - Easy to overfit.\n - Needs lots of training data.\n - Takes a long time to fit.\n - The use of brain research is really minimal.\n\n# How to train a neural network?\n- We define a loss function and try to find best value: \n\n$$\\arg\\min_{\\Theta} {l(\\;f_\\Theta(X),y)}$$\n\n- For example: \n\n$$l(\\;f_\\Theta(X),y) = \\sum(\\;f_\\Theta(X_i) - y_i)^2$$ \n
\n
where $f_\\Theta(X)$ is the function represented by the entire network.
\n\n\n# Optimizing the loss function\n- There is no close solution to the loss function: \n\n$$\\arg\\min_{\\Theta} {l(\\;f_\\Theta(X),y)}$$ \n\n- In all but the trivial cases, the loss function is *non-convex* (hard to optimize.) \n\n- A very effective approach to perform stochastic gradient descent.\n\n# Gradient descent\n- Gradient descent is a simple approach to iteratively minimize a loss function. \n\n- Intuitively, we want to follow the *negative* of the gradient to find the minimum of a loss function: \n\n$$\\Theta_{t+1} = \\Theta_{t} - \\eta \\nabla l(\\;f_\\Theta(X),y)$$ \n\n# Gradient descent: example\n
\n
\n\n# Gradient descent: example (2)\n
\n
\n\n# Gradient descent: example (3)\n
\n
\n\n# Gradient descent: example (4)\n
\n
\n\n# Gradient descent: example (5)\n
\n
\n\n# Gradient descent: problems\n- It finds the global optimum when function is convex (e.g., a parabola) and the learning rate is appropriate.\n- But:\n
\n
\n\n# Stochastic gradient descent\n- If we look at a fraction of the training data, we only observe a (noisy) sample of the loss function. \n
\n
\n\n# Stochastic gradient descent (2)\n- If we look at a fraction of the training data, we only observe a (noisy) sample of the loss function. \n
\n
\n\n# Stochastic gradient descent (3)\n- If we look at a fraction of the training data, we only observe a (noisy) sample of the loss function. \n\n- Stochastic gradient descent is good for big data (we only need pieces at a time.) \n\n- Stochastic gradient descent can escape local minima. \n\n- As long as we can compute gradients, we can use function we want!\n\n# Worked-out example\n- A simple neural network with one neuron and one layer. \n\n- More assumptions sigmoid activation $f$ and $a = y$. \n
\n
\n\n# Worked-out example (2)\n- A simple neural network with one neuron and one layer. \n\n- More assumptions sigmoid activation $f$ and $a = y$. \n
\n
\n**
Similar to Logistic Regression!
**\n\n\n# Worked-out example (3)\n- Using quadratic loss function, let’s work out the stochastic gradient descent update rule: \n\n$$\\Theta_{t+1} = \\Theta_{t} - \\eta \\nabla l(\\;f_\\Theta(X),y)$$ \n\n$$l(\\;f_\\Theta(X),y) = (\\;f(z) - y)^2 = \\left(\\sigma\\left(\\sum{x_j\\theta_j} - y\\right)\\right)^2$$ \n\n$$\\nabla{l(\\;f_\\Theta(X),y)} = \\left[\\frac{dl}{d\\theta_0}, \\frac{dl}{d\\theta_1}, \\ldots, \\frac{dl}{d\\theta_m}\\right]$$\n\n# Worked-out example (4)\n- Let’s pick one the gradients: \n\n$$\\begin{align}\n\\nabla{l(\\;f_\\Theta(X),y)} &= \\left[\\frac{dl}{d\\theta_0}, \\frac{dl}{d\\theta_1}, \\ldots, \\frac{dl}{d\\theta_m}\\right] \\\\\n\\frac{dl}{d\\theta_j} &= \\frac{d\\left(\\sigma\\left(\\sum{x_j\\theta_j} - y\\right)\\right)^2}{d\\theta_j}\n\\end{align}$$ \n\n- We are trying to compute the gradient of a nested function, what to do?\n\n# Worked-out example (5)\n
\n\n\n- We can apply basic calculus. \n\n- By representing each nested function on its own: \n\n$$\\frac{d\\left(\\sigma\\left(\\sum{x_j\\theta_j} - y\\right)\\right)^2}{d\\theta_j} = \\frac{d}{d\\theta_j} l(a(z(\\theta_0, \\cdots, \\theta_m, x), y)$$\n\n- Where $a$ is the activation, and $z$ is the summation. \n\n- Now we can simply apply the chain rule!\n\n# Worked-out example (6)\n- We can apply basic calculus.\n- By representing each nested function on its own:\n$$\\frac{d}{d\\theta_j} l(a(z(\\theta_0, \\cdots, \\theta_m, x), y) = \\frac{dl}{da}\\frac{da}{dz}\\frac{dz}{d\\theta_j}$$\n\n$$\n\\frac{dl}{da} = 2(a - y) \\qquad\n\\frac{da}{dz} = a(1-a) \\qquad\n\\frac{dz}{d\\theta_j} = x_j\n$$\n\n$$\\begin{align}\n\\Theta_j^{\\text{new}} &\\leftarrow \\Theta_j^{\\text{old}} - \\eta \\;{2(a-y)} \\;{a(1-a)} \\;{x_j} \\\\\n&\\leftarrow \\Theta_j^{\\text{old}} - \\eta \\;{\\left(\\sigma\\left(\\sum{x_j\\theta_j}\\right) - y\\right)} \\;{\\sigma\\left(\\sum{x_j\\theta_j}\\right)} \\;{\\left(1 - \\sigma\\left(\\sum{x_j\\theta_j}\\right)\\right)} {x_j}\n\\end{align}$$\n\n# Backpropagation\n- The previous example is the basis of stochastic gradient descent for several layers.\n- **Backpropagation** is a general algorithm that exploits the structure of the chain rule when applied to layers.\n- To understand backpropagation, we need to understand middle layers: \n
\n
\n\n# Backpropagation (2)\n- $\\theta_{ij}^{L-2}$: connection between neuron $j$ in layer $L-2$ to neuron $i$ in layer $L-1$.\n\n- Representing all connections from $L-2$ to $L-2$ as one matrix $\\theta^{L-2}$, we can predict all activation of layer $L-1$ as: \n\n$$a^{L-1} = f(\\theta^{L-2} a^{L-2})$$ \n\n
\n
\n\n# Backpropagation (3)\n- Then the gradient of a connection $\\theta_{ij}^{L-2}$ with respect to the loss function will be: \n\n$$\\frac{dl}{d\\theta_{ij}^{L-2}} = \\frac{dz_i^{L-1}}{d\\theta_{ij}{L-2}}\\frac{da_i^{L-1}}{dz_i^{L-1}} \\sum{\\frac{dz^L}{da_i^{L-1}} \\frac{da^L}{dz^L} \\frac{dl}{da^L}}$$ \n\n
\n
\n\n# Backpropagation (4)\n- Then the gradient of a connection $\\theta_{jk}^{L-3}$ with respect to the loss function will be: \n\n$$\\frac{dl}{d\\theta_{jk}^{L-3}} = \\frac{dz_j^{L-2}}{d\\theta_{jk}^{L-3}}\\frac{da_j^{L-2}}{dz_j^{L-2}} \\sum{\\frac{dz_i^{L-1}}{da_j^{L-2}} \\frac{da_i^{L-1}}{dz_i^{L-1}}} \\sum{\\frac{dz^L}{da_i^{L-1}} \\frac{da^L}{dz^L} \\frac{dl}{da^L}} $$ \n\n
\n
\n\n# Backpropagation (5)\n- The same structure gets repeated during the chain rule:\n\n$$\\frac{dl}{d\\theta_{ij}^{L-2}} = \\frac{dz_i^{L-1}}{d\\theta_{ij}{L-2}}\\frac{da_i^{L-1}}{dz_i^{L-1}} \\sum{\\frac{dz^L}{da_i^{L-1}} \\frac{da^L}{dz^L} \\frac{dl}{da^L}}$$ \n\n$$\\frac{dl}{d\\theta_{jk}^{L-3}} = \\frac{dz_j^{L-2}}{d\\theta_{jk}^{L-3}}\\frac{da_j^{L-2}}{dz_j^{L-2}} \\sum{\\frac{dz_i^{L-1}}{da_j^{L-2}} \\frac{da_i^{L-1}}{dz_i^{L-1}}} \\sum{\\frac{dz^L}{da_i^{L-1}} \\frac{da^L}{dz^L} \\frac{dl}{da^L}}$$\n\n- Therefore, we can *backpropagate* the gradient of the loss function. \n- Notice also, that we reuse $a$ and $z$ multiple times, therefore we could precompute them. \n- Consequently, we could forward propagate $a$ and $z$ and *backpropagate* the errors.\n\n# Backpropagation algorithm\n\nForward propagation\n1. From layer $1$ thought $L$ \n 1.1 Compute $a$ and $z$\n\nBackpropagation\n1. Define $\\delta_i^L = a^L-y$ (gradient of loss function)\n2. From layer $L–1$ to $1$ \n 2.1 Define $\\delta_j^{L-1} = a_j^{L-1} (1 - a_j^{L-1}) \\sum{\\theta_{ij}^{L-1} \\delta_i^L}$\n\nThe gradients will be computed as follows: \n$$\\frac{dl}{d\\theta_{ij}^k} = a_j^k a_i^{k+1} (1 - a_i^{k+1}) \\sum{a_i^{k+1} \\delta_i^{k+1}} $$\n\n# Demo\n\n# Problems with classic methods\n- The more layers, the more complex representations can be learned. \n\n- However, more layers also implies longer chains. \n\n- This produces numerical errors and small changes in learning. \n\n- Groundbreaking paper in 2006 proposes to train deep architectures in a novel way.\n\n# Deep learning\n- Also, new developments in:\n - Training techniques (2006)\n - GPU computing (2008)\n - Big data.\n - New types of architectures (new neurons and layers.)\n \n- This opened the door to train increasingly more complex models. \n\n- Next class we will take a look at these advances\n\n\n# Other architectures\n- Multi-layer perceptron looses spatial location (specially in images.) \n\n- Some features are independent of location.\n\n
\n
\n\n# Convolutional neural networks\n- Create translational-invariant spatial filters (share weights.)\n\n
\n
\n
\n
http://cs231n.github.io/convolutional-networks/
\n\n# Convolutional neural networks (2)\n- It can learn filters similar to what is observed in nature!\n\n
\n
\n\n# Convolutional neural networks (3)\n- Digits classification: classic MNIST problem.\n\n
\n
\n
\n
http://cs.stanford.edu/people/karpathy/convnetjs/demo/mnist.html
\n\n# Dealing with temporal data\n- Sometimes we want to capture temporal-invariance:\n - E.g., in chess, the state of the next move only depends on the current move.\n - Makes learning more efficient.\n - Allows to interpret results.\n \n
\n\n# Recurrent neural networks\n
\n
\n\n# Recurrent neural networks (2)\n- Naïve recurrent neural network training leads to numerical problems:\n$$y = h(A(A(A(\\ldots A(y_{t-T}))$$ \n\n- Why? How would the chain rule apply here? \n\n- Other more advanced neural network allows to learn long-term dependencies easier. \n
\n\n# Recurrent neural networks (3)\n- Handwriting generation:\n http://www.cs.toronto.edu/~graves/handwriting.html \n \n \n- Generating Wikipedia articles: \n
\n\n# More complex temporal problems\n
\n
\n
\n
Can you think of examples for each of this cases?
\n\n# More complex temporal problems (2)\n
\n
\n\n# More complex temporal problems (3)\n
\n
\n\n# More complex temporal problems (4)\n
\n
\n\n# Reinforcement learning\n- Given semi-supervised feedback, learn how to perform actions so as to maximize total reward. \n\n- Classical framework to study behavior in humans and animals. \n\n
\n
\n\n# Reinforcement learning (2)\n
\n
\n\n# Reinforcement learning (3)\n
\n
http://cs.stanford.edu/people/karpathy/convnetjs/demo/rldemo.html
\n\n# Inferring intentions\n
\n
\n\n# WaveNet\n
\n
\n
\n
https://deepmind.com/blog/wavenet-generative-model-raw-audio/
\n\n\n# WaveNet\n
\n
\n
\n
https://deepmind.com/blog/wavenet-generative-model-raw-audio/
\n\n\n# WaveNet\n
\n
\n
\n
https://deepmind.com/blog/wavenet-generative-model-raw-audio/
\n\n\n# Adversarial Neural Networks\n
\n
\n\n# Adversarial Neural Networks (2)\n
\n
\n\n# Adversarial Neural Networks (3)\n
\n
\n\n# Adversarial Neural Networks (4)\n
\n\n
\n\n# Take home messages\n- Neural networks try to mimic how the brain works: hierarchical layers of non-linear functions. \n\n- Neural networks take time to train and overfit badly. \n\n- Neural networks need big data. \n\n- Neural networks are hard or impossible to interpret. \n\n- Backpropagation allows efficient computation of gradients.\n", "meta": {"hexsha": "b96993eb87731768c9f5df79f81c2ac8668e6435", "size": 31798, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "slides/unit-10-0_case_study_object_recognition_DL.ipynb", "max_stars_repo_name": "daniel-acuna/ist718", "max_stars_repo_head_hexsha": "0a83f373aa00dc9cd1ff2e8da74d0255f04c9728", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 13, "max_stars_repo_stars_event_min_datetime": "2018-09-17T14:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-31T19:08:07.000Z", "max_issues_repo_path": "slides/unit-10-0_case_study_object_recognition_DL.ipynb", "max_issues_repo_name": "wozhouwozhou/ist718", "max_issues_repo_head_hexsha": "565e9767f6f35f77f9c14f2a94b2d75a0a6e2c02", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-03-24T15:51:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-13T19:48:14.000Z", "max_forks_repo_path": "slides/unit-10-0_case_study_object_recognition_DL.ipynb", "max_forks_repo_name": "wozhouwozhou/ist718", "max_forks_repo_head_hexsha": "565e9767f6f35f77f9c14f2a94b2d75a0a6e2c02", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 9, "max_forks_repo_forks_event_min_datetime": "2018-09-25T13:35:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-04T15:29:42.000Z", "avg_line_length": 27.4120689655, "max_line_length": 256, "alphanum_fraction": 0.5330523932, "converted": true, "num_tokens": 4132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.3478862186402445}} {"text": "```python\n%load_ext cython\n%load_ext line_profiler\nfrom Cython.Compiler.Options import get_directive_defaults\n\nget_directive_defaults()['linetrace'] = True\nget_directive_defaults()['binding'] = True\n```\n\n\n```python\nimport numpy as np\nfrom pycalphad import CompiledModel, Model, Database, calculate, equilibrium\nfrom pycalphad.core.eqsolver import _solve_eq_at_conditions\nimport pycalphad.variables as v\n\n#dbf = Database('2016-08-10-AlGdMgand18RLPSO-for 3d plot.tdb')\ndbf = Database('alfe_sei.TDB')\n```\n\n\n```python\nimport pstats, cProfile\n\n#models = {name: CompiledModel(dbf, ['AL', 'FE', 'VA'], name) for name in dbf.phases.keys()}\n#cProfile.runctx(\"equilibrium(dbf, ['AL', 'FE', 'VA'], dbf.phases.keys(), {v.T: 1000, v.X('AL'): (0,1,0.01), v.P: 101325}, model=models)\", globals(), locals(), \"Profile.prof\")\n#s = pstats.Stats(\"Profile.prof\")\n#s.strip_dirs().sort_stats(\"tottime\").print_stats()\neq = equilibrium(dbf, ['AL', 'FE', 'VA'], dbf.phases.keys(), {v.T: 1000, v.X('AL'): 0.1, v.P: 101325}, verbose=True)\n```\n\n Calculation Backend: Compiled (autowrap)\n Components: AL FE VA\n Phases: AL13FE4 AL2FE AL5FE2 AL5FE4 B2_BCC BCC_A2 FCC_A1 HCP_A3 LIQUID [done]\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.11111111 0.88888889]), CompositionSet(B2_BCC, [ 0.05555556 0.94444444])])\n ('NEW_L_MULTIPLIERS', array([ -1317.94916933, -1317.94916933, 926.86058643,\n 839.90874505, -585.01538944, -27488.56710902,\n -126136.93871556, -43581.92654995]))\n ('old_driving_force', -52310.477710388084)\n (1.0, -52093.079553656855, 0.008332613323217497)\n (0.5, -52138.059520487157, 0.00061219243322951922)\n (0.25, -52208.399001067679, 0.00015304810830729654)\n (0.125, -52255.426669399792, 3.8262027076824134e-05)\n (0.0625, -52281.937570527996, 9.5655067691990947e-06)\n (0.03125, -52295.952030165521, 2.3913766922928348e-06)\n (0.015625, -52303.15068807346, 5.9784417308361704e-07)\n (0.0078125, -52306.798116369158, 1.4946104327784315e-07)\n (0.00390625, -52308.633887846801, 3.7365260815991341e-08)\n (0.001953125, -52309.554792122726, 9.3413152074672823e-09)\n ('alpha', 0.001953125)\n ('Phases', [CompositionSet(B2_BCC, [ 0.11120894 0.88879106]), CompositionSet(B2_BCC, [ 0.05565864 0.94434136])])\n ('step', array([ 5.00899178e-02, -5.00899178e-02, 5.00899178e-02,\n -5.00899178e-02, 7.42121503e-17, 1.05554115e-01,\n -1.05554115e-01, 1.99194365e-10, -1.99193343e-10,\n 1.24803672e-16, -9.11292225e-01, 9.11292225e-01]))\n ('Site fractions', array([ 1.11208943e-01, 8.88791057e-01, 1.11208943e-01,\n 8.88791057e-01, 1.00000000e+00, 1.11317271e-01,\n 8.88682729e-01, 1.38905149e-12, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.79822013, 0.20177987]))\n ('Chemical potentials', array([-126136.93871556, -43581.92654995]))\n ('Chem pot progress', array([ 10618.71418285, -654.24608267]))\n ('Energy progress', 0.92214709296968067)\n ('Driving force', -472.12702561312472)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.11120894 0.88879106]), CompositionSet(B2_BCC, [ 0.05565864 0.94434136])])\n ('NEW_L_MULTIPLIERS', array([ -7.26028573e+02, -7.26028573e+02, -2.01224678e+04,\n 7.69428768e+01, -3.65198328e+02, -6.30878081e+03,\n -1.28203582e+05, -4.40034466e+04]))\n ('old_driving_force', -52309.554776755118)\n (1.0, -52346.712806257339, 0.0020813328560732591)\n (0.5, -52342.011506009068, 0.00052033788467686914)\n (0.25, -52329.007552302959, 0.00013009030949162614)\n (0.125, -52320.060818765523, 3.2528999527325908e-05)\n ('alpha', 0.125)\n ('Phases', [CompositionSet(B2_BCC, [ 0.11009074 0.88990926]), CompositionSet(B2_BCC, [ 0.06138935 0.93861065])])\n ('step', array([ -8.94562605e-03, 8.94562605e-03, -8.94562605e-03,\n 8.94562605e-03, -7.96753940e-17, 9.16913510e-02,\n -9.16913510e-02, 4.68276131e-11, -4.68285868e-11,\n 2.49111011e-16, -3.79865562e-02, 3.79865562e-02]))\n ('Site fractions', array([ 1.10090740e-01, 8.89909260e-01, 1.10090740e-01,\n 8.89909260e-01, 1.00000000e+00, 1.22778690e-01,\n 8.77221310e-01, 7.24250313e-12, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.79347181, 0.20652819]))\n ('Chemical potentials', array([-128203.58194155, -44003.44662594]))\n ('Chem pot progress', array([-2066.643226 , -421.52007599]))\n ('Energy progress', -13.244201632223849)\n ('Driving force', 103.39933873210975)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.11009074 0.88990926]), CompositionSet(B2_BCC, [ 0.06138935 0.93861065])])\n ('NEW_L_MULTIPLIERS', array([ -6.39755776e+02, -6.39760095e+02, -1.71406449e+04,\n 1.08155935e+02, -5.52038110e+02, -9.17692813e+03,\n -1.28106899e+05, -4.40249732e+04]))\n ('old_driving_force', -52320.064664004902)\n (1.0, -52291.122003656776, 0.0095602135013234113)\n (0.5, -52329.33583412438, 0.002406317875094488)\n (0.25, -52328.312472462203, 0.00062191009347833948)\n (0.125, -52324.794722051192, 0.00017784121054453816)\n (0.0625, -52322.543584968953, 6.7840521046358404e-05)\n ('alpha', 0.0625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10971661 0.89028339]), CompositionSet(B2_BCC, [ 0.0650173 0.9349827])])\n ('step', array([ -5.98606931e-03, 5.98606931e-03, -5.98606931e-03,\n 5.98606931e-03, 1.76797323e-16, 1.16094517e-01,\n -1.16094517e-01, 2.85189861e-10, -2.85189934e-10,\n -3.53197597e-16, -1.49300588e-01, 1.49300588e-01]))\n ('Site fractions', array([ 1.09716610e-01, 8.90283390e-01, 1.09716610e-01,\n 8.90283390e-01, 1.00000000e+00, 1.30034598e-01,\n 8.69965402e-01, 2.50668694e-11, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.78414053, 0.21585947]))\n ('Chemical potentials', array([-128106.89894028, -44024.97320491]))\n ('Chem pot progress', array([ 96.68300127, -21.52657898]))\n ('Energy progress', -5.447981694029295)\n ('Driving force', 110.62219347970677)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10971661 0.89028339]), CompositionSet(B2_BCC, [ 0.0650173 0.9349827])])\n ('NEW_L_MULTIPLIERS', array([ -5.81459655e+02, -5.81461050e+02, -1.55077250e+04,\n 1.08364050e+02, -6.73308521e+02, -1.07679596e+04,\n -1.28074377e+05, -4.40265878e+04]))\n ('old_driving_force', -52322.545900815778)\n (1.0, -52255.710365193852, 0.013157379294169783)\n (0.5, -52319.169275632667, 0.0033232650840654548)\n (0.25, -52324.928628278991, 0.00087321659667027873)\n (0.125, -52324.312382877768, 0.00026494450738689945)\n (0.0625, -52323.516495220349, 0.00011499650134882966)\n (0.03125, -52323.045901149904, 7.8569507980685849e-05)\n ('alpha', 0.03125)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10955589 0.89044411]), CompositionSet(B2_BCC, [ 0.06689598 0.93310402])])\n ('step', array([ -5.14278046e-03, 5.14278046e-03, -5.14345083e-03,\n 5.14345083e-03, 4.03710960e-17, 1.20235615e-01,\n -1.20235615e-01, 1.05318594e-09, -1.05318592e-09,\n -4.49590900e-16, -2.01611908e-01, 2.01611908e-01]))\n ('Site fractions', array([ 1.09555899e-01, 8.90444101e-01, 1.09555878e-01,\n 8.90444122e-01, 1.00000000e+00, 1.33791961e-01,\n 8.66208039e-01, 5.79789301e-11, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.77784015, 0.22215985]))\n ('Chemical potentials', array([-128074.37686254, -44026.58775806]))\n ('Chem pot progress', array([ 32.52207774, -1.61455315]))\n ('Energy progress', -1.4017479652757174)\n ('Driving force', 108.3207673580182)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10955589 0.89044411]), CompositionSet(B2_BCC, [ 0.06689598 0.93310402])])\n ('NEW_L_MULTIPLIERS', array([ -5.39320576e+02, -5.39305210e+02, -1.43186916e+04,\n 1.09924867e+02, -7.59472461e+02, -1.19292764e+04,\n -1.28043564e+05, -4.40291388e+04]))\n ('old_driving_force', -52323.048522546102)\n (1.0, -52227.837869577212, 0.015934696593389086)\n (0.5, -52311.071481769315, 0.0040229589023373924)\n (0.25, -52321.607331325438, 0.0010548456680724572)\n (0.125, -52322.902239349009, 0.00031772795375495377)\n (0.0625, -52323.047114787616, 0.00013590382229966558)\n (0.03125, -52323.056656372682, 9.1675437998151033e-05)\n ('alpha', 0.03125)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10941292 0.89058708]), CompositionSet(B2_BCC, [ 0.06882656 0.93117344])])\n ('step', array([ -4.57558348e-03, 4.57558348e-03, -4.57438191e-03,\n 4.57438191e-03, -7.14331381e-16, 1.23557269e-01,\n -1.23557269e-01, 2.51974705e-09, -2.51974711e-09,\n -6.06628349e-16, -2.40148117e-01, 2.40148117e-01]))\n ('Site fractions', array([ 1.09412912e-01, 8.90587088e-01, 1.09412928e-01,\n 8.90587072e-01, 1.00000000e+00, 1.37653125e-01,\n 8.62346875e-01, 1.36721025e-10, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.77033553, 0.22966447]))\n ('Chemical potentials', array([-128043.56381835, -44029.13875383]))\n ('Chem pot progress', array([ 30.81304419, -2.55099577]))\n ('Energy progress', -1.1092210019487538)\n ('Driving force', 107.52460391060595)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.30788595887)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.307885958915)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.30788595887)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.307886016846)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.307886016846)\n (CompositionSet(AL13FE4, [ 0.72922501 0.27077499]), 'Driving Force: ', -39514.41005230768)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.30788595887)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.30788601683)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39567.30788601683)\n (CompositionSet(AL13FE4, [ 0.72922501 0.27077499]), 'Driving Force: ', -39514.410052307634)\n (CompositionSet(AL2FE, [ 0.66666667 0.33333333]), 'Driving Force: ', -31829.535393894257)\n (CompositionSet(AL5FE2, [ 0.71428571 0.28571429]), 'Driving Force: ', -36602.56215079661)\n (CompositionSet(AL5FE4, [ 0.12753142 0.87246858]), 'Driving Force: ', -5545.779722938925)\n (CompositionSet(AL5FE4, [ 0.12753143 0.87246857]), 'Driving Force: ', -5545.77972293894)\n (CompositionSet(AL5FE4, [ 0.12753141 0.87246859]), 'Driving Force: ', -5545.779722938954)\n (CompositionSet(AL5FE4, [ 0.12753142 0.87246858]), 'Driving Force: ', -5545.779722938947)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7587.750797026216)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7587.750797026216)\n (CompositionSet(AL5FE4, [ 0.12753142 0.87246858]), 'Driving Force: ', -5545.779722938918)\n (CompositionSet(AL5FE4, [ 0.12753142 0.87246858]), 'Driving Force: ', -5545.7797229389325)\n (CompositionSet(AL5FE4, [ 0.12753139 0.87246861]), 'Driving Force: ', -5545.779722939049)\n (CompositionSet(AL5FE4, [ 0.12753142 0.87246858]), 'Driving Force: ', -5545.779722938911)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1756.656230721048)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1756.656230721048)\n (CompositionSet(B2_BCC, [ 0.10292434 0.89707566]), 'Driving Force: ', -2.3166557039439795)\n (CompositionSet(B2_BCC, [ 0.09867017 0.90132983]), 'Driving Force: ', -228.7950136554282)\n (CompositionSet(B2_BCC, [ 0.09884968 0.90115032]), 'Driving Force: ', -339.88192094912665)\n (CompositionSet(B2_BCC, [ 0.09866954 0.90133046]), 'Driving Force: ', -228.7252744548532)\n (CompositionSet(B2_BCC, [ 0.09866994 0.90133006]), 'Driving Force: ', -228.92200816817058)\n (CompositionSet(B2_BCC, [ 0.10292434 0.89707566]), 'Driving Force: ', -2.3166557039294275)\n (CompositionSet(B2_BCC, [ 0.0986699 0.9013301]), 'Driving Force: ', -228.7253371691695)\n (CompositionSet(B2_BCC, [ 0.09867015 0.90132985]), 'Driving Force: ', -228.7953720836158)\n (CompositionSet(BCC_A2, [ 0.10292434 0.89707566]), 'Driving Force: ', -2.3166557039294275)\n (CompositionSet(BCC_A2, [ 0.10292427 0.89707573]), 'Driving Force: ', -2.316655704569712)\n (CompositionSet(BCC_A2, [ 0.10292434 0.89707566]), 'Driving Force: ', -2.3166557039294275)\n (CompositionSet(BCC_A2, [ 0.10292429 0.89707571]), 'Driving Force: ', -2.3166557042350178)\n (CompositionSet(BCC_A2, [ 0.10292433 0.89707567]), 'Driving Force: ', -2.3166557039585314)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1756.656230721048)\n (CompositionSet(BCC_A2, [ 0.10292434 0.89707566]), 'Driving Force: ', -2.3166557039075997)\n (CompositionSet(BCC_A2, [ 0.10292433 0.89707567]), 'Driving Force: ', -2.3166557039075997)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1756.656230721048)\n (CompositionSet(BCC_A2, [ 0.10292434 0.89707566]), 'Driving Force: ', -2.3166557039221516)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2094.4019719191056)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2094.4019719191056)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2094.4019719191056)\n (CompositionSet(FCC_A1, [ 0.071525 0.928475]), 'Driving Force: ', -871.2819783434752)\n (CompositionSet(FCC_A1, [ 0.07152502 0.92847498]), 'Driving Force: ', -871.2819783433224)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2094.4019719087228)\n (CompositionSet(FCC_A1, [ 0.07152503 0.92847497]), 'Driving Force: ', -871.2819783433224)\n (CompositionSet(FCC_A1, [ 0.07152503 0.92847497]), 'Driving Force: ', -871.2819783433151)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2094.4019719087228)\n (CompositionSet(FCC_A1, [ 0.07152503 0.92847497]), 'Driving Force: ', -871.2819783433079)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.089275671242)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.089275671271)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.0892756712565)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.089275671249)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4160.022226193134)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4160.022226193134)\n (CompositionSet(HCP_A3, [ 0.10814371 0.89185629]), 'Driving Force: ', -2192.089275671271)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.089275671242)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.0892756712565)\n (CompositionSet(HCP_A3, [ 0.10814372 0.89185628]), 'Driving Force: ', -2192.089275671249)\n (CompositionSet(LIQUID, [ 0.08480137 0.91519863]), 'Driving Force: ', -6836.300694103076)\n (CompositionSet(LIQUID, [ 0.08480138 0.91519862]), 'Driving Force: ', -6836.300694103047)\n (CompositionSet(LIQUID, [ 0.08480138 0.91519862]), 'Driving Force: ', -6836.300694103069)\n (CompositionSet(LIQUID, [ 0.08480138 0.91519862]), 'Driving Force: ', -6836.300694103054)\n (CompositionSet(LIQUID, [ 0.08480138 0.91519862]), 'Driving Force: ', -6836.300694103047)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -8056.785637032233)\n (CompositionSet(LIQUID, [ 0.08480133 0.91519867]), 'Driving Force: ', -6836.300694103265)\n (CompositionSet(LIQUID, [ 0.08480138 0.91519862]), 'Driving Force: ', -6836.300694103062)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -8056.785637032233)\n (CompositionSet(LIQUID, [ 0.08480138 0.91519862]), 'Driving Force: ', -6836.300694103062)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10941292 0.89058708]), CompositionSet(B2_BCC, [ 0.06882656 0.93117344])])\n ('NEW_L_MULTIPLIERS', array([ -4.85982245e+02, -4.85982245e+02, -1.28040695e+04,\n 1.12621534e+02, -8.68038038e+02, -1.34025529e+04,\n -1.27999365e+05, -4.40331773e+04]))\n ('old_driving_force', -52323.061078589744)\n (1.0, -52189.921632966725, 0.0196274237172539)\n (0.5, -52300.232462485765, 0.0049526936483126338)\n (0.25, -52316.931859487457, 0.0012954705608271277)\n (0.125, -52320.587330808339, 0.00038689450383067037)\n (0.0625, -52321.878493580625, 0.00016261534701889069)\n (0.03125, -52322.471518834071, 0.00010797798653472412)\n (0.015625, -52322.765240789813, 9.503486077289125e-05)\n ('alpha', 0.015625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10935216 0.89064784]), CompositionSet(B2_BCC, [ 0.0698242 0.9301758])])\n ('step', array([ -3.88830420e-03, 3.88830420e-03, -3.88831455e-03,\n 3.88831455e-03, 1.31766332e-17, 1.27697993e-01,\n -1.27697993e-01, 6.18986563e-09, -6.18986555e-09,\n -6.28370667e-16, -2.89757949e-01, 2.89757949e-01]))\n ('Site fractions', array([ 1.09352157e-01, 8.90647843e-01, 1.09352173e-01,\n 8.90647827e-01, 1.00000000e+00, 1.39648406e-01,\n 8.60351594e-01, 2.33437676e-10, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.76580806, 0.23419194]))\n ('Chemical potentials', array([-127999.36460878, -44033.17729647]))\n ('Chem pot progress', array([ 44.19920957, -4.03854264]))\n ('Energy progress', 0.013759877969278023)\n ('Driving force', 107.03078691552946)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10935216 0.89064784]), CompositionSet(B2_BCC, [ 0.0698242 0.9301758])])\n ('NEW_L_MULTIPLIERS', array([ -4.55247086e+02, -4.55219921e+02, -1.19776953e+04,\n 1.13024749e+02, -9.29371760e+02, -1.42098279e+04,\n -1.27977861e+05, -4.40351194e+04]))\n ('old_driving_force', -52322.767468923957)\n (1.0, -52168.54028066375, 0.021615803522220284)\n (0.5, -52294.033119170526, 0.0054514683109413847)\n (0.25, -52314.143199265847, 0.0014222638657183095)\n (0.125, -52319.06946631868, 0.00042090243321102339)\n (0.0625, -52320.966862237976, 0.00017353191448321592)\n (0.03125, -52321.865936600028, 0.00011317420450096538)\n (0.015625, -52322.31471669671, 9.8827236855170142e-05)\n ('alpha', 0.015625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10929594 0.89070406]), CompositionSet(B2_BCC, [ 0.07083583 0.92916417])])\n ('step', array([ -3.59933363e-03, 3.59933363e-03, -3.59701969e-03,\n 3.59701969e-03, 1.14855174e-16, 1.29488808e-01,\n -1.29488808e-01, 1.06878676e-08, -1.06878656e-08,\n 4.86139654e-16, -3.16286006e-01, 3.16286006e-01]))\n ('Site fractions', array([ 1.09295917e-01, 8.90704083e-01, 1.09295970e-01,\n 8.90704030e-01, 1.00000000e+00, 1.41671669e-01,\n 8.58328331e-01, 4.00435606e-10, 1.00000000e+00,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.76086609, 0.23913391]))\n ('Chemical potentials', array([-127977.86128823, -44035.11941614]))\n ('Chem pot progress', array([ 21.50332055, -1.94211967]))\n ('Energy progress', 0.13440978069411358)\n ('Driving force', 107.07888665240898)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10929594 0.89070406]), CompositionSet(B2_BCC, [ 0.07083583 0.92916417])])\n ('NEW_L_MULTIPLIERS', array([ -4.18319429e+02, -4.18315037e+02, -1.09420640e+04,\n 1.14483156e+02, -1.00427041e+03, -1.52188090e+04,\n -1.27945460e+05, -4.40382849e+04]))\n ('old_driving_force', -52322.318231693644)\n (1.0, -52140.452153570346, 0.024250319654446156)\n (0.5, -52286.171534505469, 0.0061119935320389923)\n (0.25, -52310.609861841629, 0.0015897654060442745)\n (0.125, -52317.106359203783, 0.00046538507684890096)\n (0.0625, -52319.751372764593, 0.00018737834570170531)\n (0.03125, -52321.029164171923, 0.00011942083849081353)\n (0.015625, -52321.67034721432, 0.00010320354947612742)\n (0.0078125, -52321.99320811504, 9.9535271116502066e-05)\n ('alpha', 0.0078125)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10927115 0.89072885]), CompositionSet(B2_BCC, [ 0.07135175 0.92864825])])\n ('step', array([ -3.17369530e-03, 3.17369530e-03, -3.17372367e-03,\n 3.17372367e-03, -7.71036701e-16, 1.32074250e-01,\n -1.32074250e-01, 1.86910345e-08, -1.86910340e-08,\n 3.70789336e-16, -3.50383240e-01, 3.50383240e-01]))\n ('Site fractions', array([ 1.09271123e-01, 8.90728877e-01, 1.09271175e-01,\n 8.90728825e-01, 1.00000000e+00, 1.42703499e-01,\n 8.57296501e-01, 5.46459313e-10, 9.99999999e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.75812872, 0.24187128]))\n ('Chemical potentials', array([-127945.45970272, -44038.28491767]))\n ('Chem pot progress', array([ 32.40158552, -3.16550153]))\n ('Energy progress', 0.2656144240972935)\n ('Driving force', 107.00918805721449)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10927115 0.89072885]), CompositionSet(B2_BCC, [ 0.07135175 0.92864825])])\n ('NEW_L_MULTIPLIERS', array([ -3.99484776e+02, -3.99496001e+02, -1.04524076e+04,\n 1.14310746e+02, -1.04106113e+03, -1.56973130e+04,\n -1.27932353e+05, -4.40395444e+04]))\n ('old_driving_force', -52321.994638061245)\n (1.0, -52127.195727154118, 0.025440796179782899)\n (0.5, -52282.342004945, 0.0064099666805041977)\n (0.25, -52308.841367864836, 0.0016647012145740714)\n (0.125, -52316.081252778153, 0.00048460580253617547)\n (0.0625, -52319.07505901267, 0.00019269242674901932)\n (0.03125, -52320.527805289174, 0.00012126932141343083)\n (0.015625, -52321.257404363721, 0.00010419116438509235)\n (0.0078125, -52321.62480874655, 0.00010031043478087032)\n (0.00390625, -52321.809387951136, 9.953465720613508e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.1092593 0.8907407]), CompositionSet(B2_BCC, [ 0.07161143 0.92838857])])\n ('step', array([ -3.03429759e-03, 3.03429759e-03, -3.03471572e-03,\n 3.03471572e-03, 4.46711096e-16, 1.32955822e-01,\n -1.32955822e-01, 2.55732198e-08, -2.55732197e-08,\n 2.77586863e-16, -3.65989163e-01, 3.65989163e-01]))\n ('Site fractions', array([ 1.09259270e-01, 8.90740730e-01, 1.09259321e-01,\n 8.90740679e-01, 1.00000000e+00, 1.43222858e-01,\n 8.56777142e-01, 6.46354703e-10, 9.99999999e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.75669907, 0.24330093]))\n ('Chemical potentials', array([-127932.35300797, -44039.544449 ]))\n ('Chem pot progress', array([ 13.10669475, -1.25953133]))\n ('Energy progress', 0.1853016127643059)\n ('Driving force', 107.01591694747185)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.1092593 0.8907407]), CompositionSet(B2_BCC, [ 0.07161143 0.92838857])])\n ('NEW_L_MULTIPLIERS', array([ -3.89280459e+02, -3.89281747e+02, -1.01800850e+04,\n 1.13954959e+02, -1.06182293e+03, -1.59623444e+04,\n -1.27924387e+05, -4.40403322e+04]))\n ('old_driving_force', -52321.810259204241)\n (1.0, -52119.672652615249, 0.02612151423489173)\n (0.5, -52280.206607112385, 0.0065801458873261387)\n (0.25, -52307.857678694811, 0.0017072456325852858)\n (0.125, -52315.508369923904, 0.00049524148497548381)\n (0.0625, -52318.694991851102, 0.00019535090611078054)\n (0.03125, -52320.24468655188, 0.00012193349041356161)\n (0.015625, -52321.02336394888, 0.00010435675099851327)\n (0.0078125, -52321.415517705653, 0.00010035137339958755)\n (0.00390625, -52321.612531585866, 9.9544432627163282e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10924778 0.89075222]), CompositionSet(B2_BCC, [ 0.07187217 0.92812783])])\n ('step', array([ -2.94721693e-03, 2.94721693e-03, -2.94686277e-03,\n 2.94686277e-03, -1.60266759e-16, 1.33500263e-01,\n -1.33500263e-01, 3.02989110e-08, -3.02989101e-08,\n -1.69248665e-16, -3.74785778e-01, 3.74785778e-01]))\n ('Site fractions', array([ 1.09247757e-01, 8.90752243e-01, 1.09247810e-01,\n 8.90752190e-01, 1.00000000e+00, 1.43744343e-01,\n 8.56255657e-01, 7.64709824e-10, 9.99999999e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.75523507, 0.24476493]))\n ('Chemical potentials', array([-127924.38749933, -44040.33220406]))\n ('Chem pot progress', array([ 7.96550864, -0.78775506]))\n ('Energy progress', 0.1969076164168655)\n ('Driving force', 107.12520200275321)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.65260551605)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.65260551605)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.652605516094)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.652605574025)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.652605574025)\n (CompositionSet(AL13FE4, [ 0.72923187 0.27076813]), 'Driving Force: ', -39430.53415904238)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.65260551605)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.65260557401)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39483.65260557401)\n (CompositionSet(AL13FE4, [ 0.72923187 0.27076813]), 'Driving Force: ', -39430.53415904238)\n (CompositionSet(AL2FE, [ 0.66666667 0.33333333]), 'Driving Force: ', -31753.815664623326)\n (CompositionSet(AL5FE2, [ 0.71428571 0.28571429]), 'Driving Force: ', -36520.63433727558)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972092)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972099)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972114)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972099)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7598.944247256637)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7598.944247256637)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972114)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972121)\n (CompositionSet(AL5FE4, [ 0.12819742 0.87180258]), 'Driving Force: ', -5540.30352297215)\n (CompositionSet(AL5FE4, [ 0.12819745 0.87180255]), 'Driving Force: ', -5540.303522972092)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1767.849680951469)\n (CompositionSet(B2_BCC, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.0595022535926546)\n (CompositionSet(B2_BCC, [ 0.10342117 0.89657883]), 'Driving Force: ', -0.059502253658138216)\n (CompositionSet(B2_BCC, [ 0.09925483 0.90074517]), 'Driving Force: ', -227.11314087044593)\n (CompositionSet(B2_BCC, [ 0.09944469 0.90055531]), 'Driving Force: ', -338.14958250161)\n (CompositionSet(B2_BCC, [ 0.09925501 0.90074499]), 'Driving Force: ', -227.0361458865882)\n (CompositionSet(B2_BCC, [ 0.09944471 0.90055529]), 'Driving Force: ', -338.14958250152995)\n (CompositionSet(B2_BCC, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.0595022535926546)\n (CompositionSet(B2_BCC, [ 0.09925465 0.90074535]), 'Driving Force: ', -227.0362373766402)\n (CompositionSet(B2_BCC, [ 0.09925533 0.90074467]), 'Driving Force: ', -227.11371890397277)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.059502253599930555)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.05950225360720651)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.05950225360720651)\n (CompositionSet(BCC_A2, [ 0.10342117 0.89657883]), 'Driving Force: ', -0.05950225366541417)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1767.849680951469)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1767.849680951469)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.05950225360720651)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.05950225358537864)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.05950225361448247)\n (CompositionSet(BCC_A2, [ 0.10342119 0.89657881]), 'Driving Force: ', -0.05950225362175843)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2105.595422149534)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2105.595422149534)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2105.595422149534)\n (CompositionSet(FCC_A1, [ 0.07189187 0.92810813]), 'Driving Force: ', -873.1268209939008)\n (CompositionSet(FCC_A1, [ 0.07189189 0.92810811]), 'Driving Force: ', -873.1268209938207)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2105.595422139144)\n (CompositionSet(FCC_A1, [ 0.07189189 0.92810811]), 'Driving Force: ', -873.1268209938207)\n (CompositionSet(FCC_A1, [ 0.07189189 0.92810811]), 'Driving Force: ', -873.1268209938353)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2105.595422139144)\n (CompositionSet(FCC_A1, [ 0.07189189 0.92810811]), 'Driving Force: ', -873.1268209938353)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.151356121445)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.1513561214524)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.1513561214524)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.151356121445)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4171.215676423555)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4171.215676423555)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.151356121416)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.1513561214524)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.151356121445)\n (CompositionSet(HCP_A3, [ 0.10864545 0.89135455]), 'Driving Force: ', -2189.151356121438)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317929)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317965)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317958)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317965)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317929)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -8067.9790872626545)\n (CompositionSet(LIQUID, [ 0.08534058 0.91465942]), 'Driving Force: ', -6836.403473318052)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317965)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -8067.9790872626545)\n (CompositionSet(LIQUID, [ 0.08534061 0.91465939]), 'Driving Force: ', -6836.403473317929)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10924778 0.89075222]), CompositionSet(B2_BCC, [ 0.07187217 0.92812783])])\n ('NEW_L_MULTIPLIERS', array([ -3.78147000e+02, -3.78136572e+02, -9.87227225e+03,\n 1.14552250e+02, -1.08397141e+03, -1.62611403e+04,\n -1.27913907e+05, -4.40413986e+04]))\n ('old_driving_force', -52321.613681059331)\n (1.0, -52111.002269341341, 0.026917282387877828)\n (0.5, -52277.803409466913, 0.0067790928132832606)\n (0.25, -52306.760090872311, 0.0017569884737127506)\n (0.125, -52314.872204887695, 0.00050768391585942485)\n (0.0625, -52318.276255233352, 0.0001984685399155639)\n (0.03125, -52319.935790442694, 0.00012272007768954207)\n (0.015625, -52320.770235459095, 0.00010456065301278628)\n (0.0078125, -52321.190556288253, 0.00010040964228363869)\n (0.00390625, -52321.401733494095, 9.9566312321330841e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10923673 0.89076327]), CompositionSet(B2_BCC, [ 0.07213429 0.92786571])])\n ('step', array([ -2.82999152e-03, 2.82999152e-03, -2.82965248e-03,\n 2.82965248e-03, 9.07149654e-17, 1.34202068e-01,\n -1.34202068e-01, 3.59673816e-08, -3.59673814e-08,\n 3.52247801e-16, -3.84912714e-01, 3.84912714e-01]))\n ('Site fractions', array([ 1.09236703e-01, 8.90763297e-01, 1.09236756e-01,\n 8.90763244e-01, 1.00000000e+00, 1.44268570e-01,\n 8.55731430e-01, 9.05207408e-10, 9.99999999e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.7537315, 0.2462685]))\n ('Chemical potentials', array([-127913.90657088, -44041.39861616]))\n ('Chem pot progress', array([ 10.48092845, -1.0664121 ]))\n ('Energy progress', 0.21011246041598497)\n ('Driving force', 107.24767813937069)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10923673 0.89076327]), CompositionSet(B2_BCC, [ 0.07213429 0.92786571])])\n ('NEW_L_MULTIPLIERS', array([ -3.66898015e+02, -3.66923879e+02, -9.57093748e+03,\n 1.14811919e+02, -1.10612628e+03, -1.65565486e+04,\n -1.27905647e+05, -4.40422149e+04]))\n ('old_driving_force', -52321.402637135267)\n (1.0, -52102.424649256776, 0.027690145414026257)\n (0.5, -52275.415393211508, 0.0069723195096674795)\n (0.25, -52305.667313562793, 0.0018053088226178682)\n (0.125, -52314.233699380871, 0.00051977904537547914)\n (0.0625, -52317.849915433806, 0.00020150804832475)\n (0.03125, -52319.616082613975, 0.00012349602269223769)\n (0.015625, -52320.504526793382, 0.0001047708780990142)\n (0.0078125, -52320.952086899502, 0.00010047852285821612)\n (0.00390625, -52321.176952324204, 9.9599899501812139e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10922607 0.89077393]), CompositionSet(B2_BCC, [ 0.07239764 0.92760236])])\n ('step', array([ -2.72856138e-03, 2.72856138e-03, -2.73034466e-03,\n 2.73034466e-03, 7.44430166e-16, 1.34838909e-01,\n -1.34838909e-01, 4.26770103e-08, -4.26770100e-08,\n 1.49361297e-16, -3.94733689e-01, 3.94733689e-01]))\n ('Site fractions', array([ 1.09226044e-01, 8.90773956e-01, 1.09226091e-01,\n 8.90773909e-01, 1.00000000e+00, 1.44795285e-01,\n 8.55204715e-01, 1.07191448e-09, 9.99999999e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.75218957, 0.24781043]))\n ('Chemical potentials', array([-127905.64708103, -44042.2148985 ]))\n ('Chem pot progress', array([ 8.25948985, -0.81628234]))\n ('Energy progress', 0.22286807483033044)\n ('Driving force', 107.38116443167382)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10922607 0.89077393]), CompositionSet(B2_BCC, [ 0.07239764 0.92760236])])\n ('NEW_L_MULTIPLIERS', array([ -3.55006321e+02, -3.55009895e+02, -9.24561391e+03,\n 1.15161772e+02, -1.12989100e+03, -1.68725648e+04,\n -1.27895723e+05, -4.40432174e+04]))\n ('old_driving_force', -52321.17804062432)\n (1.0, -52093.0354131657, 0.028540190573183244)\n (0.5, -52272.836706777605, 0.0071848475930470501)\n (0.25, -52304.492481358342, 0.0018584618354504645)\n (0.125, -52313.547794893719, 0.00053309038977045198)\n (0.0625, -52317.392607744638, 0.00020486002520947455)\n (0.03125, -52319.273916008606, 0.00012435868249904836)\n (0.015625, -52320.220753277055, 0.00010501147103625375)\n (0.0078125, -52320.697792801737, 0.00010056373027789167)\n (0.00390625, -52320.937478358646, 9.9646326142122099e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10921586 0.89078414]), CompositionSet(B2_BCC, [ 0.07266241 0.92733759])])\n ('step', array([ -2.61243991e-03, 2.61243991e-03, -2.61246134e-03,\n 2.61246134e-03, -8.50427079e-16, 1.35563116e-01,\n -1.35563116e-01, 5.07008464e-08, -5.07008458e-08,\n 4.75479702e-19, -4.05434794e-01, 4.05434794e-01]))\n ('Site fractions', array([ 1.09215839e-01, 8.90784161e-01, 1.09215886e-01,\n 8.90784114e-01, 1.00000000e+00, 1.45324828e-01,\n 8.54675172e-01, 1.26996466e-09, 9.99999999e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.75060584, 0.24939416]))\n ('Chemical potentials', array([-127895.72283491, -44043.2173714 ]))\n ('Chem pot progress', array([ 9.92424611, -1.00247289]))\n ('Energy progress', 0.23666927556041628)\n ('Driving force', 107.53043938835617)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10921586 0.89078414]), CompositionSet(B2_BCC, [ 0.07266241 0.92733759])])\n ('NEW_L_MULTIPLIERS', array([ -3.42863090e+02, -3.42857339e+02, -8.91922758e+03,\n 1.15341465e+02, -1.15394145e+03, -1.71910305e+04,\n -1.27886722e+05, -4.40441188e+04]))\n ('old_driving_force', -52320.938465098196)\n (1.0, -52083.520948930047, 0.029391851021015492)\n (0.5, -52270.222664361958, 0.0073977859183252948)\n (0.25, -52303.300452979456, 0.0019117254334205525)\n (0.125, -52312.84771476069, 0.0005464382075776042)\n (0.0625, -52316.921191377507, 0.00020823034880901314)\n (0.03125, -52318.917321615962, 0.00012523535796293839)\n (0.015625, -52319.922305241322, 0.0001052650971744562)\n (0.0078125, -52320.428679140983, 0.00010066177543877064)\n (0.00390625, -52320.683106903038, 9.9705566735552864e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10920608 0.89079392]), CompositionSet(B2_BCC, [ 0.07292854 0.92707146])])\n ('step', array([ -2.50458412e-03, 2.50458412e-03, -2.50428242e-03,\n 2.50428242e-03, -2.63397379e-16, 1.36256964e-01,\n -1.36256964e-01, 6.02297110e-08, -6.02297123e-08,\n -3.02646885e-16, -4.16120987e-01, 4.16120987e-01]))\n ('Site fractions', array([ 1.09206056e-01, 8.90793944e-01, 1.09206103e-01,\n 8.90793897e-01, 1.00000000e+00, 1.45857082e-01,\n 8.54142918e-01, 1.50523697e-09, 9.99999998e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.74898037, 0.25101963]))\n ('Chemical potentials', array([-127886.72182162, -44044.11877584]))\n ('Chem pot progress', array([ 9.00101329, -0.90140444]))\n ('Energy progress', 0.2503913096006727)\n ('Driving force', 107.69597351203993)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10920608 0.89079392]), CompositionSet(B2_BCC, [ 0.07292854 0.92707146])])\n ('NEW_L_MULTIPLIERS', array([ -3.30039916e+02, -3.30039916e+02, -8.57052263e+03,\n 1.15584520e+02, -1.17952620e+03, -1.75305990e+04,\n -1.27875743e+05, -4.40452429e+04]))\n ('old_driving_force', -52320.684313600941)\n (1.0, -52073.273186267885, 0.030312362397670156)\n (0.5, -52267.43247014995, 0.0076279433827851073)\n (0.25, -52302.03031662896, 0.0019693018249060668)\n (0.125, -52312.10141929848, 0.00056087303335716765)\n (0.0625, -52316.418872168142, 0.00021188163443042196)\n (0.03125, -52318.53779244591, 0.00012619168417893345)\n (0.015625, -52319.605044331503, 0.00010554814635632681)\n (0.0078125, -52320.142855594873, 0.0001007767367705581)\n (0.00390625, -52320.413088517234, 9.9778621809210044e-05)\n ('alpha', 0.00390625)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10919678 0.89080322]), CompositionSet(B2_BCC, [ 0.07319614 0.92680386])])\n ('step', array([ -2.38117627e-03, 2.38117627e-03, -2.38119667e-03,\n 2.38119667e-03, -2.32411991e-16, 1.37012752e-01,\n -1.37012752e-01, 7.16279874e-08, -7.16279875e-08,\n 2.49977290e-16, -4.27611644e-01, 4.27611644e-01]))\n ('Site fractions', array([ 1.09196754e-01, 8.90803246e-01, 1.09196802e-01,\n 8.90803198e-01, 1.00000000e+00, 1.46392288e-01,\n 8.53607712e-01, 1.78503380e-09, 9.99999998e-01,\n 1.00000000e+00]))\n ('Phase fractions', array([ 0.74731001, 0.25268999]))\n ('Chemical potentials', array([-127875.74335876, -44045.24292615]))\n ('Chem pot progress', array([ 10.97846286, -1.12415031]))\n ('Energy progress', 0.2651008403117885)\n ('Driving force', 107.87988089449937)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.600224632115)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.60022463213)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.60022463216)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.600224690104)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.600224690104)\n (CompositionSet(AL13FE4, [ 0.7292347 0.2707653]), 'Driving Force: ', -39396.39089271358)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.600224632115)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.60022469009)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -39449.60022469009)\n (CompositionSet(AL13FE4, [ 0.7292347 0.2707653]), 'Driving Force: ', -39396.39089271358)\n (CompositionSet(AL2FE, [ 0.66666667 0.33333333]), 'Driving Force: ', -31723.02314494425)\n (CompositionSet(AL5FE2, [ 0.71428571 0.28571429]), 'Driving Force: ', -36487.29158604168)\n (CompositionSet(AL5FE4, [ 0.12847122 0.87152878]), 'Driving Force: ', -5538.34131778108)\n (CompositionSet(AL5FE4, [ 0.12847122 0.87152878]), 'Driving Force: ', -5538.34131778108)\n (CompositionSet(AL5FE4, [ 0.12847123 0.87152877]), 'Driving Force: ', -5538.341317781094)\n (CompositionSet(AL5FE4, [ 0.12847123 0.87152877]), 'Driving Force: ', -5538.341317781065)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7603.854969344786)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7603.854969344786)\n (CompositionSet(AL5FE4, [ 0.12847122 0.87152878]), 'Driving Force: ', -5538.341317781087)\n (CompositionSet(AL5FE4, [ 0.12847122 0.87152878]), 'Driving Force: ', -5538.34131778108)\n (CompositionSet(AL5FE4, [ 0.12847119 0.87152881]), 'Driving Force: ', -5538.341317781153)\n (CompositionSet(AL5FE4, [ 0.12847122 0.87152878]), 'Driving Force: ', -5538.341317781073)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1772.7604030396178)\n (CompositionSet(B2_BCC, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271055754)\n (CompositionSet(B2_BCC, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271055754)\n (CompositionSet(B2_BCC, [ 0.09949563 0.90050437]), 'Driving Force: ', -226.71363863157603)\n (CompositionSet(B2_BCC, [ 0.09968937 0.90031063]), 'Driving Force: ', -337.72800485336484)\n (CompositionSet(B2_BCC, [ 0.09949564 0.90050436]), 'Driving Force: ', -226.63287041748845)\n (CompositionSet(B2_BCC, [ 0.09949591 0.90050409]), 'Driving Force: ', -226.83775529232662)\n (CompositionSet(B2_BCC, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525270837476)\n (CompositionSet(B2_BCC, [ 0.09949519 0.90050481]), 'Driving Force: ', -226.6325480345913)\n (CompositionSet(B2_BCC, [ 0.09949566 0.90050434]), 'Driving Force: ', -226.7132296494965)\n (CompositionSet(BCC_A2, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271055754)\n (CompositionSet(BCC_A2, [ 0.1036254 0.8963746]), 'Driving Force: ', 0.5739525267854333)\n (CompositionSet(BCC_A2, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271128514)\n (CompositionSet(BCC_A2, [ 0.10362542 0.89637458]), 'Driving Force: ', 0.5739525269673322)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1772.7604030396178)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1772.7604030396178)\n (CompositionSet(BCC_A2, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525270982995)\n (CompositionSet(BCC_A2, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271055754)\n (CompositionSet(BCC_A2, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271055754)\n (CompositionSet(BCC_A2, [ 0.10362545 0.89637455]), 'Driving Force: ', 0.5739525271201273)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2110.50614423769)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2110.50614423769)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2110.50614423769)\n (CompositionSet(FCC_A1, [ 0.07204279 0.92795721]), 'Driving Force: ', -874.1833422214768)\n (CompositionSet(FCC_A1, [ 0.0720428 0.9279572]), 'Driving Force: ', -874.1833422214331)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2110.5061442272927)\n (CompositionSet(FCC_A1, [ 0.0720428 0.9279572]), 'Driving Force: ', -874.1833422214404)\n (CompositionSet(FCC_A1, [ 0.0720428 0.9279572]), 'Driving Force: ', -874.183342221455)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2110.5061442272927)\n (CompositionSet(FCC_A1, [ 0.0720428 0.9279572]), 'Driving Force: ', -874.1833422214404)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.2380620572803)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.238062057302)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.2380620573094)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.238062057302)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4176.126398511704)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4176.126398511704)\n (CompositionSet(HCP_A3, [ 0.10885175 0.89114825]), 'Driving Force: ', -2188.2380620573094)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.238062057273)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.238062057273)\n (CompositionSet(HCP_A3, [ 0.10885176 0.89114824]), 'Driving Force: ', -2188.238062057295)\n (CompositionSet(LIQUID, [ 0.08556252 0.91443748]), 'Driving Force: ', -6836.73784974483)\n (CompositionSet(LIQUID, [ 0.08556251 0.91443749]), 'Driving Force: ', -6836.737849744859)\n (CompositionSet(LIQUID, [ 0.08556252 0.91443748]), 'Driving Force: ', -6836.737849744852)\n (CompositionSet(LIQUID, [ 0.08556251 0.91443749]), 'Driving Force: ', -6836.73784974483)\n (CompositionSet(LIQUID, [ 0.08556251 0.91443749]), 'Driving Force: ', -6836.737849744859)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -8072.889809350803)\n (CompositionSet(LIQUID, [ 0.08556249 0.91443751]), 'Driving Force: ', -6836.7378497449245)\n (CompositionSet(LIQUID, [ 0.08556251 0.91443749]), 'Driving Force: ', -6836.737849744844)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -8072.889809350803)\n (CompositionSet(LIQUID, [ 0.08556251 0.91443749]), 'Driving Force: ', -6836.737849744852)\n Removing CompositionSet(B2_BCC, [ 0.07319614 0.92680386]) to obey Gibbs phase rule\n Adding CompositionSet(BCC_A2, [ 0.10362545 0.89637455]) Driving force: 0.5739525271201273\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10919678 0.89080322]), CompositionSet(BCC_A2, [ 0.10362545 0.89637455])])\n ('NEW_L_MULTIPLIERS', array([ -264.89826622, -264.8945206 , -9642.67599985,\n -1297.1737685 , -16825.70455522, -128999.77089141,\n -43915.94010308]))\n ('old_driving_force', -52416.076431590118)\n (1.0, 5876.1602062075326, 0.56873751651891269)\n (0.5, -23272.24389876474, 0.40079633804275228)\n (0.25, -47965.637436633166, 0.25299707788350401)\n (0.125, -51828.893596589245, 0.22432627929229476)\n ('alpha', 0.125)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10824675 0.89175325]), CompositionSet(BCC_A2, [ 0.34788253 0.65211749])])\n ('step', array([ -7.60119960e-03, 7.60119960e-03, -7.59926744e-03,\n 7.59926744e-03, 2.67037722e-16, 1.95405662e+00,\n -1.95405649e+00, -1.02804264e-08, -3.78586494e-01,\n 6.31276481e-01]))\n ('Site fractions', array([ 0.1082466 , 0.8917534 , 0.10824689, 0.89175311, 1. ,\n 0.34788253, 0.65211749, 1. ]))\n ('Phase fractions', array([ 0.6999867 , 0.07890956]))\n ('Chemical potentials', array([-128999.77089141, -43915.94010308]))\n ('Chem pot progress', array([-1124.02753265, 129.30282307]))\n ('Energy progress', 9935.676250522549)\n ('Driving force', 595.42958619897399)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10824675 0.89175325]), CompositionSet(BCC_A2, [ 0.34788253 0.65211749])])\n ('NEW_L_MULTIPLIERS', array([ -8.84341717e+02, -8.84341716e+02, -2.54657390e+04,\n 1.80261112e+01, -2.09457042e+03, -1.28487946e+05,\n -4.39980146e+04]))\n ('old_driving_force', -51848.954437831679)\n (1.0, -52355.875558352353, 0.0022974278501212975)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.09752271 0.90247729]), CompositionSet(BCC_A2, [ 0.22224622 0.77775378])])\n ('step', array([ -1.07238439e-02, 1.07238439e-02, -1.07242408e-02,\n 1.07242408e-02, 1.27170704e-16, -1.25636308e-01,\n 1.25636292e-01, 1.28505340e-09, 2.61730853e-01,\n -4.06271147e-02]))\n ('Site fractions', array([ 0.09752276, 0.90247724, 0.09752265, 0.90247735, 1. ,\n 0.22224622, 0.77775378, 1. ]))\n ('Phase fractions', array([ 0.96171755, 0.03828245]))\n ('Chemical potentials', array([-128487.94575801, -43998.01457606]))\n ('Chem pot progress', array([ 511.8251334 , -82.07447298]))\n ('Energy progress', -10156.883771212197)\n ('Driving force', 91.132135906940675)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.09752271 0.90247729]), CompositionSet(BCC_A2, [ 0.22224622 0.77775378])])\n ('NEW_L_MULTIPLIERS', array([ -9.01547626e+02, -9.01545100e+02, -2.59756190e+04,\n -1.29560595e+01, -6.12337466e+02, -1.28704691e+05,\n -4.39536829e+04]))\n ('old_driving_force', -52355.275752664253)\n (1.0, -52418.837388535183, 0.0012917873214325915)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10019264 0.89980736]), CompositionSet(BCC_A2, [ 0.15932106 0.84067894])])\n ('step', array([ 2.66962124e-03, -2.66962124e-03, 2.67025267e-03,\n -2.67025267e-03, 2.11869349e-16, -6.29251558e-02,\n 6.29251558e-02, -3.30891085e-17, 1.96933526e-02,\n -1.96933531e-02]))\n ('Site fractions', array([ 0.10019238, 0.89980762, 0.10019291, 0.89980709, 1. ,\n 0.15932106, 0.84067894, 1. ]))\n ('Phase fractions', array([ 0.98141091, 0.01858909]))\n ('Chemical potentials', array([-128704.69113838, -43953.68289587]))\n ('Chem pot progress', array([-216.74538037, 44.3316802 ]))\n ('Energy progress', 21.66743454404059)\n ('Driving force', 9.9463315854009124)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10019264 0.89980736]), CompositionSet(BCC_A2, [ 0.15932106 0.84067894])])\n ('NEW_L_MULTIPLIERS', array([ -9.08025758e+02, -9.08025618e+02, -2.62222764e+04,\n -1.32004895e+01, -2.53501901e+02, -1.28728431e+05,\n -4.39492174e+04]))\n ('old_driving_force', -52418.800953762977)\n (1.0, -52426.138630596652, 0.00028485002851522112)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10001996 0.89998004]), CompositionSet(BCC_A2, [ 0.12919167 0.87080833])])\n ('step', array([ -1.72410343e-04, 1.72410343e-04, -1.72956761e-04,\n 1.72956761e-04, 3.57627362e-17, -3.01293942e-02,\n 3.01293942e-02, 2.38743929e-16, 9.50872184e-03,\n -9.50872184e-03]))\n ('Site fractions', array([ 0.10001997, 0.89998003, 0.10001995, 0.89998005, 1. ,\n 0.12919167, 0.87080833, 1. ]))\n ('Phase fractions', array([ 0.99091963, 0.00908037]))\n ('Chemical potentials', array([-128728.43059314, -43949.21741968]))\n ('Chem pot progress', array([-23.73945476, 4.46547619]))\n ('Energy progress', 78.0296745749074)\n ('Driving force', 1.0001064259486157)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10001996 0.89998004]), CompositionSet(BCC_A2, [ 0.12919167 0.87080833])])\n ('NEW_L_MULTIPLIERS', array([ -9.11693966e+02, -9.11693889e+02, -2.63433721e+04,\n -7.67263976e+00, -1.19771339e+02, -1.28732581e+05,\n -4.39487572e+04]))\n ('old_driving_force', -52426.137317272318)\n (1.0, -52427.017430527267, 6.7835714527841873e-05)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10000321 0.89999679]), CompositionSet(BCC_A2, [ 0.11446116 0.88553884])])\n ('step', array([ -1.67639436e-05, 1.67639436e-05, -1.67392176e-05,\n 1.67392176e-05, -3.95517924e-16, -1.47305099e-02,\n 1.47305099e-02, 4.19363407e-16, 4.61035945e-03,\n -4.61035945e-03]))\n ('Site fractions', array([ 0.10000321, 0.89999679, 0.10000321, 0.89999679, 1. ,\n 0.11446116, 0.88553884, 1. ]))\n ('Phase fractions', array([ 0.99552999, 0.00447001]))\n ('Chemical potentials', array([-128732.58095315, -43948.75719797]))\n ('Chem pot progress', array([-4.15036001, 0.4602217 ]))\n ('Energy progress', 17.519190094884834)\n ('Driving force', 0.12214296470483532)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.691754320316)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.691754320316)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.691754320316)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.69175437822)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.69175437822)\n (CompositionSet(AL13FE4, [ 0.72918506 0.27081494]), 'Driving Force: ', -39995.077838190075)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.69175432036)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.691754378204)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40046.691754378204)\n (CompositionSet(AL13FE4, [ 0.72918506 0.27081494]), 'Driving Force: ', -39995.077838190045)\n (CompositionSet(AL2FE, [ 0.66666667 0.33333333]), 'Driving Force: ', -32262.086298476366)\n (CompositionSet(AL5FE2, [ 0.71428571 0.28571429]), 'Driving Force: ', -37071.751088267236)\n (CompositionSet(AL5FE4, [ 0.12361388 0.87638612]), 'Driving Force: ', -5562.012131740361)\n (CompositionSet(AL5FE4, [ 0.12361387 0.87638613]), 'Driving Force: ', -5562.0121317403755)\n (CompositionSet(AL5FE4, [ 0.12361385 0.87638615]), 'Driving Force: ', -5562.0121317404555)\n (CompositionSet(AL5FE4, [ 0.12361387 0.87638613]), 'Driving Force: ', -5562.0121317403755)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7507.369241169756)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7507.369241169756)\n (CompositionSet(AL5FE4, [ 0.12361385 0.87638615]), 'Driving Force: ', -5562.0121317404555)\n (CompositionSet(AL5FE4, [ 0.12361388 0.87638612]), 'Driving Force: ', -5562.012131740368)\n (CompositionSet(AL5FE4, [ 0.12361386 0.87638614]), 'Driving Force: ', -5562.012131740383)\n (CompositionSet(AL5FE4, [ 0.12361388 0.87638612]), 'Driving Force: ', -5562.012131740368)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.2746748645877)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.2746748645877)\n (CompositionSet(B2_BCC, [ 0.10000321 0.89999679]), 'Driving Force: ', 4.015679587610066e-05)\n (CompositionSet(B2_BCC, [ 0.09523972 0.90476028]), 'Driving Force: ', -222.88486400200054)\n (CompositionSet(B2_BCC, [ 0.09523913 0.90476087]), 'Driving Force: ', -223.02464278716798)\n (CompositionSet(B2_BCC, [ 0.0952387 0.9047613]), 'Driving Force: ', -222.86042421004822)\n (CompositionSet(B2_BCC, [ 0.09523949 0.90476051]), 'Driving Force: ', -223.0248025308465)\n (CompositionSet(B2_BCC, [ 0.1000032 0.8999968]), 'Driving Force: ', 4.015677404822782e-05)\n (CompositionSet(B2_BCC, [ 0.09523906 0.90476094]), 'Driving Force: ', -222.8603787835018)\n (CompositionSet(B2_BCC, [ 0.09523969 0.90476031]), 'Driving Force: ', -222.88450332220964)\n (CompositionSet(BCC_A2, [ 0.10000321 0.89999679]), 'Driving Force: ', 4.015679587610066e-05)\n (CompositionSet(BCC_A2, [ 0.10000321 0.89999679]), 'Driving Force: ', 4.0156803152058274e-05)\n (CompositionSet(BCC_A2, [ 0.10000321 0.89999679]), 'Driving Force: ', 4.015678132418543e-05)\n (CompositionSet(BCC_A2, [ 0.10000317 0.89999683]), 'Driving Force: ', 4.015659214928746e-05)\n (CompositionSet(BCC_A2, [ 0.1000032 0.8999968]), 'Driving Force: ', 4.015677404822782e-05)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.2746748645877)\n (CompositionSet(BCC_A2, [ 0.10000321 0.89999679]), 'Driving Force: ', 4.01567667722702e-05)\n (CompositionSet(BCC_A2, [ 0.10000318 0.89999682]), 'Driving Force: ', 4.015674494439736e-05)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.2746748645877)\n (CompositionSet(BCC_A2, [ 0.10000321 0.89999679]), 'Driving Force: ', 4.0156788600143045e-05)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2014.0204160625653)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2014.0204160625653)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2014.0204160625653)\n (CompositionSet(FCC_A1, [ 0.06937449 0.93062551]), 'Driving Force: ', -845.1027696366291)\n (CompositionSet(FCC_A1, [ 0.06937449 0.93062551]), 'Driving Force: ', -845.1027696366291)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2014.0204160522626)\n (CompositionSet(FCC_A1, [ 0.06937449 0.93062551]), 'Driving Force: ', -845.1027696366291)\n (CompositionSet(FCC_A1, [ 0.06937449 0.93062551]), 'Driving Force: ', -845.1027696366582)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2014.0204160522626)\n (CompositionSet(FCC_A1, [ 0.06937449 0.93062551]), 'Driving Force: ', -845.1027696366291)\n (CompositionSet(HCP_A3, [ 0.10519655 0.89480345]), 'Driving Force: ', -2193.7780461311922)\n (CompositionSet(HCP_A3, [ 0.10519655 0.89480345]), 'Driving Force: ', -2193.778046131214)\n (CompositionSet(HCP_A3, [ 0.10519655 0.89480345]), 'Driving Force: ', -2193.7780461311922)\n (CompositionSet(HCP_A3, [ 0.10519655 0.89480345]), 'Driving Force: ', -2193.7780461311704)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4079.640670336674)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4079.640670336674)\n (CompositionSet(HCP_A3, [ 0.10519654 0.89480346]), 'Driving Force: ', -2193.778046131236)\n (CompositionSet(HCP_A3, [ 0.10519656 0.89480344]), 'Driving Force: ', -2193.7780461311922)\n (CompositionSet(HCP_A3, [ 0.10519655 0.89480345]), 'Driving Force: ', -2193.7780461312286)\n (CompositionSet(HCP_A3, [ 0.10519655 0.89480345]), 'Driving Force: ', -2193.7780461312213)\n (CompositionSet(LIQUID, [ 0.08164685 0.91835315]), 'Driving Force: ', -6819.948588294188)\n (CompositionSet(LIQUID, [ 0.08164686 0.91835314]), 'Driving Force: ', -6819.948588294137)\n (CompositionSet(LIQUID, [ 0.08164686 0.91835314]), 'Driving Force: ', -6819.948588294152)\n (CompositionSet(LIQUID, [ 0.08164686 0.91835314]), 'Driving Force: ', -6819.948588294166)\n (CompositionSet(LIQUID, [ 0.08164686 0.91835314]), 'Driving Force: ', -6819.948588294159)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7976.404081175773)\n (CompositionSet(LIQUID, [ 0.08164682 0.91835318]), 'Driving Force: ', -6819.948588294392)\n (CompositionSet(LIQUID, [ 0.08164686 0.91835314]), 'Driving Force: ', -6819.948588294159)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7976.404081175773)\n (CompositionSet(LIQUID, [ 0.08164686 0.91835314]), 'Driving Force: ', -6819.948588294137)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10000321 0.89999679]), CompositionSet(BCC_A2, [ 0.11446116 0.88553884])])\n ('NEW_L_MULTIPLIERS', array([ -9.13672600e+02, -9.13672608e+02, -2.64029057e+04,\n -3.98511832e+00, -5.87748012e+01, -1.28733236e+05,\n -4.39486845e+04]))\n ('old_driving_force', -52427.017381184611)\n (1.0, -52427.124550599561, 1.6384128219068539e-05)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10000045 0.89999955]), CompositionSet(BCC_A2, [ 0.10719408 0.89280592])])\n ('step', array([ -2.75423525e-06, 2.75423525e-06, -2.75636153e-06,\n 2.75636153e-06, 6.96288171e-16, -7.26707885e-03,\n 7.26707885e-03, 4.17891631e-16, 2.25542380e-03,\n -2.25542380e-03]))\n ('Site fractions', array([ 0.10000045, 0.89999955, 0.10000045, 0.89999955, 1. ,\n 0.10719408, 0.89280592, 1. ]))\n ('Phase fractions', array([ 0.99778541, 0.00221459]))\n ('Chemical potentials', array([-128733.23563716, -43948.68449733]))\n ('Chem pot progress', array([-0.65468401, 0.07270064]))\n ('Energy progress', 4.25513023530948)\n ('Driving force', 0.015060717472806573)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10000045 0.89999955]), CompositionSet(BCC_A2, [ 0.10719408 0.89280592])])\n ('NEW_L_MULTIPLIERS', array([ -9.14679440e+02, -9.14679439e+02, -2.64323331e+04,\n -2.00833710e+00, -2.91735819e+01, -1.28733329e+05,\n -4.39486741e+04]))\n ('old_driving_force', -52427.12454890088)\n (1.0, -52427.137743845771, 4.013187669502094e-06)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10000006 0.89999994]), CompositionSet(BCC_A2, [ 0.10358754 0.89641246])])\n ('step', array([ -3.92563192e-07, 3.92563184e-07, -3.92232531e-07,\n 3.92232527e-07, -3.11369967e-16, -3.60654427e-03,\n 3.60654427e-03, 2.41270376e-16, 1.11287262e-03,\n -1.11287262e-03]))\n ('Site fractions', array([ 0.10000006, 0.89999994, 0.10000006, 0.89999994, 1. ,\n 0.10358754, 0.89641246, 1. ]))\n ('Phase fractions', array([ 0.99889829, 0.00110171]))\n ('Chemical potentials', array([-128733.32894854, -43948.67413046]))\n ('Chem pot progress', array([-0.09331139, 0.01036687]))\n ('Energy progress', 1.0356709793340997)\n ('Driving force', 0.0018684253227547742)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10000006 0.89999994]), CompositionSet(BCC_A2, [ 0.10358754 0.89641246])])\n ('NEW_L_MULTIPLIERS', array([ -9.15183480e+02, -9.15183480e+02, -2.64469435e+04,\n -1.00507792e+00, -1.45423141e+01, -1.28733342e+05,\n -4.39486727e+04]))\n ('old_driving_force', -52427.137743789332)\n (1.0, -52427.139379633685, 9.9191251501373756e-07)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.10000001 0.89999999]), CompositionSet(BCC_A2, [ 0.10179134 0.89820866])])\n ('step', array([ -5.31582525e-08, 5.31582535e-08, -5.32046478e-08,\n 5.32046598e-08, 6.65301323e-16, -1.79619350e-03,\n 1.79619350e-03, -2.01007408e-17, 5.52246671e-04,\n -5.52246671e-04]))\n ('Site fractions', array([ 0.10000001, 0.89999999, 0.10000001, 0.89999999, 1. ,\n 0.10179134, 0.89820866, 1. ]))\n ('Phase fractions', array([ 9.99450532e-01, 5.49468053e-04]))\n ('Chemical potentials', array([-128733.34160659, -43948.67272404]))\n ('Chem pot progress', array([-0.01265805, 0.00140643]))\n ('Energy progress', 0.2545219693129184)\n ('Driving force', 0.00023265689378604293)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.10000001 0.89999999]), CompositionSet(BCC_A2, [ 0.10179134 0.89820866])])\n ('NEW_L_MULTIPLIERS', array([ -9.15435197e+02, -9.15435197e+02, -2.64542232e+04,\n -5.02284417e-01, -7.26003672e+00, -1.28733343e+05,\n -4.39486725e+04]))\n ('old_driving_force', -52427.139379631953)\n (1.0, -52427.139583269083, 2.4658185224235574e-07)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10089506 0.89910494])])\n ('step', array([ -6.61034324e-09, 6.61034128e-09, -6.60619097e-09,\n 6.60618448e-09, 1.67282150e-17, -8.96284014e-04,\n 8.96284014e-04, -7.62261594e-17, 2.75117782e-04,\n -2.75117782e-04]))\n ('Site fractions', array([ 0.1 , 0.9 , 0.1 , 0.9 , 1. ,\n 0.10089506, 0.89910494, 1. ]))\n ('Phase fractions', array([ 9.99725650e-01, 2.74350271e-04]))\n ('Chemical potentials', array([-128733.34317625, -43948.67254963]))\n ('Chem pot progress', array([-0.00156966, 0.00017441]))\n ('Energy progress', 0.06298897750093602)\n ('Driving force', 2.9021874070167542e-05)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10089506 0.89910494])])\n ('NEW_L_MULTIPLIERS', array([ -9.15560867e+02, -9.15560867e+02, -2.64578555e+04,\n -2.51025422e-01, -3.62736820e+00, -1.28733343e+05,\n -4.39486725e+04]))\n ('old_driving_force', -52427.139583269025)\n (1.0, -52427.139608667007, 6.1453809943601279e-08)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10044738 0.89955262])])\n ('step', array([ -8.95129687e-10, 8.95133129e-10, -8.93765722e-10,\n 8.93770188e-10, 1.28763209e-18, -4.47683746e-04,\n 4.47683746e-04, -1.02267136e-16, 1.37270860e-04,\n -1.37270860e-04]))\n ('Site fractions', array([ 0.1 , 0.9 , 0.1 , 0.9 , 1. ,\n 0.10044738, 0.89955262, 1. ]))\n ('Phase fractions', array([ 9.99862921e-01, 1.37079412e-04]))\n ('Chemical potentials', array([-128733.34338866, -43948.67252603]))\n ('Chem pot progress', array([ -2.12406012e-04, 2.36006672e-05]))\n ('Energy progress', 0.01567062217509374)\n ('Driving force', 3.6239434848539531e-06)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.223383738135)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338373815)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338373815)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338379604)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338379604)\n (CompositionSet(AL13FE4, [ 0.72918502 0.27081498]), 'Driving Force: ', -39995.61086432342)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338373818)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338379602)\n (CompositionSet(AL13FE4, [ 0.72753623 0.27246377]), 'Driving Force: ', -40047.22338379602)\n (CompositionSet(AL13FE4, [ 0.72918502 0.27081498]), 'Driving Force: ', -39995.61086432343)\n (CompositionSet(AL2FE, [ 0.66666667 0.33333333]), 'Driving Force: ', -32262.56636483186)\n (CompositionSet(AL5FE2, [ 0.71428571 0.28571429]), 'Driving Force: ', -37072.27149307284)\n (CompositionSet(AL5FE4, [ 0.12360958 0.87639042]), 'Driving Force: ', -5562.032172209918)\n (CompositionSet(AL5FE4, [ 0.12360957 0.87639043]), 'Driving Force: ', -5562.032172209889)\n (CompositionSet(AL5FE4, [ 0.12360958 0.87639042]), 'Driving Force: ', -5562.032172209896)\n (CompositionSet(AL5FE4, [ 0.12360958 0.87639042]), 'Driving Force: ', -5562.032172209911)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7507.284569223484)\n (CompositionSet(AL5FE4, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7507.284569223484)\n (CompositionSet(AL5FE4, [ 0.12360955 0.87639045]), 'Driving Force: ', -5562.032172209976)\n (CompositionSet(AL5FE4, [ 0.12360958 0.87639042]), 'Driving Force: ', -5562.032172209918)\n (CompositionSet(AL5FE4, [ 0.12360956 0.87639044]), 'Driving Force: ', -5562.032172209911)\n (CompositionSet(AL5FE4, [ 0.12360958 0.87639042]), 'Driving Force: ', -5562.032172209889)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.1900029183162)\n (CompositionSet(B2_BCC, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.1900029183162)\n (CompositionSet(B2_BCC, [ 0.1 0.9]), 'Driving Force: ', 1.4551915228366852e-11)\n (CompositionSet(B2_BCC, [ 0.09523594 0.90476406]), 'Driving Force: ', -222.88048632366554)\n (CompositionSet(B2_BCC, [ 0.09523592 0.90476408]), 'Driving Force: ', -223.02109609990293)\n (CompositionSet(B2_BCC, [ 0.09523555 0.90476445]), 'Driving Force: ', -222.85652010350168)\n (CompositionSet(B2_BCC, [ 0.0952361 0.9047639]), 'Driving Force: ', -223.02104784097173)\n (CompositionSet(B2_BCC, [ 0.09999999 0.90000001]), 'Driving Force: ', 0.0)\n (CompositionSet(B2_BCC, [ 0.09523494 0.90476506]), 'Driving Force: ', -222.856047112924)\n (CompositionSet(B2_BCC, [ 0.0952346 0.9047654]), 'Driving Force: ', -222.87958953971247)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', -1.4551915228366852e-11)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', -2.1827872842550278e-11)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', -7.275957614183426e-12)\n (CompositionSet(BCC_A2, [ 0.09999993 0.90000007]), 'Driving Force: ', -6.330083124339581e-10)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', 0.0)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.1900029183162)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', 0.0)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', -2.1827872842550278e-11)\n (CompositionSet(BCC_A2, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -1676.1900029183162)\n (CompositionSet(BCC_A2, [ 0.1 0.9]), 'Driving Force: ', 7.275957614183426e-12)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2013.9357441162938)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2013.9357441162938)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2013.9357441162938)\n (CompositionSet(FCC_A1, [ 0.06937214 0.93062786]), 'Driving Force: ', -845.076864340248)\n (CompositionSet(FCC_A1, [ 0.06937213 0.93062787]), 'Driving Force: ', -845.0768643402771)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2013.935744105991)\n (CompositionSet(FCC_A1, [ 0.06937214 0.93062786]), 'Driving Force: ', -845.0768643402625)\n (CompositionSet(FCC_A1, [ 0.06937213 0.93062787]), 'Driving Force: ', -845.0768643402771)\n (CompositionSet(FCC_A1, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -2013.935744105991)\n (CompositionSet(FCC_A1, [ 0.06937214 0.93062786]), 'Driving Force: ', -845.0768643402625)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.7824856016086)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.7824856016014)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.7824856015795)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.782485601594)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4079.5559983904022)\n (CompositionSet(HCP_A3, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -4079.5559983904022)\n (CompositionSet(HCP_A3, [ 0.1051933 0.8948067]), 'Driving Force: ', -2193.782485601667)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.782485601587)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.782485601587)\n (CompositionSet(HCP_A3, [ 0.10519332 0.89480668]), 'Driving Force: ', -2193.7824856015795)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.933078551323)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.933078551345)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.933078551359)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.933078551352)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.933078551381)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7976.319409229502)\n (CompositionSet(LIQUID, [ 0.08164337 0.91835663]), 'Driving Force: ', -6819.933078551578)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.933078551359)\n (CompositionSet(LIQUID, [ 1.00000000e-12 1.00000000e+00]), 'Driving Force: ', -7976.319409229502)\n (CompositionSet(LIQUID, [ 0.08164341 0.91835659]), 'Driving Force: ', -6819.9330785513375)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10044738 0.89955262])])\n ('NEW_L_MULTIPLIERS', array([ -9.15623650e+02, -9.15623650e+02, -2.64596699e+04,\n -1.25468623e-01, -1.81293335e+00, -1.28733343e+05,\n -4.39486725e+04]))\n ('old_driving_force', -52427.139608667007)\n (1.0, -52427.139611838211, 1.5340343662018086e-08)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10022365 0.89977635])])\n ('step', array([ -1.10111442e-10, 1.10110322e-10, -1.10105774e-10,\n 1.10094355e-10, 1.58932383e-16, -2.23726593e-04,\n 2.23726593e-04, 6.72751338e-16, 6.85674031e-05,\n -6.85674031e-05]))\n ('Site fractions', array([ 0.1 , 0.9 , 0.1 , 0.9 , 1. ,\n 0.10022365, 0.89977635, 1. ]))\n ('Phase fractions', array([ 9.99931488e-01, 6.85120085e-05]))\n ('Chemical potentials', array([-128733.34341486, -43948.67252312]))\n ('Chem pot progress', array([ -2.62004032e-05, 2.91114702e-06]))\n ('Energy progress', 0.003906543868652079)\n ('Driving force', 4.5276101445779204e-07)\n ('Composition Sets', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10022365 0.89977635])])\n ('NEW_L_MULTIPLIERS', array([ -9.15655021e+02, -9.15655021e+02, -2.64605765e+04,\n -6.27280521e-02, -9.06361610e-01, -1.28733343e+05,\n -4.39486725e+04]))\n ('old_driving_force', -52427.139611838211)\n (1.0, -52427.139612234372, 3.8314409422923745e-09)\n ('alpha', 1.0)\n ('Phases', [CompositionSet(B2_BCC, [ 0.1 0.9]), CompositionSet(BCC_A2, [ 0.10011182 0.89988818])])\n ('step', array([ -1.61309354e-11, 1.61403622e-11, -1.61286488e-11,\n 1.61301355e-11, -1.02692581e-16, -1.11834397e-04,\n 1.11834397e-04, -1.41461337e-16, 3.42599279e-05,\n -3.42599279e-05]))\n ('Site fractions', array([ 0.1 , 0.9 , 0.1 , 0.9 , 1. ,\n 0.10011182, 0.89988818, 1. ]))\n ('Phase fractions', array([ 9.99965748e-01, 3.42520807e-05]))\n ('Chemical potentials', array([-128733.3434187 , -43948.67252269]))\n ('Chem pot progress', array([ -3.83899896e-06, 4.26574843e-07]))\n ('Energy progress', 0.0009753828344400972)\n ('Driving force', 5.657784640789032e-08)\n No progress\n\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.scatter(eq.coords['X_AL'], eq.GM[0,0])\nplt.show()\n```\n\n\n```python\nres = calculate(dbf, ['AL', 'FE', 'VA'], ['B2_BCC'], T=790, P=101325, model=Model, pdens=50)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.scatter(res.X[0,0].sel(component='AL'), res.GM[0,0])\n#plt.plot([1,0], [-105391.47499307, -31879.10489844])\n\n#plt.xlim((0.135, 0.145))\n#plt.ylim((-45000, -40000))\nplt.show()\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pycalphad import equilibrium, calculate\nfrom pycalphad import Database, Model\nimport pycalphad.variables as v\nimport numpy as np\nfrom pycalphad.plot.utils import phase_legend\n\ndb = Database('alfe_sei.TDB')\nphase_names=set(sorted(list(db.phases.keys()))) - {'BCC_A2'}\neq = equilibrium(db, ['AL', 'FE', 'VA'], phase_names, {v.X('AL'): 0.23, v.T: 1170, v.P: 101325}, verbose=True)\n\nprint(eq)\n```\n\n\n```python\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pycalphad import equilibrium, calculate\nfrom pycalphad import Database, Model\nimport pycalphad.variables as v\nimport numpy as np\nfrom pycalphad.plot.utils import phase_legend\n\ndb = Database('alfe_sei.TDB')\nphase_names=sorted(list(db.phases.keys()))\n\nmy_phases = ['LIQUID', 'FCC_A1']\nphase_handles, phasemap = phase_legend(my_phases)\n\nTvector=np.arange(900.0,950.0,1.0)\n\neq = equilibrium(db, ['AL', 'FE', 'VA'], my_phases, {v.X('FE'): 1.5e-3, v.T: Tvector, v.P: 101325}, verbose=False)\n\nprint(eq)\n\nplt.figure()\n\nfor name in my_phases:\n phase_indices = np.nonzero(eq.Phase.values == name)\n plt.scatter(np.take(eq['T'].values, phase_indices[1]), eq.NP.values[phase_indices], color=phasemap[name])\n plt.gca().legend(phase_handles, my_phases, loc='lower right')\n plt.xlabel('Temperature (K)')\n plt.ylabel('Phase Fraction')\nplt.figure()\nplt.scatter(eq['T'].values, eq.MU.sel(component='FE').isel(P=0))\nplt.xlabel('Temperature (K)')\nplt.ylabel('MU(FE)')\n```\n\n\n```python\neq.GM\n```\n\n\n```python\nimport numpy as np\nfrom pycalphad.plot.utils import phase_legend\nfig = plt.figure()\nphase_handles, phasemap = phase_legend(['LIQUID', 'FCC_A1'])\nfor phase, color in phasemap.items():\n res = calculate(db, ['AL', 'FE', 'VA'], phase, T=901, P=101325)\n order = np.argsort(res.X[0,0].sel(component='FE'))\n x = res.X[0,0].sel(component='FE').values[order]\n y = res.GM[0,0].values[order]\n fig.gca().plot(x, y, c=color)\nfig.gca().vlines(1.5e-3, -37000, -35000, colors='r', linestyles='dotted')\nfig.gca().set_xlim((0, 2e-2))\nfig.gca().set_ylim((-37000, -35000))\nfig.gca().set_xlabel('X(FE)')\nfig.gca().set_ylabel('Molar Gibbs Energy (J/mol-atom)')\nfig.gca().set_title('T = 901 K')\nfig.gca().legend(phase_handles, ['LIQUID', 'FCC_A1'], loc='lower right')\n```\n\n\n```python\nfrom pycalphad import equilibrium, calculate\nfrom pycalphad import Database, Model\nimport pycalphad.variables as v\nfrom sympy import Symbol\ndbf = Database('alfe_sei.TDB')\n#calculate(dbf, ['AL', 'VA'], 'FCC_A1', T=1200, P=101325)\neq = equilibrium(dbf, ['AL', 'VA'], 'FCC_A1', {v.T: 1200, v.P: 101325}, verbose=True, output='SM', parameters={'GHSERAL': 1000})\n```\n\n\n```python\neq\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "84de19362ac19d64515c17b358293a356fce41c1", "size": 90837, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "EqPerformance-CompiledModel.ipynb", "max_stars_repo_name": "richardotis/pycalphad-sandbox", "max_stars_repo_head_hexsha": "43d8786eee8f279266497e9c5f4630d19c893092", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-08T18:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-08T18:21:30.000Z", "max_issues_repo_path": "EqPerformance-CompiledModel.ipynb", "max_issues_repo_name": "richardotis/pycalphad-sandbox", "max_issues_repo_head_hexsha": "43d8786eee8f279266497e9c5f4630d19c893092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EqPerformance-CompiledModel.ipynb", "max_forks_repo_name": "richardotis/pycalphad-sandbox", "max_forks_repo_head_hexsha": "43d8786eee8f279266497e9c5f4630d19c893092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-03T01:31:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-03T01:31:57.000Z", "avg_line_length": 70.9110070258, "max_line_length": 188, "alphanum_fraction": 0.6116450345, "converted": true, "num_tokens": 33852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3477711431940868}} {"text": "```python\n# This cell is for the Google Colaboratory\n# https://stackoverflow.com/a/63519730\nif 'google.colab' in str(get_ipython()):\n # https://colab.research.google.com/notebooks/io.ipynb\n import google.colab.drive as gcdrive\n # may need to visit a link for the Google Colab authorization code\n gcdrive.mount(\"/content/drive/\")\n import sys\n sys.path.insert(0,\"/content/drive/My Drive/Colab Notebooks/nmisp/10_root_finding\")\n\n```\n\n# 적용 사례
Examples\n\n\n\n\n```python\nimport pylab as py\n\n\n```\n\n## 경사 곡선로의 자동차
A car on a banked curve\n\n\n\nref : Beer et. al., Vector Mechanics for Engineers, 8th Ed in SI, Dynamics, Sample problem 12.6, McGraw-Hill, 2007.\n\n\n\n### 질문
Question\n\n\n\n반경 $\\rho=122m$, 횡경사각 $\\theta=18^\\circ$ 인 곡선로에서 횡방향 마찰력 없이 차량이 달릴 수 있는 속도 $v$(m/s) 는?\n\n\n\nOn a curved road with radius $\\rho=122m$ and bank angle $\\theta=18^\\circ$, what is the speed $v$(m/s) such that no lateral friction forces would exert on the vehicle?\n\n\n\n### 풀이 예
One possible answer\n\n\n\n지면에 수직한 중력 가속도 성분
\nComponent of the gravitational acceleration normal to the ground surface\n\n\n\n$$\n g_n = g \\cdot cos\\theta\n$$\n\n\n\n지면에 평행한 중력 가속도 성분
\nComponent of the gravitational acceleration parallel to the ground surface\n\n\n\n$$\n g_p = g \\cdot sin\\theta\n$$\n\n\n\n원심가속도
\nCentrifugal Acceleration\n\n\n\n$$\n a_c = \\frac{v^2}{\\rho}\n$$\n\n\n\n지면에 평행한 원심 가속도 성분
\nComponent of the centrifugal Acceleration normal to the ground surface\n\n\n\n$$\n a_{cp} = a_c \\cdot cos\\theta\n$$\n\n\n\n지면에 수직인 원심 가속도 성분
\nComponent of the centrifugal acceleration parallel to the ground surface\n\n\n\n$$\n a_{cn} = a_c \\cdot sin\\theta\n$$\n\n\n\n두 가속도의 지면에 평행한 성분들끼리 같으면 횡가속도는 0이 될 것이다.
\nIf two components of accelerations parallel to the ground are the same, the lateral acceleration would be zero.\n\n\n\n$$\n\\begin{align}\ng_p & = a_{cp} \\\\\ngsin\\theta & = \\frac{v^2}{\\rho}cos\\theta \\\\\ngsin\\theta & - \\frac{v^2}{\\rho}cos\\theta = 0\n\\end{align}\n$$\n\n\n\n매개변수
\nParameters\n\n\n\n\n```python\ng_mps2 = 9.8\ntheta_deg = 18\ntheta_rad = py.deg2rad(theta_deg)\nrho_m = 122\n\n\n```\n\n$ f(v)=0 $\n\n\n\n\n```python\ndef f(v_mps):\n return g_mps2 * py.sin(theta_rad) - v_mps * v_mps * py.cos(theta_rad) / rho_m\n\n\n```\n\n1변수 방정식 해법 함수를 불러들임\n\n\n\n\n```python\nimport root_finding as rf\n\n\n```\n\n순차법
\nSequential Method\n\n\n\n\n```python\n%time v_seq_mps = rf.sequential(f, 0, 1/2**12, 1e-3, 20)\nv_seq_mps\n\n\n```\n\n이분법
\nBisection Method\n\n\n\n\n```python\n%time v_bis_mps = rf.bisection(f, 0, 100, 1e-3)\nv_bis_mps\n\n\n```\n\n뉴튼랩슨법
\nNewotn Raphson Method\n\n\n\n$$\n\\begin{align}\nf(v) &= gsin\\theta - \\frac{v^2}{\\rho}cos\\theta \\\\\n\\frac{d}{dv}f(v) &= - 2\\frac{v}{\\rho}cos\\theta\n\\end{align}\n$$\n\n\n\n\n```python\ndef df(v_mps):\n return - 2 * v_mps * py.cos(theta_rad) / rho_m\n\n\n```\n\n\n```python\n%time v_nr_mps = rf.newton_raphson(f, df, 1, 1e-3)\nv_nr_mps\n\n\n```\n\n## 분포하중 외팔보
Distributed load cantilever\n\n\n\nref : Pytel et. al, Mechanics of Materials, 2nd Ed, SI, Ex. 6.9 & Table 6.2, Cengage Learning, 2011.\n\n\n\n### 질문
Question\n\n\n\n균일 분포하중 외팔보의 처짐은 다음과 같다.
\nThe deflection of a uniform distributed load cantilver is as follows.\n\n\n\n$$\n\\begin{align}\n\\delta(x) &= \\frac{w_o x^2}{24EI}\\left(6L^2 - 4Lx + x^2 \\right) \\\\\n\\delta(L) &= \\frac{w_o L^4}{8EI}\n\\end{align}\n$$\n\n\n\n다음 매개변수들을 사용하여 처짐의 $x=L$ 에서의 절반인 $x$(m)를 구하시오.
\nUsing following parameters, find $x$ such that its deflection $\\delta(x)$ is the half of the deflection at $x=L$.\n\n\n\n$$\nEI=20.48\\times 10^3 N \\cdot m^2 \\\\ \nw_o=100N/m \\\\ \nL=1m\n$$\n\n\n\n### 풀이 예
One possible answer\n\n\n\n$$\n\\begin{align}\n\\delta(x) &= \\frac{1}{2}\\delta(L) \\\\\n\\frac{w_o x^2}{24EI}\\left(6L^2 - 4Lx + x^2 \\right) &= \\frac{1}{2}\\frac{w_o L^4}{8EI} \\\\\n\\frac{x^2}{3}\\left(6L^2 - 4Lx + x^2 \\right) &= \\frac{1}{2}L^4\n\\end{align}\n$$\n\n\n\n$$\n\\frac{x^2}{3}\\left(6L^2 - 4Lx + x^2 \\right) - \\frac{1}{2}L^4 = 0\n$$\n\n\n\n\n```python\nL_m = 1\n\n\n```\n\n$g(x)=0 $\n\n\n\n\n```python\ndef g(x_m):\n return (x_m ** 2) * (6 * L_m - 4 * L_m * x_m + x_m ** 2) / 3. - 0.5 * L_m ** 4\n\n\n```\n\n순차법
\nSequential Method\n\n\n\n\n```python\n%time x_seq_m = rf.sequential(g, 0, 1/2**12, 1e-3, 1)\nx_seq_m\n\n\n```\n\n이분법
\nBisection Method\n\n\n\n\n```python\n%time x_bis_m = rf.bisection(g, 0, 1, 1e-3)\nx_bis_m\n\n\n```\n\n뉴튼랩슨법
\nNewotn Raphson Method\n\n\n\n$$\n\\begin{align}\ng(x) &= \\frac{x^2}{3}\\left(6L^2 - 4Lx + x^2 \\right) - \\frac{1}{2}L^4 \\\\\n&= \\left(6L^2\\frac{x^2}{3} - 4Lx\\frac{x^2}{3} + x^2\\frac{x^2}{3} \\right) - \\frac{1}{2}L^4 \\\\\n&= \\frac{1}{3}x^4 - \\frac{4L}{3}x^3 + 2L^2x^2 - \\frac{1}{2}L^4 \\\\\n\\frac{d}{dx}g(x) &= \\frac{4}{3}x^3 - 4Lx^2 + 4L^2x\n\\end{align}s\n$$\n\n\n\n\n```python\ndef dg(x_m):\n return 4./3 * x_m ** 3 - 4 * L_m * x_m ** 2 + 4 * L_m ** 2 * x_m\n\n\n```\n\n\n```python\n%time x_nr_m = rf.newton_raphson(g, dg, .1, 1e-3)\nx_nr_m\n\n\n```\n\n## 여러 구간으로 나누어진 연속 함수
A piecewise continuous function\n\n\n\n$$\nh(x) = p(x) - \\sqrt{2}\n$$\n\n\n\n$$\np(x) = \n\\begin{cases}\nx & x < -1 \\\\\nsin \\frac{\\pi}{2} x & -1 \\leq x < 1 \\\\\nx & 1 < x\n\\end{cases}\n$$\n\n\n\n아래 함수는 float 형 매개변수를 받아들일 것이다
\n Ths function below expects a float argument
\n반환형은 float형 일 것이다.
\n Also expected to return a float variable.\n\n\n\n\n```python\ndef h(x: float) -> float:\n return p(x) - 2 ** (-0.5)\n\n\n```\n\n이 경우 `p(x)` 함수는 `h(x)` 함수를 호출 하기 전에 정의되면 된다.
\nIn this case, we need to define the `p(x)` function before calling `h(x).\n\n\n\n\n```python\ndef p(x: float) -> float:\n if (-1 > x) or (1 < x):\n result = x\n else :\n result = py.sin(py.pi * x * 0.5)\n\n return result\n\n\n```\n\n\n```python\nx = py.linspace(-2, 2)\ny = py.array([h(xi) for xi in x])\n\npy.plot(x, y)\npy.grid(True)\npy.xlabel('x')\npy.ylabel('h(x)')\n\n\n```\n\n순차법
\nSequential Method\n\n\n\n\n```python\n%time x_seq = rf.sequential(h, 0, 1/2**12, 1e-3, 1)\nx_seq\n\n\n```\n\n이분법
\nBisection Method\n\n\n\n\n```python\n%time x_bis = rf.bisection(h, 0, 3, 1e-3)\nx_bis\n\n\n```\n\n뉴튼법
\nNewton-Raphson Method\n\n\n\n함수 $h(x)$ 는 $x=\\pm 1$ 에서 기울기가 불연속이다.
\nThe slope of the function $h(x)$ is not continuous at $x=\\pm 1$.\n\n\n\n기울기를 구하기 위해 아래 함수를 사용해 보자.
\nTo find the slopes, let's use following function.\n\n\n\n$$\nq(x) = \n\\begin{cases}\n1 & x < -1 \\\\\n\\frac{\\pi}{2} cos \\frac{\\pi}{2} x & -1 \\leq x < 1 \\\\\n1 & 1 < x\n\\end{cases}\n$$\n\n\n\n\n```python\ndef q(x: float) -> float:\n if (-1 > x) or (1 < x):\n result = 1\n else :\n result = (py.pi * 0.5) * py.sin(py.pi * x * 0.5)\n\n return result\n\n\n```\n\n\n```python\n%time x_nr = rf.newton_raphson(h, q, .1, 1e-3)\nx_nr\n\n\n```\n\n## 유한한 구간에만 정의된 함수
A function defined within a finite interval\n\n\n\n$$\nr(x) = 2\\sqrt{1-\\frac{x^2}{4^2}} - \\frac{1}{2}\n$$\n\n\n\n함수 $r(x)$ 는 아래 구간에서만 정의된다.
\nFunction $r(x)$ is defined within the following interval only.\n\n\n\n$$ -4 \\leq x \\leq 4 $$\n\n\n\n\n```python\ndef r(x: float) -> float:\n return 2 * (1 - (x**2)/16) ** 0.5 - 0.5\n\n\n```\n\n\n```python\nx = 4 * py.cos(py.deg2rad(py.arange(180, 0-1, -1)))\n\npy.plot(x, r(x))\npy.grid(True)\npy.xlabel('x')\npy.ylabel('r(x)')\npy.axis('equal');\n\n\n```\n\n순차법
\nSequential Method\n\n\n\n\n```python\n%time x_seq_interval = rf.sequential(r, 0, 1/2**12, 1e-3, 3.9)\nx_seq_interval\n\n\n```\n\n이분법
\nBisection Method\n\n\n\n\n```python\n%time x_bis_interval = rf.bisection(r, 0, 3.9, 1e-3)\nx_bis_interval\n\n\n```\n\n뉴튼법을 위한 $r(x)$ 함수의 미분
\nDerivative of $r(x)$ for the Newton Raphson method\n\n\n\n\n```python\nimport sympy as sy\n\nx = sy.symbols('x', real=True)\nr_sym = 2 * sy.sqrt(1 - (x/4)**2) - 1 / 2\n\n\n```\n\n\n```python\nr_sym.diff(x)\n\n\n```\n\n\n```python\nprint(sy.python(r_sym.diff(x)))\n\n\n```\n\n\n```python\ndef drdx(x:float) -> float:\n return float((-x / 8) * (1 - (x**2)/16) ** (-0.5))\n\n\n```\n\n그러나, 함수 `drdx()` 는 $\\left| x \\right| > 4$ 일 경우 예외 Exception 을 발생시킬 것이다.
However, function `drdx()` would raise an Exception if $\\left| x \\right| > 4$.\n\n\n\n\n```python\n# try:\n# %time x_nr_interval = rf.newton_raphson(r, drdx, .1, 1e-3)\n# x_nr_interval\n# except TypeError as te:\n# print(te)\n# except NameError as ne:\n# print(ne)\n\n\n```\n\n## 여러 구간으로 나누어진 불연속 함수
A piecewise discontinuous function\n\n\n\n$$\ns(x) = t(x) - \\sqrt{2}\n$$\n\n\n\n$$\nt(x) = \n\\begin{cases}\nx & x < -1 \\\\\nsin \\pi x & -1 \\leq x < 1 \\\\\nx & 1 < x\n\\end{cases}\n$$\n\n\n\n\n```python\ndef s(x: float) -> float:\n return t(x) - 2 ** (-0.5)\n\n\n```\n\n\n```python\ndef t(x: float) -> float:\n if (-1 > x) or (1 < x):\n result = x\n else :\n result = py.sin(py.pi * x)\n\n return result\n\n\n```\n\n\n```python\nx = py.linspace(-2, 2)\ny = py.array([s(xi) for xi in x])\n\npy.plot(x, y)\npy.grid(True)\npy.xlabel('x')\npy.ylabel('s(x)')\n\n\n```\n\n순차법
\nSequential Method\n\n\n\n\n```python\n%time x_seq = rf.sequential(s, 0, 1/2**12, 1e-3, 1)\nx_seq\n\n\n```\n\n이분법
\nBisection Method\n\n\n\n\n```python\n%time x_bis = rf.bisection(s, 0, 0.51, 1e-3)\nx_bis\n\n\n```\n\n뉴튼법
\nNewton-Raphson Method\n\n\n\n함수 $h(x)$ 는 $x=\\pm 1$ 에서 기울기가 불연속이다.
\nThe slope of the function $h(x)$ is not continuous at $x=\\pm 1$.\n\n\n\n기울기를 구하기 위해 아래 함수를 사용해 보자.
\nTo find the slopes, let's use following function.\n\n\n\n$$\nq(x) = \n\\begin{cases}\n1 & x < -1 \\\\\n\\pi cos \\pi x & -1 \\leq x < 1 \\\\\n1 & 1 < x\n\\end{cases}\n$$\n\n\n\n\n```python\ndef u(x: float) -> float:\n if (-1 > x) or (1 < x):\n result = 1\n else :\n result = py.pi * py.sin(py.pi * x)\n\n return result\n\n\n```\n\n\n```python\n%time x_nr = rf.newton_raphson(s, u, .1, 1e-3)\nx_nr\n\n\n```\n\n\n```python\n%time x_nr = rf.newton_raphson(s, u, .9, 1e-3)\nx_nr\n\n\n```\n\n## 연습 문제
Exercises\n\n\n\n도전과제 1 : 반지름이 다음과 같을 때, 시속 160 km의 차량이 횡방향 마찰력 없이 주행할 수 있는 경사각($^\\circ$)은?
\nTry this 1 : With following radius, what would be the bank angle ($^\\circ$) such that a vehicle of 160km/hr can travel without lateral friction force?\n\n\n\n$$\n\\rho = 200(m)\n$$\n\n\n\n\n```python\n\n```\n\n도전과제 2 : 위 외팔보의 처짐 문제를 $x=L$ 지점의 집중하중에 대해 반복하시오.
\nTry this 2 : Repeat the cantilever deflection problem above regarding a single load at $x=L$.\n\n\n\n$$\n\\delta(x)=\\frac{Px^2}{6EI}\\left(3L-x\\right)\n$$\n\n\n\n\n```python\n\n```\n\n## Final Bell
마지막 종\n\n\n\n\n```python\n# stackoverfow.com/a/24634221\nimport os\nos.system(\"printf '\\a'\");\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "82ea8dbdc8f91e48792233f536c29e0d12c2b5b0", "size": 24193, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "10_root_finding/40_examples.ipynb", "max_stars_repo_name": "kangwonlee/2109eca-nmisp-template", "max_stars_repo_head_hexsha": "2e078870757fa06222df62d0ff8f4f4f288af51a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "10_root_finding/40_examples.ipynb", "max_issues_repo_name": "kangwonlee/2109eca-nmisp-template", "max_issues_repo_head_hexsha": "2e078870757fa06222df62d0ff8f4f4f288af51a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "10_root_finding/40_examples.ipynb", "max_forks_repo_name": "kangwonlee/2109eca-nmisp-template", "max_forks_repo_head_hexsha": "2e078870757fa06222df62d0ff8f4f4f288af51a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1551860649, "max_line_length": 178, "alphanum_fraction": 0.4485181664, "converted": true, "num_tokens": 4114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.34754702125239717}} {"text": "# KVLCC2 model tests\n\n# Purpose\nAnalyze the model tests and build roll decay mathematical models.\n\n# Methodology\nLook at the results from the KVLCC2 ship.\n* Load model test data\n* Determine damping by fitting an apropriate model.\n* Save these models to pkl files.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nimport sys\nsys.path.append(\"../../\")\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nimport copy\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic, EstimatorQuadratic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport src.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nimport shipflowmotionshelpers.shipflowmotionshelpers as helpers\nimport src.visualization.visualize as visualize\nimport scipy\nfrom copy import deepcopy\nimport joblib\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 463 ('figure.dpi : 100 ## figure dots per inch')\n\n\n\n```python\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorCubic,EstimatorQuadraticB\nfrom sklearn.base import clone\nfrom copy import deepcopy\nimport joblib\nfrom reports import mdl_results\n```\n\n\n```python\ndf_rolldecays = mdl_results.df_rolldecays\n```\n\n\n```python\ndf_rolldecays\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
project_numberseries_numberrun_numbertest_numbermodel_numbership_nameloading_condition_idascii_nameship_speedcommentfile_path_asciifile_path_ascii_tempfile_path_logfile_path_hdf5datetest_typefacilityangle1angle2KörfallstypnamelcgkggmCWTFTABWLKXXKZZBTT1CPVolumeA0RHscale_factorlppbeamABULBBKXTWINDCLRVDESRHBLASKEGPDARHCFPAIXPDTDESRTYPESFPBKLBKBPROTDLSKEGRRXSKEGNDESARBRBRAIRUDPTYPEXRUDAIHSKEGRSKEGLOAship_type_idrhogpaper_name
id
21337401783621941M5057-01-AM5057-01-A16694.00.0Roll decay, 0 knNaNNaN\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNaNNaNNaN20.811.267218.65.73NaN20.820.8NaN23.280.0NaNNaN312653.00.99538NaN68.0320.058.0NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN10009.811
21338401783621951M5057-01-AM5057-01-A16695.00.0Roll decay, 0 knNaNNaN\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNaNNaNNaN20.811.267218.65.73NaN20.820.8NaN23.280.0NaNNaN312653.00.99538NaN68.0320.058.0NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN10009.812
21340401783621971M5057-01-AM5057-01-A16697.015.5Roll decay, 15.5 knNaNNaN\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-04roll decayMDLNaNNaNNaN20.811.267218.65.73NaN20.820.8NaN23.280.0NaNNaN312653.00.99538NaN68.0320.058.0NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN10009.813
\n
\n\n\n\n\n```python\ndf_rolldecays[['date','ship_speed']]\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
dateship_speed
id
213372018-04-030.0
213382018-04-030.0
213402018-04-0415.5
\n
\n\n\n\n\n\n\n```python\ndef load_run(id, save_dir='../../data/processed/roll decay KVLCC2'):\n save_file_name = 'model_test_%s.csv' % id\n save_path = os.path.join(save_dir, save_file_name)\n df = pd.read_csv(save_path, index_col=0)\n \n save_path_units = os.path.join(save_dir, 'model_test_units.csv')\n units = pd.read_csv(save_path_units,index_col=0).transpose().iloc[0]\n return df,units\n```\n\n\n```python\nfig,axes=plt.subplots(nrows=len(df_rolldecays))\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n df, units = load_run(id=id) \n df.plot(y='phi', ax=ax)\n ax.set_ylabel(f\"roll [{units['phi']}]\")\n ax.grid(True)\n ax.set_ylim([-0.2,0.2])\n \nplt.tight_layout()\n```\n\n## Analyze the damping\n\n\n```python\nlowpass_filter = LowpassFilterDerivatorTransformer(cutoff=1, minimum_score=0.999)\ncutter = CutTransformer(phi_max=np.deg2rad(15), phi_min=np.deg2rad(3.5), phi1d_start_tolerance=0.015)\noffset_transformer = OffsetTransformer()\n```\n\n\n```python\nestimator_cubic = EstimatorCubic(fit_method='derivation')\n```\n\n\n```python\nsteps = [\n ('filter',lowpass_filter),\n ('cutter', cutter), \n# ('offset_transformer',offset_transformer),\n ('estimator', estimator_cubic)\n]\n\npipline_cubic = Pipeline(steps=steps)\n```\n\n### Cubic\n\n\n```python\nmodels_cubic_int = OrderedDict()\nscores = pd.DataFrame()\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n df, units = load_run(id=id)\n \n estimator_cubic_der = EstimatorQuadratic(fit_method='derivation', maxfev=100000)\n steps = [\n ('filter',lowpass_filter),\n ('cutter', cutter), \n ('estimator', estimator_cubic_der)\n ]\n pipline_cubic_der = Pipeline(steps=steps)\n pipline_cubic_der.fit(X=df[['phi']])\n \n estimator_cubic_int = EstimatorQuadratic(fit_method='integration', maxfev=100000, \n p0=estimator_cubic_der.parameters)\n steps = [\n ('filter',lowpass_filter),\n ('cutter', cutter), \n ('estimator', estimator_cubic_int)\n ]\n pipline_cubic_int = Pipeline(steps=steps)\n pipline_cubic_int.fit(X=df[['phi']])\n \n scale_factor = row.scale_factor\n Disp = row.Volume/(scale_factor**3)\n meta_data = {\n 'Volume' : Disp,\n 'GM': row.gm/scale_factor,\n 'rho':1000,\n 'g':9.81,\n }\n result = estimator_cubic_int.result_for_database(meta_data=meta_data)\n \n scores.loc['models_quadratic_int',id] = pipline_cubic_int.score(X=df[['phi']])\n \n models_cubic_int[id]=deepcopy(pipline_cubic_int)\n```\n\n\n\n\n```python\nfig,ax=plt.subplots()\n\ncolors = ['r','g','b']\nmarkers = ['o','*','+']\n\nfor id, model in models_cubic_int.items():\n \n estimator = model['estimator']\n estimator.plot_damping(ax=ax)\n \nfig,ax=plt.subplots()\nfor id, model in models_cubic_int.items():\n \n estimator = model['estimator']\n estimator.plot_omega0(ax=ax, include_model_test=True)\n```\n\n\n```python\nscores\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
213372133821340
models_quadratic_int0.999970.9999420.999966
\n
\n\n\n\n## Save models\n\n\n```python\nfor name, model in models_cubic_int.items():\n joblib.dump(model, '../../models/KVLCC2_%i.pkl' % name)\n```\n", "meta": {"hexsha": "a7639404a859d85c3a86a663109f891bf4192e81", "size": 189080, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "reports/ISOPE_outline/00.6_KLVCC2_model_tests.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "reports/ISOPE_outline/00.6_KLVCC2_model_tests.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reports/ISOPE_outline/00.6_KLVCC2_model_tests.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 190.0301507538, "max_line_length": 55744, "alphanum_fraction": 0.8709382272, "converted": true, "num_tokens": 5197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.3475470179294237}} {"text": "# Section 0 问题描述与完成项目流程\n\n## 1. 问题描述\n\n\n\n\n在该项目中,你将使用强化学习算法,实现一个自动走迷宫机器人。\n\n1. 如上图所示,智能机器人显示在右上角。在我们的迷宫中,有陷阱(红色炸弹)及终点(蓝色的目标点)两种情景。机器人要尽量避开陷阱、尽快到达目的地。\n2. 小车可执行的动作包括:向上走 `u`、向右走 `r`、向下走 `d`、向左走 `l`。\n3. 执行不同的动作后,根据不同的情况会获得不同的奖励,具体而言,有以下几种情况。\n - 撞到墙壁:-10\n - 走到终点:50\n - 走到陷阱:-30\n - 其余情况:-0.1\n4. 我们需要通过修改 `robot.py` 中的代码,来实现一个 Q Learning 机器人,实现上述的目标。\n\n## 2. 完成项目流程\n\n1. 配置环境,使用 `envirnment.yml` 文件配置名为 `robot-env` 的 conda 环境,具体而言,你只需转到当前的目录,在命令行/终端中运行如下代码,稍作等待即可。\n```\nconda env create -f envirnment.yml\n```\n安装完毕后,在命令行/终端中运行 `source activate robot-env`(Mac/Linux 系统)或 `activate robot-env`(Windows 系统)激活该环境。\n\n2. 阅读 `main.ipynb` 中的指导完成项目,并根据指导修改对应的代码,生成、观察结果。\n3. 导出代码与报告,上传文件,提交审阅并优化。\n---\n\n---\n\n# Section 1 算法理解\n\n\n## 1. 1 强化学习总览\n\n强化学习作为机器学习算法的一种,其模式也是让智能体在“训练”中学到“经验”,以实现给定的任务。但不同于监督学习与非监督学习,在强化学习的框架中,我们更侧重通过智能体与环境的**交互**来学习。通常在监督学习和非监督学习任务中,智能体往往需要通过给定的训练集,辅之以既定的训练目标(如最小化损失函数),通过给定的学习算法来实现这一目标。然而在强化学习中,智能体则是通过其与环境交互得到的奖励进行学习。这个环境可以是虚拟的(如虚拟的迷宫),也可以是真实的(自动驾驶汽车在真实道路上收集数据)。\n\n\n在强化学习中有五个核心组成部分,它们分别是:**环境(Environment)**、**智能体(Agent)**、**状态(State)**、**动作(Action)**和**奖励(Reward)**。在某一时间节点 $t$:\n \n- 智能体在从环境中感知其所处的状态 $s_t$\n- 智能体根据某些准则选择动作 $a_t$\n- 环境根据智能体选择的动作,向智能体反馈奖励 $r_{t+1}$\n\n通过合理的学习算法,智能体将在这样的问题设置下,成功学到一个在状态 $s_t$ 选择动作 $a_t$ 的策略 $\\pi (s_t) = a_t$。\n\n---\n\n**问题 1**:请参照如上的定义,描述出 “机器人走迷宫这个问题” 中强化学习五个组成部分对应的实际对象:\n\n- **环境** : 有陷阱的迷宫\n- **状态** : 机器人在迷宫中的位置\n\n\n- **动作** : 机器人选择向上走 u、向右走 r、向下走 d、向左走 l\n- **奖励** : 撞到墙壁:-10,走到终点:50,走到陷阱:-30,其余情况:-0.1\n\n$$T(s^{'}, a, s) = P(s^{'}|a,s)$$\n\n\n---\n\n## 1.2 计算 Q 值 \n\n在我们的项目中,我们要实现基于 Q-Learning 的强化学习算法。Q-Learning 是一个值迭代(Value Iteration)算法。与策略迭代(Policy Iteration)算法不同,值迭代算法会计算每个”状态“或是”状态-动作“的值(Value)或是效用(Utility),然后在执行动作的时候,会设法最大化这个值。因此,对每个状态值的准确估计,是我们值迭代算法的核心。通常我们会考虑**最大化动作的长期奖励**,即不仅考虑当前动作带来的奖励,还会考虑动作长远的奖励。\n\n在 Q-Learning 算法中,我们把这个长期奖励记为 Q 值,我们会考虑每个 ”状态-动作“ 的 Q 值,具体而言,它的计算公式为:\n\n$$\nq(s_{t},a) = R_{t+1} + \\gamma \\times\\max_a q(a,s_{t+1})\n$$\n\n也就是对于当前的“状态-动作” $(s_{t},a)$,我们考虑执行动作 $a$ 后环境给我们的奖励 $R_{t+1}$,以及执行动作 $a$ 到达 $s_{t+1}$后,执行任意动作能够获得的最大的Q值 $\\max_a q(a,s_{t+1})$,$\\gamma$ 为折扣因子。\n\n不过一般地,我们使用更为保守地更新 Q 表的方法,即引入松弛变量 $alpha$,按如下的公式进行更新,使得 Q 表的迭代变化更为平缓。\n\n$$\nq(s_{t},a) = (1-\\alpha) \\times q(s_{t},a) + \\alpha \\times(R_{t+1} + \\gamma \\times\\max_a q(a,s_{t+1}))\n$$\n\n\n\n---\n\n\n**问题 2**:根据已知条件求 $q(s_{t},a)$,在如下模板代码中的空格填入对应的数字即可。\n\n\n已知:如上图,机器人位于 $s_1$,行动为 `u`,行动获得的奖励与题目的默认设置相同。在 $s_2$ 中执行各动作的 Q 值为:`u`: -24,`r`: -13,`d`: -0.29、`l`: +40,$\\gamma$ 取0.9。\n\n\n$$\n\\begin{align}\nq(s_{t},a) & = R_{t+1} + \\gamma \\times\\max_a q(a,s_{t+1}) \\\\\n & =(-0.1) + (0.9)*(40) \\\\\n & =(35.9)\n\\end{align}\n$$\n\n\n---\n\n## 1.3 如何选择动作\n\n在强化学习中,「探索-利用」问题是非常重要的问题。具体来说,根据上面的定义,我们会尽可能地让机器人在每次选择最优的决策,来最大化长期奖励。但是这样做有如下的弊端:\n1. 在初步的学习中,我们的 Q 值会不准确,如果在这个时候都按照 Q 值来选择,那么会造成错误。\n2. 学习一段时间后,机器人的路线会相对固定,则机器人无法对环境进行有效的探索。\n\n因此我们需要一种办法,来解决如上的问题,增加机器人的探索。由此我们考虑使用 epsilon-greedy 算法,即在小车选择动作的时候,以一部分的概率随机选择动作,以一部分的概率按照最优的 Q 值选择动作。同时,这个选择随机动作的概率应当随着训练的过程逐步减小。\n\n---\n\n**问题 3**:在如下的代码块中,实现 epsilon-greedy 算法的逻辑,并运行测试代码。\n\n\n```python\nimport random\nimport numpy as np\n\nactions = ['u','r','d','l']\nqline = {'u':1.2, 'r':-2.1, 'd':-24.5, 'l':27}\nepsilon = 0.3 # 以0.3的概率进行随机选择\n\ndef epsilon_greedy_probs(Q_s, epsilon, nA):\n \"\"\" obtains the action probabilities corresponding to epsilon-greedy policy \"\"\"\n policy_s = np.ones(nA) * epsilon / nA\n best_a = np.argmax(Q_s)\n policy_s[best_a] = 1 - epsilon + (epsilon / nA)\n return policy_s\n\n\ndef choose_action(epsilon):\n \n action = None\n if epsilon < random.random(): # 以某一概率\n #pass # 实现对动作的随机选择\n p = np.random.choice(np.arange(len(actions)), p=epsilon_greedy_probs(qline, epsilon, len(actions)))\n action = actions[p]\n else: \n #pass # 否则选择具有最大 Q 值的动作\n action = max(qline,key=qline.get)\n return action\n\n```\n\n---\n\n---\n\n# Section 2 代码实现\n\n## 2.1. `Maze` 类理解\n\n我们首先引入了迷宫类 `Maze`,这是一个非常强大的函数,它能够根据你的要求随机创建一个迷宫,或者根据指定的文件,读入一个迷宫地图信息。\n\n1. 使用 `Maze(\"file_name\")` 根据指定文件创建迷宫,或者使用 `Maze(maze_size=(height,width))` 来随机生成一个迷宫。\n2. 使用 `trap_number` 参数,在创建迷宫的时候,设定迷宫中陷阱的数量。\n3. 直接键入迷宫变量的名字按回车,展示迷宫图像(如 `g=Maze(\"xx.txt\")`,那么直接输入 `g` 即可。\n4. 建议生成的迷宫尺寸,长在 6~12 之间,宽在 10~12 之间。\n\n---\n\n**问题 4**:在如下的代码块中,创建你的迷宫并展示。\n\n\n```python\nfrom Maze import Maze\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\n## todo: 创建迷宫并展示\nmm = Maze(maze_size=(10,12),trap_number=6)\nmm\n```\n\n---\n\n你可能已经注意到,在迷宫中我们已经默认放置了一个机器人。实际上,我们为迷宫配置了相应的 API,来帮助机器人的移动与感知。其中你随后会使用的两个 API 为 `maze.sense_robot()` 及 `maze.move_robot()`。\n\n1. `maze.sense_robot()` 为一个无参数的函数,输出机器人在迷宫中目前的位置。\n2. `maze.move_robot(direction)` 对输入的移动方向,移动机器人,并返回对应动作的奖励值。\n\n---\n\n**问题 5**:随机移动机器人,并记录下获得的奖励,展示出机器人最后的位置。\n\n\n```python\nrewards = []\n\n## 循环、随机移动机器人10次,记录下奖励\nfor i in range(10):\n rewards.append(mm.move_robot(choose_action(i)))\n \n\n## 输出机器人最后的位置\nprint(mm.sense_robot())\nprint(rewards)\n\n## 打印迷宫,观察机器人位置\nmm\n```\n\n## 2.2. `Robot` 类实现\n\n`Robot` 类是我们需要重点实现的部分。在这个类中,我们需要实现诸多功能,以使得我们成功实现一个强化学习智能体。总体来说,之前我们是人为地在环境中移动了机器人,但是现在通过实现 `Robot` 这个类,机器人将会自己移动。通过实现学习函数,`Robot` 类将会学习到如何选择最优的动作,并且更新强化学习中对应的参数。\n\n首先 `Robot` 有多个输入,其中 `alpha=0.5, gamma=0.9, epsilon0=0.5` 表征强化学习相关的各个参数的默认值,这些在之前你已经了解到,`Maze` 应为机器人所在迷宫对象。\n\n随后观察 `Robot.update` 函数,它指明了在每次执行动作时,`Robot` 需要执行的程序。按照这些程序,各个函数的功能也就明了了。\n\n最后你需要实现 `Robot.py` 代码中的8段代码,他们都在代码中以 `#TODO` 进行标注,你能轻松地找到他们。\n\n---\n\n**问题 6**:实现 `Robot.py` 中的8段代码,并运行如下代码检查效果(记得将 `maze` 变量修改为你创建迷宫的变量名)。\n\n\n\n\n```python\nfrom Robot import Robot\nrobot = Robot(mm) # 记得将 maze 变量修改为你创建迷宫的变量名\nrobot.set_status(learning=True,testing=False)\nprint(robot.update())\n\nmm\n```\n\n---\n\n## 2.3 用 `Runner` 类训练 Robot\n\n在实现了上述内容之后,我们就可以开始对我们 `Robot` 进行训练并调参了。我们为你准备了又一个非常棒的类 `Runner`,来实现整个训练过程及可视化。使用如下的代码,你可以成功对机器人进行训练。并且你会在当前文件夹中生成一个名为 `filename` 的视频,记录了整个训练的过程。通过观察该视频,你能够发现训练过程中的问题,并且优化你的代码及参数。\n\n---\n\n**问题 7**:尝试利用下列代码训练机器人,并进行调参。可选的参数包括:\n\n- 训练参数\n - 训练次数 `epoch`\n- 机器人参数:\n - `epsilon0` (epsilon 初值)\n - `epsilon`衰减(可以是线性、指数衰减,可以调整衰减的速度),你需要在 Robot.py 中调整\n - `alpha`\n - `gamma`\n- 迷宫参数:\n - 迷宫大小\n - 迷宫中陷阱的数量\n\n\n```python\n## 可选的参数:\nepoch = 20\n\nepsilon0 = 0.5\nalpha = 0.5\ngamma = 0.9\n\nmaze_size = (6,6)\ntrap_number = 1\n```\n\n\n```python\nfrom Runner import Runner\n%matplotlib inline\n\ng = Maze(maze_size=maze_size,trap_number=trap_number)\nr1 = Robot(g,alpha=0.5, epsilon0=0.5, gamma=0.9)\nr2 = Robot(g,alpha=0.01, epsilon0=0.5, gamma=0.9)\nr3 = Robot(g,alpha=0.5, epsilon0=0.01, gamma=0.9)\nr4 = Robot(g,alpha=0.5, epsilon0=0.5, gamma=0.1)\nr1.set_status(learning=True)\nr2.set_status(learning=True)\nr3.set_status(learning=True)\nr4.set_status(learning=True)\n\nrunner1 = Runner(r1, g)\nrunner2 = Runner(r2, g)\nrunner3 = Runner(r3, g)\nrunner4 = Runner(r4, g)\nrunner1.run_training(epoch, display_direction=True)\nrunner2.run_training(epoch, display_direction=True)\nrunner3.run_training(epoch, display_direction=True)\nrunner4.run_training(epoch, display_direction=True)\n#runner.generate_movie(filename = \"final1.mp4\") # 你可以注释该行代码,加快运行速度,不过你就无法观察到视频了。\n```\n\n---\n\n使用 `runner.plot_results()` 函数,能够打印机器人在训练过程中的一些参数信息。\n\n- Success Times 代表机器人在训练过程中成功的累计次数,这应当是一个累积递增的图像。\n- Accumulated Rewards 代表机器人在每次训练 epoch 中,获得的累积奖励的值,这应当是一个逐步递增的图像。\n- Running Times per Epoch 代表在每次训练 epoch 中,小车训练的次数(到达终点就会停止该 epoch 转入下次训练),这应当是一个逐步递减的图像。\n\n---\n\n**问题 8**:使用 `runner.plot_results()` 输出训练结果,根据该结果对你的机器人进行分析。\n\n- 指出你选用的参数如何,选用参数的原因。\n- 建议你比较不同参数下机器人的训练的情况。\n- 训练的结果是否满意,有何改进的计划。\n\n\n```python\nrunner1.plot_results()\nrunner2.plot_results()\nrunner3.plot_results()\nrunner4.plot_results()\n```\n\n(回答区)\nepsilon0:epsilon-greedy 算法中的epsilon值,表示随机选择动作概率\nalpha:当前知识权重,alpha越大,当前知识对策略影响越大,之前知识影响越小\ngamma:为折扣因子,表示执行动作s(t+1)状态后,执行任意动作能够获得的最大的Q值对当前Q值影响程度,gamma越大,对当前Q值影响越大\n\n\n对比上图,alpha较小时,Runtime比较大,训练需要更长时间;epsilon0较低,按照已经学到的qtable执行,前期训练可能会出现转圈,达不到终点;gamma较小,终点处的正奖励不能够“扩散”到周围,机器人很有可能无法学习到一个到达终点的策略\n\n\n对于epsilon0 = 0.5,alpha = 0.5,gamma = 0.9,曲线比较平滑,效果较好。\n\n---\n\n**问题 9:** 请将如下的文件打包,提交文件给审阅者。\n\n- `robot.py`\n- `robot_maze.ipynb`\n- 由 `robot_maze.ipynb` 导出的 `robot_maze.html`\n", "meta": {"hexsha": "5c28c5fb8d9f7f6040a1bee261a52210fc4f9992", "size": 608183, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "qlearning_maze/robot_maze.ipynb", "max_stars_repo_name": "user-ZJ/Reinforcement-Learning", "max_stars_repo_head_hexsha": "696544d60b94e69141d33c41c0700023e0b342a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-07T07:58:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-07T07:58:08.000Z", "max_issues_repo_path": "qlearning_maze/robot_maze.ipynb", "max_issues_repo_name": "user-ZJ/Reinforcement-Learning", "max_issues_repo_head_hexsha": "696544d60b94e69141d33c41c0700023e0b342a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qlearning_maze/robot_maze.ipynb", "max_forks_repo_name": "user-ZJ/Reinforcement-Learning", "max_forks_repo_head_hexsha": "696544d60b94e69141d33c41c0700023e0b342a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 941.459752322, "max_line_length": 88856, "alphanum_fraction": 0.9544396999, "converted": true, "num_tokens": 5035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.3474975502372993}} {"text": "# DIY ZHL\n\n## References etc.\n\n * Mark Powell's \"Deco for Divers\" has all the background information in a succinct and easy to read form. The book should be available on interlibrary loan, ask your librarian.\n \n * Erik Baker's papers: \"Decolessons\", \"Understanding M-values\", \"Clearing up the confusion about Deep Stops\", are more technical and tend to omit much of the background info. PDFs are freely available on-line from several sources.\n \n * Buhlmann's \"Decompression - Decompression sickness\".\n \n * Several open-source implementations are out there, most notable Subsurface software, but you have to read C.\n \n * Plenty of other on-line sources, e.g. Stuart Morrison's \"DIY Decompresion\"\n\n\n## Primer\n\n### Dissolved gas\n\nGas is driven in and out of tissue by the difference in pressure: \"outside\" aka ambient $ P_{amb} $   and \"inside\" aka dissolved gas pressure, $ P_{t} $. The rate is assumed to be $ ln(2) $\n\n**Partial pressure** refers to pressures of individual gases in the breathing mix: oxygen, nitrogen, etc.\n\n### Tissue compartments\n\nTo simulate real tissue the model uses hypothetical \"compartments\". They are defined by the time $ T_{ h } $ it takes for the pressure difference (above) to get to -- since we're using log 2 -- half (or double, depending on whether the tissues in on- or off-gassing) its intial value. That time is callled ``half time``. It is usually given in minutes.\n\nThe body is modelled as a set of \"tissue compartments\" with different half-times. They have nothing to do with real tissues, but to illustrate the concept it is usually said that blood is \"fast\": gas gets in and out very quickly, whereas bone is very \"slow\".\n\n### M-values\n\nThe greater the difference between $ P_{amb} $   and $ P_t $, the faster the gas flows. There is, however, such thing as too fast. To recreational divers \"too fast\" is only relevant on the way up.\n\nThe model defines \"maximum allowed pressure difference\" value, ``M-value`` for short. The model does not attempt to quantify the risk, it only works in binary \"above the M-value\" (bad) or \"below the M-value\" (OK) terms.\n\nHaldane originally set his M-value as a fixed ratio (2:1). Workman replaced it with a function: a straight line $ M = \\Delta M + M_0 $ with greater overpressure tolerated at greater depths.\n\n## Water vapour etc. in alveolae\n\nBreathing gas in respiratory passages is diluted with water vapour and expelled carbon dioxide. The fraction of water vapour and carbon dioxide is subtracted from the partial pressure of inert gas.\n\n$\n\\begin{align}\nP_{alv} = ( P_{amb} - P_{H_{2}O} + ( 1 - RQ ) / RQ * P_{CO_{2}} ) Q\n\\end{align}\n$\n\nwhere\n * $ P_{ CO_2 } $ is pressure of carbon dioxide, 40 mm Hg or 0.0534 bar,\n * $ RQ $ is respiratory quotient,\n * $ P_{ H_{2}O } $ is pressure of water vapour, 47 mm Hg or 0.0627 bar,\n * $ Q $ is the fraction of inert gas,\n * $ P_{amb} $ is ambient pressure.\n\n$ RQ $ is a ratio of oxygen consumed to carbon dioxide produced in metabolism, it depends on nutrition and exertion and is in the range 0.7..1. Smaller number results in greater calculated gas loading. Buhlmann uses 1 whereas Shreiner uses 0.8 and USN uses 0.9. \n\n## Schreiner equation to calculate inert gas pressure in a tissue compartment\n\n\n$\n\\begin{align}\nP_{t}(t) = P_{alv0} + R * (t - 1 / k) - (P_{alv0} - P_{t0} - R / k) * e^{-k * t}\n\\end{align}\n$\n\n*where*\n\n * $ P_{t}(t) $ : partial pressure of inert gas in the tissue (bar) at time $ t $\n \n * $ P_{alv0} $ : initial alveolar partial pressure of the gas in the breathing mix (bar)\n \n * $ P_{t0} $ : initial partial pressure of the gas in the tissue (bar) (at time $ t0 $)\n \n * $ R $ is rate of change in inert gas pressure in the breathing mix, bar/min. This is rate of change in ambient pressure, $ \\Delta P $ times fraction of inert gas. $ \\Delta P $ is negative for ascent, positive for descent, zero for constant depth.\n\n * $ t $ : time of exposure in minutes\n\n * $ k $ : gas decay constant for a tissue compartment: $ k = \\frac {\\ln(2)} {T_{h}} $\n\n * $ \\quad T_{h} $ : gas \"half-life\" time for tissue compartment in minutes\n\n * $ e $ : 2.7182818284590452353602874713527 and counting\n\nNote that for constant depth this reduces to a \"short form\" given in many sources, the code below just uses the full form with $ R = 0 $\n\n## M-values\n\n### Workman\n\nWorkman-style M-value $ M $ is defined in terms of $ \\Delta M $ and $ M_{ 0 } $, where\n\n * $ M_{0} $ is the surfacing M-value and\n * $ \\Delta M $ is the slope of M-value line: multiply by depth to get tha actual number at that depth.\n\n$ M = \\Delta M * Depth + M_{0} $\n\n\n$ Tolerated Depth = ( P - M_{0} ) / \\Delta M $\n\nwhere Depth is measured as pressure from sea level and Tolerated Depth is how high you can ascend without exceeding the M-value.\n\n### Buhlmann\n\nIn Buhlmann model the M-values are expresed in terms of two coeficients: $ a $ and $ b $. In addition, it is using absolute instead od sea-level pressure for diving at altitude, and comes with separate numbers for different inert gases. Buhlmann's model calls \"Tolerated Depth\" an \"ascent ceiling\".\n\n### Conversion\n\n * Workman to Buhlmann:\n \n * $ a = M_{0} - \\Delta M * P_{ \\text{ amb. (surface at sea level) }} $ \n \n * $ b = 1 / \\Delta M $ \n\n * Buhlmann to Workman:\n\n * $ \\Delta M = 1 / b $\n \n * $ M_{0} = a + \\frac { P_{ \\text{ amb. (surface at sea level) }}} { b } $\n \n**Note** that this only really works with $ \\Delta M $ greater than 1. See Erik Baker's \"M-values\" for the why.\n \n\n## No-stop time\n\n### by (variant of) Schreiner equation\n\nThis needs Workman-style M-values:\n\n$\n\\begin{align}\nP_{no-deco} \\ = ( M_{0} - P_{alv0} - R * (t_{asc} - 1/k) ) * e ^ {k * t_{asc}} \\ + P_{alv0} - R / k\n\\end{align}\n$\n * $ P_{no-deco} $   is the pressure at which ascent must be started (bar),\n * $ M_{0} $ is the surfacing M-value,\n * $ P_{alv0} $ is alveolar partial pressure (bar),\n * $ t_{asc} $ is the time needed for ascent (minutes): depth divided by speed.\n * $ R, k, e $ are the same as in Schreiner's equation above.\n \nYou have to figure out how long it'll take to get from the current inspired pressure $ P_{t} $ to $ P_{no-deco} $   : run `schreiner()` in a loop adding a minute of exposure on each iteration until you hit $ P_{no-deco} $   (or do a fancy binary search from, say, 99 minutes down, etc.)\n\n### by Buhlmann equation\n\nBuhlmann equation calculates Tolerated Depth in absolute pressure and calls it \"safe ascent ceiling\":\n\n$\n\\begin{align}\nP_{amb.tol.} = ( P_{t} - a ) * b\n\\end{align}\n$\n\nwhere\n * $ P_{amb.tol.} $   is the ascent ceiling,\n * $ P_{t} $ is current inert gas pressure in the tisue, and\n * $ a $ and $ b $ are Buhlmann's coefficients.\n\nWhen the calculated $ P_{amb.tol.} $   is above 1, i.e. under the water surface (assuming surface pressure is 1 bar of course), that means we have a deco ceiling and must stop and off-gas there.\n\nBuhlmann equation modified by Erik Baker's Gradient Factors is\n\n$\n\\begin{align}\nP_{amb.tol.} = ( P_{t} - a * GF ) / ( GF / b + 1.0 - GF )\n\\end{align}\n$\n\nwhere $ GF $ is the \"current\" gradient factor. \n\n(Without the gradient factor: $ GF = 1 $, that reduces to $ ( P_{t} - a * 1 ) / ( 1/b + 1 - 1 ) => ( P_{t} - a ) / ( 1/b ) => ( P_{t} - a ) * b $: Buhlmann's original.)\n\nGradient Factors plural are a pair of numbers: $ GFLo $ that applies at first decompression stop and $ GFHi $ that applies at the last stop: the surface. The \"current\" $ GF $ at any given depth between those two points is calculated from a simple proportion. **Note** that this only works when you have a relatively deep decompression stop.\n\n### You can calculate no-stop time\nby running `shreiner()` and `buhlmann()` in a loop, adding a minute of exposure at each iteration, until the latter produces a ceiling. **Note** however, that neither this method nor the equation above factor in off-gassing that will take place during ascent.\n\n### Helium\n\nWith multiple inert gases, each has to be tracked separately by Schreiner equation.\n\nFor Buhlmann's formula you add up the partial pressures and proportionally adjust the $ a $ and $ b $:\n\n$ P_{t} = P_{iN_2} + P_{iHe} $\n\n$ a = (a_{N_2} * P_{N_2} + a_{He} * P_{He}) / P_{t} $\n\n$ b = (b_{N_2} * P_{N_2} + b_{He} * P_{He}) / P_{t} $\n\n\n\n## Decompression stop\n\n... is ascent ceiling rounded to next 3 metres down.\n\nThe best I could find, in Buhlmann's \"Decompression\", is in open water it's hard to maintain stops at smaller intervals. Buhlmann suggests using smaller intervals or even \"ride the M-value line\" continuously for in-chamber decompression there. (**Note** this assumes no gas switching.)\n\nOnce you're at deco stop, run `schreiner()` and `buhlmann()` in a loop adding a minute on each iteration, as usual, until your next ceiling is at your next stop: 3 metres above you current depth if using the 3 m spacing.\n\n## Tissue compartments\n\nTables are coded as python dicts: keys for each compartment are ``t``, ``a``, and ``b`` for half-time and the coefficients resp. E.g. ZH-L12's $ b $ coefficient for nitrogen in TC 3 is ``ZHL12N[3][\"b\"]``\n\n\n### ZH-L16\n\n**Note** that you have two options for the 1st (fastest) tissue compartment: 4 minutes or 5. Pick one. The 5-minute TC is usually called \"1b\" and is keyed as \"1.1\" in the table below.\n\nThe ''a'' key in the nitrogen tables is a dict itself with three sub-keys: ''A'', ''B'', adn ''C'' for the three versions of ZH-L16 resp. Helium numbers seem to be unobtainable for ''A'' or ''C'', nor for the 4-minute tissue compartment. I.e. if you want to use this for trimix, ZH-L16B with 5-minute TC is your only option.\n\nM-values for \"-A\" were calculated as\n\n$\n\\begin{align}\na = 2 * T_{h} ^ {- \\frac{1}{3}}\n\\end{align}\n$\n\n$\n\\begin{align}\nb = 1.005 - T_{h} ^ {- \\frac{1}{2}}\n\\end{align}\n$\n\n\n * $ T_{h} $ is tissue compartment half-time\n\n\n### Workman\n\nNot useful as is, would need to be recalculated for $ \\Delta M $ instead of $ M $ first, then converted to Buhlmann's `a` and `b` coefficients.\n\n### DSAT\n\nConvert to Buhlmann's `a` and `b` using $ \\Delta M = 1 $\n\n## Code\n\nRun the cell below to load python code (assuming you have the `diyzhl.py` in the same directory as the notebook file).\n\nThe functions are written to closely follow the above formulae. That includes calculating constants on the fly, like e.g. $ K $ or $ P_{alv} $   -- you'd normally use pre-calculated numbers for your chosen parameters.\n\nAbout the only added features are \n * some of them save intermediate results in variables: mainly because I wanted to play with rounding at different steps. Note that although I round the numbers to 4 decimal digits, they're probably only meaningful to 2 at best.\n \n * Typecasts to `float` are there so that passing in not-a-number will throw an exception early. \n \n * Similarly, `asserts` are used to catch division by zero early.\n\n\n```python\n# %load diyzhl.py\n#!/usr/bin/python -u\n#\n# (K) Copy Rites Reversed: reuse what you like (but give credit)\n#\n# Credits:\n#\n# Mark Powell's \"Deco for Divers\"\n# Erik Baker's papers: \"Decolessons\", \"Understanding M-values\", and \"Clearing up the confusion about Deep Stops\" in particular\n# Buhlmann's \"Decompression - Decompression Sickness\", English edition\n# Several open-source implementations, most notably Subsurface software (and people, Robert in particular)\n# Plenty of other on-line sources, e.g. Stuart Morrison's \"DIY Decompresion\"\n#\n# The goal here is \"by the book\" implementation to use for learning this stuff.\n# There's a lot of things that can be done differently, more efficeint, and so on... and\n# that's not what this code is for.\n#\n\nimport sys\nimport math\n\n# ZH-L12 from \"Decompression\"\n#\nZHL12N = {\n 1 : { \"t\" : 2.65, \"a\" : 2.2, \"b\" : 0.82 },\n 2 : { \"t\" : 7.94, \"a\" : 1.5, \"b\" : 0.82 },\n 3 : { \"t\" : 12.2, \"a\" : 1.08, \"b\" : 0.825 },\n 4 : { \"t\" : 18.5, \"a\" : 0.9, \"b\" : 0.835 },\n 5 : { \"t\" : 26.5, \"a\" : 0.75, \"b\" : 0.845 },\n 6 : { \"t\" : 37.0, \"a\" : 0.58, \"b\" : 0.86 },\n 7 : { \"t\" : 53.0, \"a\" : 0.47, \"b\" : 0.87 },\n 8 : { \"t\" : 79.0, \"a\" : 0.45, \"b\" : 0.89 },\n 9 : { \"t\" : 114.0, \"a\" : 0.45, \"b\" : 0.89 },\n 10 : { \"t\" : 146.0, \"a\" : 0.455, \"b\" : 0.934 },\n 11 : { \"t\" : 185.0, \"a\" : 0.455, \"b\" : 0.934 },\n 12 : { \"t\" : 238.0, \"a\" : 0.38, \"b\" : 0.944 },\n 13 : { \"t\" : 304.0, \"a\" : 0.255, \"b\" : 0.962 },\n 14 : { \"t\" : 397.0, \"a\" : 0.255, \"b\" : 0.962 },\n 15 : { \"t\" : 503.0, \"a\" : 0.255, \"b\" : 0.962 },\n 16 : { \"t\" : 635.0, \"a\" : 0.255, \"b\" : 0.962 }\n}\n\nZHL12He = {\n 1 : { \"t\" : 1.0, \"a\" : 2.2, \"b\" : 0.82 },\n 2 : { \"t\" : 3.0, \"a\" : 1.5, \"b\" : 0.82 },\n 3 : { \"t\" : 4.6, \"a\" : 1.08, \"b\" : 0.825 },\n 4 : { \"t\" : 7.0, \"a\" : 0.9, \"b\" : 0.835 },\n 5 : { \"t\" : 10.0, \"a\" : 0.75, \"b\" : 0.845 },\n 6 : { \"t\" : 14.0, \"a\" : 0.58, \"b\" : 0.86 },\n 7 : { \"t\" : 20.0, \"a\" : 0.47, \"b\" : 0.87 },\n 8 : { \"t\" : 30.0, \"a\" : 0.45, \"b\" : 0.89 },\n 9 : { \"t\" : 43.0, \"a\" : 0.45, \"b\" : 0.89 },\n 10 : { \"t\" : 55.0, \"a\" : 0.515, \"b\" : 0.926 },\n 11 : { \"t\" : 70.0, \"a\" : 0.515, \"b\" : 0.926 },\n 12 : { \"t\" : 90.0, \"a\" : 0.515, \"b\" : 0.926 },\n 13 : { \"t\" : 115.0, \"a\" : 0.515, \"b\" : 0.926 },\n 14 : { \"t\" : 150.0, \"a\" : 0.515, \"b\" : 0.926 },\n 15 : { \"t\" : 190.0, \"a\" : 0.515, \"b\" : 0.926 },\n 16 : { \"t\" : 240.0, \"a\" : 0.515, \"b\" : 0.926 },\n}\n\n# ZH_L16: several sources incl. a photo of a page from Tauchmedizin @\n# http://www.nigelhewitt.co.uk/stuff/aab.jpg\n# It appears nobody has Helium numbers for \"-A\" and \"-C\", nor for the 4-minute TC\n# 5-minute TC is keyed as 1.1\n#\nZHL16N = {\n 1 : { \"t\" : 4.0, \"b\" : 0.505, \"a\" : { \"A\" : 1.2599, \"B\" : 1.2599, \"C\" : 1.2599 } },\n 1.1 : { \"t\" : 5.0, \"b\" : 0.5578, \"a\" : { \"A\" : 1.1696, \"B\" : 1.1696, \"C\" : 1.1696 } },\n 2 : { \"t\" : 8.0, \"b\" : 0.6514, \"a\" : { \"A\" : 1.0, \"B\" : 1.0, \"C\" : 1.0 } },\n 3 : { \"t\" : 12.5, \"b\" : 0.7222, \"a\" : { \"A\" : 0.8618, \"B\" : 0.8618, \"C\" : 0.8618 } },\n 4 : { \"t\" : 18.5, \"b\" : 0.7825, \"a\" : { \"A\" : 0.7562, \"B\" : 0.7562, \"C\" : 0.7562 } },\n 5 : { \"t\" : 27.0, \"b\" : 0.8126, \"a\" : { \"A\" : 0.6667, \"B\" : 0.6667, \"C\" : 0.62 } },\n 6 : { \"t\" : 38.3, \"b\" : 0.8434, \"a\" : { \"A\" : 0.5933, \"B\" : 0.56, \"C\" : 0.5043 } },\n 7 : { \"t\" : 54.3, \"b\" : 0.8693, \"a\" : { \"A\" : 0.5282, \"B\" : 0.4947, \"C\" : 0.441 } },\n 8 : { \"t\" : 77.0, \"b\" : 0.891, \"a\" : { \"A\" : 0.4701, \"B\" : 0.45, \"C\" : 0.4 } },\n 9 : { \"t\" : 109.0, \"b\" : 0.9092, \"a\" : { \"A\" : 0.4187, \"B\" : 0.4187, \"C\" : 0.375 } },\n 10 : { \"t\" : 146.0, \"b\" : 0.9222, \"a\" : { \"A\" : 0.3798, \"B\" : 0.3798, \"C\" : 0.35 } },\n 11 : { \"t\" : 187.0, \"b\" : 0.9319, \"a\" : { \"A\" : 0.3497, \"B\" : 0.3497, \"C\" : 0.3295 } },\n 12 : { \"t\" : 239.0, \"b\" : 0.9403, \"a\" : { \"A\" : 0.3223, \"B\" : 0.3223, \"C\" : 0.3065 } },\n 13 : { \"t\" : 305.0, \"b\" : 0.9477, \"a\" : { \"A\" : 0.2971, \"B\" : 0.285, \"C\" : 0.2835 } },\n 14 : { \"t\" : 390.0, \"b\" : 0.9544, \"a\" : { \"A\" : 0.2737, \"B\" : 0.2737, \"C\" : 0.261 } },\n 15 : { \"t\" : 498.0, \"b\" : 0.9602, \"a\" : { \"A\" : 0.2523, \"B\" : 0.2523, \"C\" : 0.248 } },\n 16 : { \"t\" : 635.0, \"b\" : 0.9653, \"a\" : { \"A\" : 0.2327, \"B\" : 0.2327, \"C\" : 0.2327 } }\n}\n\nZHL16He = {\n 1.1 : { \"t\" : 1.88, \"a\" : { \"B\" : 1.6189 }, \"b\" : 0.477 },\n 2 : { \"t\" : 3.02, \"a\" : { \"B\" : 1.383 }, \"b\" : 0.5747 },\n 3 : { \"t\" : 4.72, \"a\" : { \"B\" : 1.1919 }, \"b\" : 0.6527 },\n 4 : { \"t\" : 6.99, \"a\" : { \"B\" : 1.0458 }, \"b\" : 0.7223 },\n 5 : { \"t\" : 10.21, \"a\" : { \"B\" : 0.922 }, \"b\" : 0.7582 },\n 6 : { \"t\" : 14.48, \"a\" : { \"B\" : 0.8205 }, \"b\" : 0.7957 },\n 7 : { \"t\" : 20.53, \"a\" : { \"B\" : 0.7305 }, \"b\" : 0.8279 },\n 8 : { \"t\" : 29.11, \"a\" : { \"B\" : 0.6502 }, \"b\" : 0.8553 },\n 9 : { \"t\" : 41.20, \"a\" : { \"B\" : 0.595 }, \"b\" : 0.8757 },\n 10 : { \"t\" : 55.19, \"a\" : { \"B\" : 0.5545 }, \"b\" : 0.8903 },\n 11 : { \"t\" : 70.69, \"a\" : { \"B\" : 0.5333 }, \"b\" : 0.8997 },\n 12 : { \"t\" : 90.34, \"a\" : { \"B\" : 0.5189 }, \"b\" : 0.9073 },\n 13 : { \"t\" : 115.29, \"a\" : { \"B\" : 0.5181 }, \"b\" : 0.9122 },\n 14 : { \"t\" : 147.42, \"a\" : { \"B\" : 0.5176 }, \"b\" : 0.9171 },\n 15 : { \"t\" : 188.24, \"a\" : { \"B\" : 0.5172 }, \"b\" : 0.9217 },\n 16 : { \"t\" : 240.03, \"a\" : { \"B\" : 0.5119 }, \"b\" : 0.9267 }\n}\n\n# From Deco for Divers\n# Do not use: \n# need to convert to bar and delta-M to use,\n# M0 is in msw and M calculated as Delta M * Depth + M0,\n# Depth is unknown\n#\nWORKMAN = {\n 1 : { \"t\" : 5.0, \"M0\" : 31.5, \"M\" : 1.8 },\n 2 : { \"t\" : 10.0, \"M0\" : 26.8, \"M\" : 1.6 },\n 3 : { \"t\" : 20.0, \"M0\" : 21.9, \"M\" : 1.5 },\n 4 : { \"t\" : 40.0, \"M0\" : 17.0, \"M\" : 1.4 },\n 5 : { \"t\" : 80.0, \"M0\" : 16.4, \"M\" : 1.3 },\n 6 : { \"t\" : 120.0, \"M0\" : 15.8, \"M\" : 1.2 },\n 7 : { \"t\" : 160.0, \"M0\" : 15.5, \"M\" : 1.15 },\n 8 : { \"t\" : 200.0, \"M0\" : 15.5, \"M\" : 1.1 },\n 9 : { \"t\" : 240.0, \"M0\" : 15.2, \"M\" : 1.1 }\n}\n\n# Also from Deco for Divers\n#\n# Since DSAT's primary concern is no-stop diving, it only uses M0\n# -- there is no Delta M i.e. Delta M = 1\n# values are in msw\n#\n# Conveert to Buhlmann with\n# m_w2b( M0 = NNN / 10, dM = 1, P = 1 )\n# and run ZHL with DSAT compartments and M-values\n#\nDSAT = {\n 1 : { \"t\" : 5.0, \"M0\" : 30.42 },\n 2 : { \"t\" : 10.0, \"M0\" : 25.37 },\n 3 : { \"t\" : 20.0, \"M0\" : 20.54 },\n 4 : { \"t\" : 30.0, \"M0\" : 18.34 },\n 5 : { \"t\" : 40.0, \"M0\" : 17.11 },\n 6 : { \"t\" : 60.0, \"M0\" : 15.79 },\n 7 : { \"t\" : 80.0, \"M0\" : 15.11 },\n 8 : { \"t\" : 100.0, \"M0\" : 14.69 },\n 9 : { \"t\" : 120.0, \"M0\" : 14.41 },\n 10 : { \"t\" : 160.0, \"M0\" : 14.06 },\n 11 : { \"t\" : 200.0, \"M0\" : 13.84 },\n 12 : { \"t\" : 240.0, \"M0\" : 13.69 },\n 13 : { \"t\" : 360.0, \"M0\" : 13.45 },\n 14 : { \"t\" : 480.0, \"M0\" : 13.33 }\n}\n\n# return alveolar inert gas pressure\n# with P amb = 1 bar, fraction of inert gas = 0.79, and RQ = 0.9\n# this should return 0.79 - 0.0567 = 0.7451 or 0.7452 dep. on where you round it\n#\ndef palv( Pamb = 1, Q = 0.79, RQ = 0.9 ) :\n assert float( RQ ) != 0.0\n vw = float( Pamb ) - 0.0627 + (1.0 - float( RQ )) / float( RQ ) * 0.0534\n return round( vw * float( Q ), 4 )\n\n# return k: constant for tissue compartment (min^-1)\n# Th : tissue compartment half-time in minutes\n# for 5-minute compartment it's 0.8452\n#\ndef kay( Th = 5 ) :\n assert float( Th ) > 0.0\n return round( math.log( 2 ) / float( Th ), 4 )\n\n# return rate of pressure change in bar/min\n# d0 : start pressure, bar\n# dt : end pressure, bar\n# t : time, min\n# Q : fraction of inert gas (same Q as in palv()\n#\ndef arr( d0 = 1.0, dt = 1.0, t = 1, Q = 0.79 ) :\n assert float( t ) > 0.0\n dP = (float( dt ) - float( d0 )) / float( t )\n rc = dP * float( Q )\n return round( rc, 4 )\n\n# Schreiner equation\n# Palv + R * (t - 1/k) - (Palv - Pi - R/k) * e^(-k * t)\n#\n# returns pressure in tissue compartment after time t at depth Pa & dP\n#\n# Pi: initial pressure of inert gas in tissue (bar)\n# Palv: initial pressure of inert gas in the lungs (bar, output of palv())\n# t: time (minutes)\\n\",\n# R: rate of pressure change (output of arr()),\n# k: gas decay constant (output of kay()\n#\n# (Intermediate variables b/c I was playing with rounding)\n#\n\ndef schreiner( Pi = 0.7451, Palv = 0.7451, t = 1, R = 0, k = 0.1386, verbose = False ) :\n\n assert float( k ) != 0.0\n x1 = float( R ) * (float( t ) - 1.0 / float( k ))\n x2 = float( Palv ) - float( Pi ) - float( R ) / float( k )\n x3 = math.e ** (float( -k ) * float( t ))\n rc = round( float( Palv ) + x1 - x2 * x3, 4 )\n if verbose : sys.stdout.write( \"x1: %f, x2: %f, x3: %f, rc: %f\\n\" % (x1, x2, x3, rc,) )\n return round( rc, 4 )\n\n# M-value: workman to buhlmann\n# P is ambient pressure in bar\n# returns pair ( a, b )\n#\n# TODO: add GF\n#\ndef m_w2b( M0 = 2.9624, dM = 1.7928, P = 1 ) :\n assert float( dM ) >= 1.0\n a = float( M0 ) - float( dM ) * float( P )\n b = 1.0 / float( dM )\n return (round( a, 4 ), round( b, 4 ))\n\n# M-value: buhlmann to workman\n# returns pair ( M0, dM )\n#\ndef m_b2w( a = 1.1696, b = 0.5578, P = 1 ) :\n assert float( b ) > 0.0\n M0 = float( a ) + float( P ) / float( b )\n dM = 1.0 / float( b )\n return (round( M0, 4 ), round( dM, 4 ))\n\n# no-stop time by Schreiner\n#\n# Palv: initial pressure of inert gas in the lungs (bar, output of palv())\n# t: time (minutes)\\n\",\n# R: rate of pressure change (output of arr()),\n# k: gas decay constant (output of kay()\n# -- same as schreiner()\n# M0: surfacing M-value as per Workman\n#\ndef ndl( Palv = 0.7451, M0 = 2.9624, t = 0, R = 0, k = 0.1386, verbose = False ) :\n\n# (M0 - Palv - R * (t - 1/k)) * math.e ** (k * t) + Palv - R / k\n assert float( k ) != 0.0\n x1 = float( M0 ) - float( Palv ) - float( R ) * (float( t ) - 1.0 / float( k ))\n x2 = math.e ** (float( k ) * float( t ))\n rc = x1 * x2 + float( Palv ) - float( R ) / float( k )\n if verbose : sys.stdout.write( \"x1: %f, x2: %f, rc: %f\\n\" % (x1, x2, rc,) )\n return round( rc, 4 )\n\n# Buhlman formula with GF and Helium\n# returns safe ascent ceiling\n#\n# Pn is N2 pressure in tissue compartment\n# Phe is He pressure in tissue compartment\n# an is N2 a coefficient\n# bn is N2 b coefficient\n# ahe is He a coefficient\n# bhe is He b coefficient\n# gf is current gradient factor\n#\ndef buhlmann( Pn, an, bn, Phe = 0, ahe = 0, bhe = 0, gf = 1 ) :\n\n P = float( Pn ) + float( Phe )\n assert float( P ) != 0.0\n a = (float( an ) * float( Pn ) + float( ahe ) * float( Phe )) / P\n b = (float( bn ) * float( Pn ) + float( bhe ) * float( Phe )) / P\n num = float( P ) - float( a ) * float( gf )\n den = float( gf ) / float( b ) + 1.0 - float( gf )\n assert den != 0.0\n rc = num / den\n return round( rc, 4 )\n\n# eof\n#\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "33401c5be1d94e12f05c0e6ca4250e64b698d2e2", "size": 28537, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "diyzhl.ipynb", "max_stars_repo_name": "dmaziuk/diy-zhl", "max_stars_repo_head_hexsha": "79bc42ab184d65972baccba4274e0f06f3ec34d9", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2019-12-11T00:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-17T05:32:31.000Z", "max_issues_repo_path": "diyzhl.ipynb", "max_issues_repo_name": "dmaziuk/diy-zhl", "max_issues_repo_head_hexsha": "79bc42ab184d65972baccba4274e0f06f3ec34d9", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diyzhl.ipynb", "max_forks_repo_name": "dmaziuk/diy-zhl", "max_forks_repo_head_hexsha": "79bc42ab184d65972baccba4274e0f06f3ec34d9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-12-11T17:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T18:27:27.000Z", "avg_line_length": 45.5135566188, "max_line_length": 363, "alphanum_fraction": 0.4773101587, "converted": true, "num_tokens": 8508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.4921881357207956, "lm_q1q2_score": 0.3473790170707484}} {"text": "\n\n# Textual entailment classifier using an MLP plus attention \n\nIn textual entailment, \nthe input is 2 sentences (premise and hypothesis), and the output\nis a label, specifying if P entails H, P contradicts H, or neither.\n(This is also called \"natural language inference\".)\nWe use attention to align hypothesis to premise and vice versa,\nthen compare the aligned words to estimate similarity between the sentences, and pass the weighted similarities to an MLP.\n\n\nBased on sec 15.5 of http://d2l.ai/chapter_natural-language-processing-applications/natural-language-inference-attention.html\n\n\n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nnp.random.seed(seed=1)\nimport math\nimport collections\nimport os\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n!mkdir figures # for saving plots\n\n!wget https://raw.githubusercontent.com/d2l-ai/d2l-en/master/d2l/torch.py -q -O d2l.py\nimport d2l\n```\n\n mkdir: cannot create directory ‘figures’: File exists\n\n\n# Data\n\nWe use SNLI (Stanford Natural Language Inference) dataset described in sec 15.4 of http://d2l.ai/chapter_natural-language-processing-applications/natural-language-inference-and-dataset.html.\n\n\n```python\n\nimport re\n\nd2l.DATA_HUB['SNLI'] = ('https://nlp.stanford.edu/projects/snli/snli_1.0.zip',\n '9fcde07509c7e87ec61c640c1b2753d9041758e4')\n\ndata_dir = d2l.download_extract('SNLI')\n```\n\n Downloading ../data/snli_1.0.zip from https://nlp.stanford.edu/projects/snli/snli_1.0.zip...\n\n\n\n```python\ndef read_snli(data_dir, is_train):\n \"\"\"Read the SNLI dataset into premises, hypotheses, and labels.\"\"\"\n def extract_text(s):\n # Remove information that will not be used by us\n s = re.sub('\\\\(', '', s)\n s = re.sub('\\\\)', '', s)\n # Substitute two or more consecutive whitespace with space\n s = re.sub('\\\\s{2,}', ' ', s)\n return s.strip()\n\n label_set = {'entailment': 0, 'contradiction': 1, 'neutral': 2}\n file_name = os.path.join(\n data_dir, 'snli_1.0_train.txt' if is_train else 'snli_1.0_test.txt')\n with open(file_name, 'r') as f:\n rows = [row.split('\\t') for row in f.readlines()[1:]]\n premises = [extract_text(row[1]) for row in rows if row[0] in label_set]\n hypotheses = [extract_text(row[2]) for row in rows if row[0] in label_set]\n labels = [label_set[row[0]] for row in rows if row[0] in label_set]\n return premises, hypotheses, labels\n```\n\nShow first 3 training examples and their labels (“0”, “1”, and “2” correspond to “entailment”, “contradiction”, and “neutral”, respectively ).\n\n\n```python\ntrain_data = read_snli(data_dir, is_train=True)\nfor x0, x1, y in zip(train_data[0][:3], train_data[1][:3], train_data[2][:3]):\n print('premise:', x0)\n print('hypothesis:', x1)\n print('label:', y)\n```\n\n premise: A person on a horse jumps over a broken down airplane .\n hypothesis: A person is training his horse for a competition .\n label: 2\n premise: A person on a horse jumps over a broken down airplane .\n hypothesis: A person is at a diner , ordering an omelette .\n label: 1\n premise: A person on a horse jumps over a broken down airplane .\n hypothesis: A person is outdoors , on a horse .\n label: 0\n\n\n\n```python\ntest_data = read_snli(data_dir, is_train=False)\nfor data in [train_data, test_data]:\n print([[row for row in data[2]].count(i) for i in range(3)])\n```\n\n [183416, 183187, 182764]\n [3368, 3237, 3219]\n\n\n\n```python\nclass SNLIDataset(torch.utils.data.Dataset):\n \"\"\"A customized dataset to load the SNLI dataset.\"\"\"\n def __init__(self, dataset, num_steps, vocab=None):\n self.num_steps = num_steps\n all_premise_tokens = d2l.tokenize(dataset[0])\n all_hypothesis_tokens = d2l.tokenize(dataset[1])\n if vocab is None:\n self.vocab = d2l.Vocab(all_premise_tokens + all_hypothesis_tokens,\n min_freq=5, reserved_tokens=[''])\n else:\n self.vocab = vocab\n self.premises = self._pad(all_premise_tokens)\n self.hypotheses = self._pad(all_hypothesis_tokens)\n self.labels = torch.tensor(dataset[2])\n print('read ' + str(len(self.premises)) + ' examples')\n\n def _pad(self, lines):\n return torch.tensor([\n d2l.truncate_pad(self.vocab[line], self.num_steps,\n self.vocab['']) for line in lines])\n\n def __getitem__(self, idx):\n return (self.premises[idx], self.hypotheses[idx]), self.labels[idx]\n\n def __len__(self):\n return len(self.premises)\n```\n\n\n```python\ndef load_data_snli(batch_size, num_steps=50):\n \"\"\"Download the SNLI dataset and return data iterators and vocabulary.\"\"\"\n num_workers = d2l.get_dataloader_workers()\n data_dir = d2l.download_extract('SNLI')\n train_data = read_snli(data_dir, True)\n test_data = read_snli(data_dir, False)\n train_set = SNLIDataset(train_data, num_steps)\n test_set = SNLIDataset(test_data, num_steps, train_set.vocab)\n train_iter = torch.utils.data.DataLoader(train_set, batch_size,\n shuffle=True,\n num_workers=num_workers)\n test_iter = torch.utils.data.DataLoader(test_set, batch_size,\n shuffle=False,\n num_workers=num_workers)\n return train_iter, test_iter, train_set.vocab\n```\n\n\n```python\ntrain_iter, test_iter, vocab = load_data_snli(128, 50)\nlen(vocab)\n```\n\n read 549367 examples\n read 9824 examples\n\n\n /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:477: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n\n\n\n\n\n 18678\n\n\n\n\n```python\nfor X, Y in train_iter:\n print(X[0].shape)\n print(X[1].shape)\n print(Y.shape)\n break\n```\n\n /usr/local/lib/python3.7/dist-packages/torch/utils/data/dataloader.py:477: UserWarning: This DataLoader will create 4 worker processes in total. Our suggested max number of worker in current system is 2, which is smaller than what this DataLoader is going to create. Please be aware that excessive worker creation might get DataLoader running slow or even freeze, lower the worker number to avoid potential slowness/freeze if necessary.\n cpuset_checked))\n\n\n torch.Size([128, 50])\n torch.Size([128, 50])\n torch.Size([128])\n\n\n# Model\n\nThe model is described in the book. Below we just give the code.\n\n## Attending\n\nWe define attention weights\n$$\ne_{ij} = f(a_i)^T f(b_j)\n$$\nwhere $a_i \\in R^E$ is the embedding of the $i$'th token from the premise,\n$b_j \\in R^E$ is the embedding of the $j$'th token from the hypothesis,\nand $f: R^E \\rightarrow R^H$ is an MLP that maps from the embedding space to another hidden space.\n\n\n\n\n```python\ndef mlp(num_inputs, num_hiddens, flatten):\n net = []\n net.append(nn.Dropout(0.2))\n net.append(nn.Linear(num_inputs, num_hiddens))\n net.append(nn.ReLU())\n if flatten:\n net.append(nn.Flatten(start_dim=1))\n net.append(nn.Dropout(0.2))\n net.append(nn.Linear(num_hiddens, num_hiddens))\n net.append(nn.ReLU())\n if flatten:\n net.append(nn.Flatten(start_dim=1))\n return nn.Sequential(*net)\n```\n\nThe $i$'th word in A computes a weighted average of \"relevant\" words in B, and vice versa, as follows:\n$$\n\\begin{align}\n\\beta_i &= \\sum_{j=1}^n \n\\frac{\\exp(e_{ij})}{\\sum_{k=1}^n \\exp(e_{ik})}\n b_j \n \\\\ \n\\alpha_j &= \\sum_{i=1}^m \\frac{\\exp(e_{ij})}{\\sum_{k=1}^m \\exp(e_{kj})}\n a_i\n \\end{align} \n $$\n\n\n\n```python\nclass Attend(nn.Module):\n def __init__(self, num_inputs, num_hiddens, **kwargs):\n super(Attend, self).__init__(**kwargs)\n self.f = mlp(num_inputs, num_hiddens, flatten=False)\n\n def forward(self, A, B):\n # Shape of `A`/`B`: (`batch_size`, no. of words in sequence A/B,\n # `embed_size`)\n # Shape of `f_A`/`f_B`: (`batch_size`, no. of words in sequence A/B,\n # `num_hiddens`)\n f_A = self.f(A)\n f_B = self.f(B)\n # Shape of `e`: (`batch_size`, no. of words in sequence A,\n # no. of words in sequence B)\n e = torch.bmm(f_A, f_B.permute(0, 2, 1))\n # Shape of `beta`: (`batch_size`, no. of words in sequence A,\n # `embed_size`), where sequence B is softly aligned with each word\n # (axis 1 of `beta`) in sequence A\n beta = torch.bmm(F.softmax(e, dim=-1), B)\n # Shape of `alpha`: (`batch_size`, no. of words in sequence B,\n # `embed_size`), where sequence A is softly aligned with each word\n # (axis 1 of `alpha`) in sequence B\n alpha = torch.bmm(F.softmax(e.permute(0, 2, 1), dim=-1), A)\n return beta, alpha\n```\n\n## Comparing\n\nWe concatenate word $i$ in A, $a_i$, with its \"soft counterpart\" in B, $\\beta_i$, and vice versa, and then pass this through another MLP $g$\nto get a \"comparison vector\" for each input location.\n$$\n\\begin{align}\n v_{A,i} &= g([a_i, \\beta_i]), \\; i=1,\\ldots, m \\\\\n v_{B,j} &= g([b_j, \\alpha_j]), \\; j=1,\\ldots, n\n\\end{align}\n$$\n\n\n```python\nclass Compare(nn.Module):\n def __init__(self, num_inputs, num_hiddens, **kwargs):\n super(Compare, self).__init__(**kwargs)\n self.g = mlp(num_inputs, num_hiddens, flatten=False)\n\n def forward(self, A, B, beta, alpha):\n V_A = self.g(torch.cat([A, beta], dim=2))\n V_B = self.g(torch.cat([B, alpha], dim=2))\n return V_A, V_B\n```\n\n## Aggregation\n\nWe sum-pool the \"comparison vectors\" for each input sentence, and then pass the pair of poolings to yet another MLP $h$ to generate the final classification.\n\n$$\n\\begin{align}\n v_A &= \\sum_{i=1}^m v_{A,i} \\\\\n v_B &= \\sum_{j=1}^n v_{B,j} \\\\\n \\hat{y} &= h([v_A, v_B])\n\\end{align}\n$$\n\n\n\n```python\nclass Aggregate(nn.Module):\n def __init__(self, num_inputs, num_hiddens, num_outputs, **kwargs):\n super(Aggregate, self).__init__(**kwargs)\n self.h = mlp(num_inputs, num_hiddens, flatten=True)\n self.linear = nn.Linear(num_hiddens, num_outputs)\n\n def forward(self, V_A, V_B):\n # Sum up both sets of comparison vectors\n V_A = V_A.sum(dim=1)\n V_B = V_B.sum(dim=1)\n # Feed the concatenation of both summarization results into an MLP\n Y_hat = self.linear(self.h(torch.cat([V_A, V_B], dim=1)))\n return Y_hat\n```\n\n## Putting it altogether\n\nWe use a pre-trained embedding of size E=100.\nThe $f$ (attend) function maps from $E=100$ to $H=200$ hiddens.\nThe $g$ (compare) function maps $2E=200$ to $H=200$.\nThe $h$ (aggregate) function maps $2H=400$ to 3 outputs.\n\n\n\n```python\nclass DecomposableAttention(nn.Module):\n def __init__(self, vocab, embed_size, num_hiddens, num_inputs_attend=100,\n num_inputs_compare=200, num_inputs_agg=400, **kwargs):\n super(DecomposableAttention, self).__init__(**kwargs)\n self.embedding = nn.Embedding(len(vocab), embed_size)\n self.attend = Attend(num_inputs_attend, num_hiddens)\n self.compare = Compare(num_inputs_compare, num_hiddens)\n # There are 3 possible outputs: entailment, contradiction, and neutral\n self.aggregate = Aggregate(num_inputs_agg, num_hiddens, num_outputs=3)\n\n def forward(self, X):\n premises, hypotheses = X\n A = self.embedding(premises)\n B = self.embedding(hypotheses)\n beta, alpha = self.attend(A, B)\n V_A, V_B = self.compare(A, B, beta, alpha)\n Y_hat = self.aggregate(V_A, V_B)\n return Y_hat\n```\n\n\n```python\nembed_size, num_hiddens, devices = 100, 200, d2l.try_all_gpus()\nnet = DecomposableAttention(vocab, embed_size, num_hiddens)\n# get pre-trained GloVE embeddings of size 100\nglove_embedding = d2l.TokenEmbedding('glove.6b.100d')\nembeds = glove_embedding[vocab.idx_to_token]\nnet.embedding.weight.data.copy_(embeds);\n```\n\n Downloading ../data/glove.6B.100d.zip from http://d2l-data.s3-accelerate.amazonaws.com/glove.6B.100d.zip...\n\n\n# Training\n\n\n```python\nlr, num_epochs = 0.001, 4\ntrainer = torch.optim.Adam(net.parameters(), lr=lr)\nloss = nn.CrossEntropyLoss(reduction=\"none\")\nd2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)\n```\n\n loss 0.497, train acc 0.804, test acc 0.824\n 14685.9 examples/sec on [device(type='cuda', index=0)]\n\n\n\n \n\n \n\n\n# Testing\n\n\n```python\ndef predict_snli(net, vocab, premise, hypothesis):\n net.eval()\n premise = torch.tensor(vocab[premise], device=d2l.try_gpu())\n hypothesis = torch.tensor(vocab[hypothesis], device=d2l.try_gpu())\n label = torch.argmax(\n net([premise.reshape((1, -1)),\n hypothesis.reshape((1, -1))]), dim=1)\n return 'entailment' if label == 0 else 'contradiction' if label == 1 \\\n else 'neutral'\n```\n\n\n```python\npredict_snli(net, vocab, ['he', 'is', 'good', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'contradiction'\n\n\n\n\n```python\npredict_snli(net, vocab, ['he', 'is', 'very', 'naughty', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'neutral'\n\n\n\n\n```python\npredict_snli(net, vocab, ['he', 'is', 'awful', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'entailment'\n\n\n\n\n```python\npredict_snli(net, vocab, ['he', 'is', 'handsome', '.'], ['he', 'is', 'bad', '.'])\n```\n\n\n\n\n 'contradiction'\n\n\n\n## Examples from training set\n\n\n```python\npredict_snli(net, vocab, \n ['a', 'person', 'on', 'a', 'horse', 'jumps', 'over', 'a', 'log' '.'],\n ['a', 'person', 'is', 'outdoors', 'on', 'a', 'horse', '.']) \n```\n\n\n\n\n 'entailment'\n\n\n\n\n```python\npredict_snli(net, vocab, \n ['a', 'person', 'on', 'a', 'horse', 'jumps', 'over', 'a', 'log' '.'],\n ['a', 'person', 'is', 'at', 'a', 'diner', 'ordering', 'an', 'omelette', '.']) \n```\n\n\n\n\n 'contradiction'\n\n\n\n\n```python\npredict_snli(net, vocab, \n ['a', 'person', 'on', 'a', 'horse', 'jumps', 'over', 'a', 'log' '.'],\n ['a', 'person', 'is', 'training', 'a', 'horse', 'for', 'a', 'competition', '.']) \n```\n\n\n\n\n 'neutral'\n\n\n", "meta": {"hexsha": "250a8e96a16a8e7276f5f614429bfb4d7d646220", "size": 62632, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/entailment_attention_mlp_torch.ipynb", "max_stars_repo_name": "ashishpapanai/pyprobml", "max_stars_repo_head_hexsha": "8eadb39af7ac4575f9d0b661168eb0e876c33dfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/entailment_attention_mlp_torch.ipynb", "max_issues_repo_name": "ashishpapanai/pyprobml", "max_issues_repo_head_hexsha": "8eadb39af7ac4575f9d0b661168eb0e876c33dfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-04-19T12:25:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T12:25:26.000Z", "max_forks_repo_path": "notebooks/entailment_attention_mlp_torch.ipynb", "max_forks_repo_name": "Nirzu97/pyprobml", "max_forks_repo_head_hexsha": "397173b09668d21aac5c047b830db577cbb30530", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 65.7899159664, "max_line_length": 31704, "alphanum_fraction": 0.5535828331, "converted": true, "num_tokens": 4039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.6261241842048093, "lm_q1q2_score": 0.3471673767582569}} {"text": "# The Specific Factors or Ricardo-Viner Model\n\n### Background\n\nThe SF model is a workhorse model in trade, growth, political economy and development. We will see variants of the model used to describe rural to urban migration, the Lewis model and other dual sector models of sectoral misallocation, models such as the Harris-Todaro model that explain migration and the urban informal sector. The specific factors model predicts that, in the absence of political redistribution mechanisms, specific factors in declining sectors will organize strong opposition to policies that might otherwise raise growth. The initial distribution of factor endowments may therefore make a big difference in terms of what types of political coalitions mobilize for and against different policies. This is the basic driving force in Moav-Galor's (2006) growth model on why some regions made public investments in human capital which sped the transition from agriculture to manufacturing and enhanced growth, whereas similar policies were delayed in other regions where political/economic resistance was stronger, for instance where landlords had stronger voice in political decisions. \n\nThese are just a few of the applications. The model is relatively easy to analyze -- it can be described compactly in terms of diagrams and yet is very rich in predictions. \n\nThe Specific Factors (SF) or Ricardo-Viner model is a close relative of the Hecksher-Ohlin-Samuelson (HOS) neoclassical trade model. The 2x2 HOS model assumes production in each of two sectors takes place by firms using constant returns to scale technologies with capital and labor as inputs and that both capital and labor are mobile across sectors. In the SF model only labor is inter-sectorally mobile and the fixed amounts of capital become 'specific' to the sector they are trapped within. \n\nIn effect the SF model therefore consists of three factors of production: mobile labor and two types of capital, one specific to each sector. Let's label the two sectors are Agriculture and Manufacturing. In agriculture competitive firms bid to hire land and labor. In manufacturing competitive firms bid to hire capital and labor. Each factor of production will be competitively priced in equilibrium but only labor is priced on a national labor market. \n\nThe SF model is often described as a short-run version of the HOS model. For example suppose we start with a HOS model equilibrium where labor wage and rental rate of capital have equalized across sectors (which also implies marginal products are equalized across sectors -- no productivity differences across sectors). Now suppose that the relative price of manufacturing products suddenly rises (due to a change of world price, or government trade protection or other policies that favor manufacturing). The higher relative product price should lead firms in the booming manufacturing sector to demand both more capital and labor. Correspondingly, demand for land and labor decline in the agricultural sector. In the short run however only labor can be move from agriculture to manufacturing. Agricultural workers can become factory workers but agricultural capital (say 'land' or 'tractors') cannot be easily converted to manufacturing capital (say 'weaving machines'). So labor moves from manufacturing to the agriculture, lowering the capital labor ratio in manufacturing and raising the land to labor ratio in agriculture. The model thus predicts a surge in the real return to capital in the expanding sector and a real decline in the real return to capital in agriculture (land). Hence the measured average and marginal product of capital will now diverge across sectors. What happens to the real wage is more ambiguous: it rises measured in terms of purchasing power over agricultural goods but falls in terms of purchasing power over manufacturing goods. Whether workers are better off or worse off following this price/policy change therefore comes down to how important agricultural and manufacturing goods are in their consumption basket. This result is labeled the neo-classical ambiguity. \n\nOver the longer-term weaving machines cannot be transformed into tractors but over time new capital accumulation will build tractors and old weaving machines can be sold overseas or as scrap metal. Hence over time more capital will arrive into the manufacturing sector and leave the agricultural sector, whcih in turn will lead to even more movement of labor to manufacturing. If this process continues capital has, in effect become mobile over time, and we end up getting closer to the predictions of the HOS model.\n\n### Technology and Endowments\nThere are two sectors Agriculture and Manufacturing. Production in each sector takes place with a linear homogenous (constant returns to scale) production functions. Agricultural production requires land which is non-mobile or specific to the sector and mobile labor.\n\n$$Q_a = F(\\bar T, L_a)$$\n\nManufacturing production requires specific capital $K$ and mobile labor. \n\n$$Q_m = G(\\bar K, L_m)$$\n\nThe quantity of land in the agricultural sector and the quantity of capital in the manufacturing sector are in fixed supply during the period of analysis. That means that firms within the agricultural (manufacturing) sector may compete with one another for the limited supply of the factor, but no new land (capital) can be supplied in the short-run period of analysis. This of course means that the price of the factor will rise (or fall) quickly in response to swings in factor demand compared to the wage of labor whose supply is more elastic.\n\nThe market for mobile labor is competitive and the market clears at a wage where the sum of labor demands from each sector equals total labor supply. While the total labor supply in the economy is inelastic, the supply of labor to each sector will be elastic, since a rise in the wage in one sector will attract workers from the other sector. \n\n$$L_a + L_m = \\bar{L}$$\n\nNotice that we can invert the two production function to get minimum labor requirement functions $L_a(Q_a)$ and $L_m(Q_m)$ which tell us the minimum amount of labor $L_i$ required in sector $i$ to produce quantity $Q_i$. If we take these expressions and substitute them into the labor resource constraint we get an expression for the **production possibility frontier (PPF)** which summarizes the tradeoffs between sectors. \n\n### Assumptions and parameters for visualizations\n\nLet's get concrete and assume each sector employs a CRS Cobb-Douglas production function:\n\n$$F(\\bar T, L_a)=\\bar T^{1-\\alpha} \\cdot L_a^\\alpha$$\n\n$$G(\\bar K, L_m)=\\bar K^{1-\\beta} \\cdot L_m^\\beta$$\n\nIf $\\alpha = \\beta = \\frac{1}{2}$ and $\\bar T= \\bar K = 100$. Then\n\n$$Q_a = \\sqrt{\\bar T} \\sqrt{L_a} $$\n\n$$Q_m = \\sqrt{\\bar K} \\sqrt{L_m}$$\n\nSubstituting these into the labor resource constraint yields:\n\n$$\\frac{Q_a^2}{\\bar T}+\\frac{Q_m^2}{\\bar K} = \\bar L$$\n\nor \n\n$$Q_m = \\sqrt{\\bar K \\bar L - \\frac{\\bar K Q_a^2}{\\bar T} } $$\n\nIf we make the further assumption that $\\bar K = \\bar L = 100$ and $\\bar L = 400$ then the PPF would look like this:\n\n**NOTE:** If you are running this as a live jupyter notebook please first go to the [code section](#codesection) below and execute all the code cells there. Then return and run the code cells that follow sequentially.\n\n\n```python\nppf(Tbar=100, Kbar=100, Lbar=400)\n```\n\n## Labor market equilibrium\n\nProfit maximizing firms in each sector will hire labor up to the point where the marginal value product of labor (MVPL) equals the market wage. Since labor is mobile across sectors in equilibrium workers must be paid the same nominal wage $w$ in either sector:\n\n$$ P_a \\cdot MPL_a(\\bar T, L_a) = w = P_m \\cdot MPL_m(\\bar K, L_m) $$\n\nIt will be useful to express the wage in real terms. Divide each expression above by $P_m$ to get\n\n$$ p \\cdot MPL_a = \\frac{w}{p_m} = MPL_m $$\n\n$$\\text{ where } p = \\frac{P_a}{P_m}$$\n\nIn the plots below we will place the real wage measured in terms of manufactured goods on the vertical axis of the labor demand and supply diagrams.\n\n### Labor allocation across sectors \n\nIn a competitive market firms take the market prices of goods $p$ and wages $w$ as given. Since in equilibrium the labor market clears we can write $L_m = \\bar L - L_a$ and substitute into the equilibrium condition above to get:\n\n$$p \\cdot MPL_a(L_A) = w = MPL_m(\\bar L-L_A) $$\n\nThe left hand side $p \\cdot MPL_a(L_A)=w$ can be solved to give us demand for labor in the agricultural sector as a function of the wage $L_a(w/p)$ and is plotted below. The right hand side $w = MPL_m(\\bar L-L_a)$ gives us demand for labor in the manufacturing sector $L_m$ as a function of the real wage but this in turn also gives us the supply of labor to the agricultural sector $L_a^s = \\bar L - L_m(w/p)$ since firms in the agricultural sector can only attract workers to their sector by paying those workers just a bit above what they would be paid for the jobs they have to leave in the manufacturing sector. \n\nThe diagram below can therefore be interpreted as showing labor demand and supply in the agricultural sector and their intersection gives us the equilibrium real wage (measured on the vertical in terms of purchasing power over manufactured goods).\n\n\n```python\nsfmplot(p=1)\n```\n\n\n\nWe can solve for the equilibrium labor allocation $L_a$ as a function of the relative price $p$, and this in turn also gives us the equilibrium real wage. When $\\alpha=\\beta = \\frac{1}{2}$ the equilibrium condition $p \\cdot MPL_a(L_a) = MPL_m(\\bar L-L_a)$ becomes:\n\n$$p \\cdot \\frac{\\sqrt{\\bar T}}{\\sqrt{L_a}} = \\frac{\\sqrt{\\bar K}}{\\sqrt{\\bar L - L_a}}$$\n\nwhich we solve to find:\n\n$$L_a^e = \\frac{p^2 \\bar T \\bar L}{\\bar K - p^2 \\bar T}$$\n\nFor cases where $\\alpha \\ne \\beta$ we find the optimal $L_a$ that solves this equilibrium condition numerically. \n\n## Autarky prices\n\nThus far we have a pretty complete model of how production allocations and real wages would be determined in a small open economy where producers face world price ratio $p$. we explore comparative statics in this economy in more detail below. \n\nIf however the economy is inititally in autarky or closed to the world then we must also consider the role of domestic consumer preferences in the determination of domestic equilibrium product prices. \n\nWith Cobb-Douglas preferences $u(x,y) = \\gamma \\ln(x) + (1-\\gamma) \\ln(y)$ consumers demands can be written as a function of relative price $p=\\frac{P_a}{P_m}$. Setting $P_m=1$ to make manufacturing the numeraire good, this can be written:\n\n$$\\begin{align}\nC_a(p) =& \\gamma \\cdot \\frac{I(p)}{p} \\\\\nC_m(p) =& (1-\\gamma) \\cdot I(p)\n\\end{align}$$\n\nIncome $I$ in the expressions is given by the value of national production or GDP at these prices. Measured in manufactured goods:\n\n$$I(p) = p \\cdot F(\\bar T, L_a(p)) + G(\\bar K, \\bar L - L_a(p)$$\n\nBy Walras' law we only need to find the relative price at which output equals demand in one of the two product markets so in the the code below we solve for equilibrium domestic prices from the condition $Q_a(p)=C_a(p)$. \n\nFor parameters $\\alpha=\\beta=\\gamma = \\frac{1}{2}$, $\\bar T = \\bar K =100$ and $\\bar L=400$ the domestic equilibrium prices are unitary:\n\n\n```python\np_autarky(Lbar, Tbar, Kbar)\n```\n\n\n\n\n 1.0\n\n\n\nAnd this in turn leads to an equilibrium autarky allocation with $L_a = L_m = 200$ and a real wage $\\frac{w}{p}=0.35$.\n\n\n```python\neqn(p_autarky())\n```\n\n\n\n\n (200.0, 0.35355339059327373)\n\n\n\nThe plot below shows the autarky production and consumption point (marked by an 'X') as well as the new production point (marked by a circle) and consumption point (marked by a square) if the country opened to trade with a world relative price $p=\\frac{7}{4}$. \n\nOpening to trade leads the country to expand agricultural production by re-allocating labor from manufacturing to agriculture. We confirm the expected **neoclassical ambiguity** result which is that an increase in the relative price of agricultural goods will lead to an *increase* in the real wage measured in terms of manufactured goods $\\frac{w}{p_m}$ ($=w$ since we have $P_m=1$) but a *decrease* in real wage measured in terms of agricultural goods or $\\frac{w}{P_a} = \\frac{w}{p}$ in our notation (since $\\frac{w}{P_a} = \\frac{w}{p_m} \\cdot \\frac{P_m}{P_a}$).\n\nDiagrammatically\n\n$$p \\uparrow \\rightarrow \\frac{w}{p_m} \\uparrow , \\frac{w}{p_a} \\downarrow$$\n\n\n```python\npw = 7/4\nLao, wo = eqn(p=pw)\nLao, wo, wo/pw\n```\n\n\n\n\n (301.53846153846149, 0.50389110926865943, 0.28793777672494825)\n\n\n\n\n```python\nsfmtrade(p=7/4)\n```\n\n## Effects of a price change on the income distribution\n\nMore explanations to be placed here...\n\n\n```python\nsfmplot2(2)\n```\n\n\n## Code Section\n\nMake sure you run the cells below FIRST. Then run the cells above\n\n## Python simulation and plots\n\n\n```python\nimport numpy as np\nfrom scipy.optimize import fsolve\nnp.seterr(divide='ignore', invalid='ignore')\nimport matplotlib.pyplot as plt\nfrom ipywidgets import interact, fixed\nimport seaborn\n%matplotlib inline\n```\n\n\n```python\nplt.style.use('seaborn-colorblind')\nplt.rcParams[\"figure.figsize\"] = [7,7]\nplt.rcParams[\"axes.spines.right\"] = True\nplt.rcParams[\"axes.spines.top\"] = False\nplt.rcParams[\"font.size\"] = 18\nplt.rcParams['figure.figsize'] = (10, 6)\nplt.rcParams['axes.grid']=True\n```\n\n\n```python\nTbar = 100 # Fixed specific land in ag. \nKbar = 100 # Fixed specific capital in manuf\nLbar = 400 # Total number of mobile workers\nLbarMax = 400 # Lbar will be on slider, max value.\n\np = 1.00 # initial rel price of ag goods, p = Pa/Pm\nalpha, beta = 0.5, 0.5 # labor share in ag, manuf\n```\n\nFor the plots we want to plot over $L_a$ and $L_m = \\bar L -l_a$:\n\n\n```python\nLa = np.linspace(1, LbarMax-1,LbarMax)\nLm = Lbar - La\n```\n\nThe production functions in each sector:\n\n\n```python\ndef F(La, Tbar = Tbar):\n return (Tbar**(1-alpha) * La**alpha)\n\ndef G(Lm, Kbar =Kbar):\n return (Kbar**(1-beta) * Lm**beta) \n```\n\n\n```python\ndef MPLa(La):\n return alpha*Tbar**(1-alpha) * La**(alpha-1)\n\ndef MPLm(Lm):\n return beta*Kbar**(1-beta) * Lm**(beta-1)\n\ndef MPT(La, Tbar=Tbar):\n return (1-alpha)*Tbar**(-alpha) * La**alpha\n\ndef MPK(Lm, Kbar=Kbar):\n return (1-beta)*Kbar**(-beta) * Lm**beta\n```\n\nWe have enough to plot a production possibility Frontier (and how it varies with factor supplies):\n\n\n```python\ndef ppf(Tbar=Tbar, Kbar=Kbar, Lbar=Lbar):\n Qa = F(La, Tbar) * (La1:\n plt.title(r'$\\frac{P_a}{P_m} \\uparrow \\rightarrow \\frac{w}{P_m} \\uparrow, \\frac{w}{P_a} \\downarrow $' );\n elif p<1:\n plt.title(r'$\\frac{P_a}{P_m} \\downarrow \\rightarrow \\frac{w}{P_m} \\downarrow, \\frac{w}{P_a} \\uparrow $' );\n plt.show();\n \n```\n\n\n```python\nsfmplot2(2)\n```\n\n\n```python\ninteract(sfmplot2, p=(0.1, 2,0.1));\n```\n\n\n\n## Before and after plots\n\nThe trick here is to define a new plotting function that first plots a static plot and then allows an interaction. \n\n\n```python\ninteract(sfmplot2, p=(0,2,0.2), Lbar=fixed(400), show=fixed(True))\n```\n\n\n\n\n\n\n \n\n\n", "meta": {"hexsha": "2478bde50878dc0a3b9bddd65e849cd82b80a8fd", "size": 361894, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/SFM.ipynb", "max_stars_repo_name": "snowdj/Dev-II", "max_stars_repo_head_hexsha": "1feb49a64b3cfba5b96519298d91653a0f5c4045", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/SFM.ipynb", "max_issues_repo_name": "snowdj/Dev-II", "max_issues_repo_head_hexsha": "1feb49a64b3cfba5b96519298d91653a0f5c4045", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/SFM.ipynb", "max_forks_repo_name": "snowdj/Dev-II", "max_forks_repo_head_hexsha": "1feb49a64b3cfba5b96519298d91653a0f5c4045", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 375.0196891192, "max_line_length": 50822, "alphanum_fraction": 0.9218500445, "converted": true, "num_tokens": 5305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.3466676072981253}} {"text": "
\n

Introduction to Jet Images and Computer Vision

\n

Tiago Vale - LIP

\n

Adapted from a tutorial by Michela Paganini

\n
\n\n\nMaterial:\n 1. Ben Nachman's plenary talk at ACAT 2017 (slides)\n 1. My talk on Generative Adversarial Networks for jet images at the 2017 IML Workshop (video)\n 1. Jannicke Pearkes's talk on boosted top tagging with jet images at the 2017 IML Workshop (video)\n 1. Michael Kagan's overview talk at LHCP 2017 (slides)\n 1. ATLAS PUB Note on quark vs gluon tagging with jet images(note)\n 1. Lynn Huynh's summer report on jet image pre-processing (write-up)\n 1. Ben Nachman's talk at DataScience@LHC 2015 (video)\n\n# Dataset\n\n[](https://doi.org/10.17632/4r4v785rgx.1)\n\n\n\nAlthough the dataset was released in conjunction with the arXiv publication of our [work on Generative Adversarial Networks for jet images](https://arxiv.org/pdf/1701.05927.pdf), it was previously used in the original \"[Jet Images -- Deep Learning Edition](https://link.springer.com/article/10.1007%2FJHEP07%282016%29069)\" work on jet image classification. Feel free to explore the dataset and use it for any project you have in mind (please cite the dataset and relevant publications explaining its generation!)\n\n### Download dataset from Zenodo\n\n\n```python\nimport os\nfrom keras.utils.data_utils import get_file\n\n# Info for downloading the dataset from Zenodo\nMD5_HASH = 'f9b11c46b6a0ff928bec2eccf865ecf0'\nDATAFILE = 'jet-images_Mass60-100_pT250-300_R1.25_Pix25.hdf5'\nURL_TEMPLATE = 'https://zenodo.org/record/{record}/files/{filename}'\n\nprint('[INFO] MD5 verification: {}'.format(MD5_HASH))\n\ndatafile = get_file(\n fname=DATAFILE,\n origin=URL_TEMPLATE.format(record=269622, filename=DATAFILE),\n md5_hash=MD5_HASH\n)\n```\n\n# Jets at the LHC\n\n\n\nJets are the observable result of quarks and gluons scattering at high energy. A collimated stream of\nprotons and other hadrons forms in the direction of the initiating quark or gluon. Clusters of such\nparticles are called jets.\n\n# Jet Images\n\nMature field of research! (image courtesy of B.P.Nachman) \n\n\n\n\n### What is a jet image?\n\n\n\n> A jet image is a two-dimensional representation of the radiation pattern within a jet: the distribution of the locations and energies of the jet’s constituent particles. The jet image consists of a regular grid of pixels in η×φ. \n\nAdvantages of this data format include: easy visual inspection, fixed-length representation, suitable for application of computer vision techniques.\n\n### Pre-processing\n\nIn the dataset we will be using today:\n\n> The finite granularity of a calorimeter is simulated with a regular 0.1×0.1 grid in η and φ. The energy of each calorimeter cell is given by the sum of the energies of all particles incident on the cell. Cells with positive energy are assigned to jets using the anti-kt clustering algorithm with a radius parameter of R = 1.0 via the software package FastJet 3.2.1.\n\n> To mitigate the contribution from the underlying event, jets are are trimmed by re-clustering the constituents into R = 0.3 kt subjets and dropping those which have less than 5% of the transverse momentum of the parent jet. Trimming also reduces the impact of pileup: multiple proton-proton collisions occurring in the same event as the hard-scatter process. Jet images are formed by translating the η and φ of all constituents of a given jet so that its highest pT subjet is centered at the origin.\n\n> A rectangular grid of η × φ ∈ [−1.25, 1.25] × [−1.25, 1.25] with 0.1 × 0.1 pixels centered at the origin\nforms the basis of the jet image. The intensity of each pixel is the pT corresponding to the energy\nand pseudorapditiy of the constituent calorimeter cell, pT = E_cell/ cosh(η_cell). The radiation pattern\nis symmetric about the origin of the jet image and so the images are rotated. The subjet with the\nsecond highest pT (or, in its absence, the direction of the first principle component) is placed at an\nangle of −π/2 with respect to the η − φ axes. Finally, a parity transform about the vertical axis is\napplied if the left side of the image has more energy than the right side.\n\n
\n Learning Particle Physics by Example: Location-Aware Generative Adversarial Networks for Physics Synthesis
\n [arXiv:1701.05927](https://arxiv.org/pdf/1701.05927.pdf)\n
\n\nReferences: \n* Section 3 of [arXiv:1511.05190](https://link.springer.com/content/pdf/10.1007%2FJHEP07%282016%29069.pdf)\n* Appendix B of [arXiv:1701.05927](https://arxiv.org/pdf/1701.05927.pdf)\n\n### Uniqueness with respect to natural images in ML literature\n\n* Sparse (low occupancy)\n* High dynamic range (pixel intensity represents pT of particles and spans several orders of magnitude)\n* Pixel activations and positions are physically meaningful\n* Small variations can drastically modify physical properties of a jet\n\n# Hands-on tutorial\n\n\n```python\nimport h5py\nimport numpy as np\nimport os\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom matplotlib.colors import LogNorm, Normalize\n%matplotlib inline\n```\n\n\n```python\n# number of images to load\nnb_points = 800000\n```\n\n\n```python\n# open hdf5 data file\nd = h5py.File(datafile, 'r')\n```\n\n\n```python\n# content of the dataset\nd.items()\n```\n\n\n\n\n ItemsViewHDF5()\n\n\n\n\n```python\n# extract a random subset of samples\nix = list(range(d['image'].shape[0])) # get indices\nnp.random.shuffle(ix) # shuffle them\nix = ix[:nb_points] # select out nb_points\n\n# extract data from dataset\nimages, labels = d['image'][:][ix], d['signal'][:][ix]\nmass = d['jet_mass'][:][ix]\ndelta_R = d['jet_delta_R'][:][ix]\ntau_21 = d['tau_21'][:][ix]\n```\n\nYou can compute the quantities above directly from the images:\n\n\\begin{align}\n&p_\\text{T}^2(I) =\\left(\\sum_{i=0}^{N} I_i\\cos(\\phi_i)\\right)^2+\\left(\\sum_{i=0}^{N} I_i\\sin(\\phi_i)\\right)^2\n\\label{eq:pt}\n\\\\\n&m^2(I) = \\left(\\sum_{i=0}^{N} I_i\\right)^2-p_\\text{T}^2(I)-\\left(\\sum_{i=0}^{N} I_i\\sinh(\\eta_i)\\right)^2\n\\label{eq:m}\n\\\\\n&\\tau_{21}(I)=\\frac{\\tau_2(I)}{\\tau_1(I)},\n\\label{eq:tau21}\n\\end{align}\nwhere:\n\\begin{equation*}\n\\tau_{n}(I)\\propto\\sum_{i=0}^{N} I_i \\min_{1\\leq a\\leq n}\\left\\{\\sqrt{\\left(\\eta_i-\\eta_a\\right)^2+\\left(\\phi_i-\\phi_a\\right)^2}\\right\\}\n\\end{equation*}\n\n\n```python\ndef plot_jet_image(content, output_fname=None, vmin=1e-6, vmax=300, title=''):\n '''\n Function to help you visualize a jet image on a log scale\n Args:\n -----\n content : numpy array of dimensions 25x25, first arg to imshow, \n content of the image\n e.g.: images.mean(axis=0) --> the average image\n\n output_fname : string, name of the output file where the plot will be \n saved. \n\n vmin : (default = 1e-6) float, lower bound of the pixel intensity \n scale before saturation\n\n vmax : (default = 300) float, upper bound of the pixel intensity \n scale before saturation\n\n title : (default = '') string, title of the plot, to be displayed \n on top of the image\n '''\n fig, ax = plt.subplots(figsize=(7, 6))\n extent = [-1.25, 1.25, -1.25, 1.25]\n\n im = ax.imshow(content, interpolation='nearest',\n norm=LogNorm(vmin=vmin, vmax=vmax), extent=extent)\n\n cbar = plt.colorbar(im, fraction=0.05, pad=0.05)\n cbar.set_label(r'Pixel $p_T$ (GeV)', y=0.85)\n plt.xlabel(r'[Transformed] Pseudorapidity $(\\eta)$')\n plt.ylabel(r'[Transformed] Azimuthal Angle $(\\phi)$')\n plt.title(title)\n\n if output_fname is None:\n plt.savefig('output_fname')\n```\n\n\n```python\ndef plot_diff_jet_image(content, output_fname=None, extr=None, title='',\n cmap=matplotlib.cm.seismic):\n '''\n Function to help you visualize the difference between two sets of jet \n images on a linear scale\n Args:\n -----\n content : numpy array of dimensions 25x25, first arg to imshow, \n content of the image\n e.g.: sig_images.mean(axis=0) - bkg_images.mean(axis=0)\n output_fname : string, name of the output file where the plot will be \n saved.\n extr : (default = None) float, magnitude of the upper and lower \n bounds of the pixel intensity scale before saturation (symmetric \n around 0)\n title : (default = '') string, title of the plot, to be displayed on \n top of the image\n cmap : (default = matplotlib.cm.PRGn_r) matplotlib colormap, ideally \n white in the middle\n '''\n fig, ax = plt.subplots(figsize=(6, 6))\n extent = [-1.25, 1.25, -1.25, 1.25]\n if extr == None:\n extr = max(abs(content.min()), abs(content.max()))\n im = ax.imshow(\n content,\n interpolation='nearest',\n norm=Normalize(vmin=-extr, vmax=+extr), extent=extent,\n cmap=cmap\n )\n\n plt.colorbar(im, fraction=0.05, pad=0.05)\n plt.xlabel(r'[Transformed] Pseudorapidity $(\\eta)$')\n plt.ylabel(r'[Transformed] Azimuthal Angle $(\\phi)$')\n plt.title(title)\n\n if output_fname:\n plt.savefig(output_fname)\n\n```\n\n\n```python\n# visualize a jet image\nplot_jet_image(images[0])\n```\n\n\n```python\n# visualize the average jet image\nplot_jet_image(images.mean(axis=0))\n```\n\n\n```python\n# visualize the difference between the average signal and the average background image\nplot_diff_jet_image(\n images[labels == 1].mean(axis=0) - images[labels == 0].mean(axis=0)\n)\n```\n\n## Looking at Physics features\n\n\n```python\ndef plot_physics_feature(feature_name, feature, labels, bins=None, output_fname=None):\n\n # if bins are not defined when function is called, define them here\n if not bins:\n bins = np.linspace(feature.min(), feature.max(), 50)\n\n fig, ax = plt.subplots(figsize=(6, 6))\n\n _ = plt.hist(feature[labels == 1], bins=bins, histtype='step',\n label=r\"Signal ($W' \\rightarrow WZ$)\",\n color='red')\n\n _ = plt.hist(feature[labels == 0], bins=bins, histtype='step',\n label=r'Background (QCD dijets)', color='blue')\n\n plt.xlabel(r'Discretized {} of Jet Image'.format(feature_name))\n plt.ylabel(r'Units normalized to unit area')\n plt.legend()\n\n if output_fname:\n plt.savefig(output_fname)\n\n```\n\n\n```python\nplot_physics_feature(r'$m$', mass, labels)\n```\n\n\n```python\nplot_physics_feature(r'$\\Delta R$', delta_R, labels)\n```\n\n\n```python\nplot_physics_feature(r'$\\tau_{2,1}$', tau_21, labels)\n```\n\n# Jet Image Classification\n\nWe can now try to use various techniques to classify the jet images into signal (i.e. originating from boosted W bosons) and background (QCD).\n\nWe will start with a classic feature-based classifier, which will use properties of the jet such as mass, tau_21, and delta_R (known to have good discriminative power) to separate the two classes.\n\nThen, we will construct different networks that operate directly at the pixel level and compare them all.\n\n## Simple feature-based classifier\n\n#### Data processing\n\nFollow the procedure from yesterday to create your matrix of features X. Shuffle its entries, split them into train, test, and validation set, and scale them to zero mean and unit standard deviation.\n\n\n```python\nfeatures = np.stack((mass, tau_21, delta_R)).T # What we called X yesterday\n```\n\n\n```python\nfeatures\n```\n\n\n\n\n array([[7.4899811e+01, 1.3971861e-01, 5.7381898e-01],\n [9.6999718e+01, 3.8425145e-01, 7.0187241e-01],\n [8.1882729e+01, 3.6674374e-01, 5.5160850e-01],\n ...,\n [8.1609734e+01, 3.1000379e-01, 6.3720000e-01],\n [7.3569969e+01, 8.4428534e-02, 4.9061748e-01],\n [7.7200653e+01, 1.0726629e-01, 5.4942137e-01]], dtype=float32)\n\n\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\n# 80% train+validate, 20% test\nimages_train, images_test, \\\n labels_train, labels_test, \\\n features_train, features_test \\\n = train_test_split(images, labels, features,\n test_size=0.2)\n\n# 64% train, 16% validate\nimages_train, images_val, \\\n labels_train, labels_val, \\\n features_train, features_val \\\n = train_test_split(images_train, labels_train, features_train,\n test_size=0.2)\n```\n\n\n```python\nprint ('{} training samples\\n{} validation samples\\n{} testing samples'\n .format(images_train.shape[0], images_val.shape[0], images_test.shape[0]))\n```\n\n 512000 training samples\n 128000 validation samples\n 160000 testing samples\n\n\n\n```python\nfrom sklearn.preprocessing import StandardScaler\n```\n\n\n```python\nscaler = StandardScaler()\nfeatures_train = scaler.fit_transform(features_train)\nfeatures_val = scaler.transform(features_val)\nfeatures_test = scaler.transform(features_test)\n```\n\n#### Model\n\nBuild a simple keras model made of fully-connected (Dense) layers. Remember the steps:\n1. Define the symbolic graph by connecting layers\n1. Define an optimizer and a loss function to minimize\n1. Train ('fit') the model to the training dataset, monitoring whether the validation loss continues to decrease\n1. Stop the training automatically when the validation loss stops going down\n1. Evaluate performance on test set\n\nRecall activation functions: Rectified Linear Unit (relu) vs. Leaky Rectified Linear Unit\n\n\n\n```python\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\n```\n\n\n```python\nx = Input(shape=(features_train.shape[1], ))\nh = Dense(64, activation='relu')(x)\nh = Dense(64, activation='relu')(h)\nh = Dense(64, activation='relu')(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\nbaseline_model = Model(x, y)\nbaseline_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\nThe command below trains the model. However, in the interest of time, I will not train the network on the spot. I will instead load in pre-trained weights from a training I performed last night.\n\n\n```python\nbaseline_model.fit(\n features_train, labels_train, # X and y\n epochs=200,\n batch_size=128,\n validation_data=(features_val, labels_val), # validation X and y\n callbacks=[\n EarlyStopping(verbose=True, patience=15, monitor='val_loss'),\n ModelCheckpoint('./models/baseline-model.h5', monitor='val_loss',\n verbose=True, save_best_only=True)\n ]\n)\n```\n\n Epoch 1/200\n 4000/4000 [==============================] - 4s 936us/step - loss: 0.4614 - acc: 0.7879 - val_loss: 0.4503 - val_acc: 0.7918\n \n Epoch 00001: val_loss improved from inf to 0.45032, saving model to ./models/baseline-model.h5\n Epoch 2/200\n 4000/4000 [==============================] - 4s 908us/step - loss: 0.4514 - acc: 0.7925 - val_loss: 0.4509 - val_acc: 0.7923\n \n Epoch 00002: val_loss did not improve from 0.45032\n Epoch 3/200\n 4000/4000 [==============================] - 4s 883us/step - loss: 0.4508 - acc: 0.7924 - val_loss: 0.4493 - val_acc: 0.7931\n \n Epoch 00003: val_loss improved from 0.45032 to 0.44934, saving model to ./models/baseline-model.h5\n Epoch 4/200\n 4000/4000 [==============================] - 4s 881us/step - loss: 0.4511 - acc: 0.7931 - val_loss: 0.4498 - val_acc: 0.7926\n \n Epoch 00004: val_loss did not improve from 0.44934\n Epoch 5/200\n 4000/4000 [==============================] - 4s 915us/step - loss: 0.4508 - acc: 0.7926 - val_loss: 0.4494 - val_acc: 0.7931\n \n Epoch 00005: val_loss did not improve from 0.44934\n Epoch 6/200\n 4000/4000 [==============================] - 4s 919us/step - loss: 0.4498 - acc: 0.7934 - val_loss: 0.4489 - val_acc: 0.7933\n \n Epoch 00006: val_loss improved from 0.44934 to 0.44887, saving model to ./models/baseline-model.h5\n Epoch 7/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4509 - acc: 0.7934 - val_loss: 0.4490 - val_acc: 0.7927\n \n Epoch 00007: val_loss did not improve from 0.44887\n Epoch 8/200\n 4000/4000 [==============================] - 4s 955us/step - loss: 0.4494 - acc: 0.7937 - val_loss: 0.4493 - val_acc: 0.7925\n \n Epoch 00008: val_loss did not improve from 0.44887\n Epoch 9/200\n 4000/4000 [==============================] - 4s 937us/step - loss: 0.4496 - acc: 0.7934 - val_loss: 0.4491 - val_acc: 0.7932\n \n Epoch 00009: val_loss did not improve from 0.44887\n Epoch 10/200\n 4000/4000 [==============================] - 4s 993us/step - loss: 0.4508 - acc: 0.7926 - val_loss: 0.4495 - val_acc: 0.7929\n \n Epoch 00010: val_loss did not improve from 0.44887\n Epoch 11/200\n 4000/4000 [==============================] - 4s 949us/step - loss: 0.4490 - acc: 0.7935 - val_loss: 0.4500 - val_acc: 0.7928\n \n Epoch 00011: val_loss did not improve from 0.44887\n Epoch 12/200\n 4000/4000 [==============================] - 4s 952us/step - loss: 0.4501 - acc: 0.7929 - val_loss: 0.4487 - val_acc: 0.7932\n \n Epoch 00012: val_loss improved from 0.44887 to 0.44868, saving model to ./models/baseline-model.h5\n Epoch 13/200\n 4000/4000 [==============================] - 4s 970us/step - loss: 0.4500 - acc: 0.7931 - val_loss: 0.4493 - val_acc: 0.7927\n \n Epoch 00013: val_loss did not improve from 0.44868\n Epoch 14/200\n 4000/4000 [==============================] - 4s 940us/step - loss: 0.4496 - acc: 0.7936 - val_loss: 0.4493 - val_acc: 0.7926\n \n Epoch 00014: val_loss did not improve from 0.44868\n Epoch 15/200\n 4000/4000 [==============================] - 4s 941us/step - loss: 0.4499 - acc: 0.7932 - val_loss: 0.4489 - val_acc: 0.7930\n \n Epoch 00015: val_loss did not improve from 0.44868\n Epoch 16/200\n 4000/4000 [==============================] - 4s 941us/step - loss: 0.4504 - acc: 0.7930 - val_loss: 0.4496 - val_acc: 0.7925\n \n Epoch 00016: val_loss did not improve from 0.44868\n Epoch 17/200\n 4000/4000 [==============================] - 4s 939us/step - loss: 0.4502 - acc: 0.7923 - val_loss: 0.4490 - val_acc: 0.7930\n \n Epoch 00017: val_loss did not improve from 0.44868\n Epoch 18/200\n 4000/4000 [==============================] - 5s 1ms/step - loss: 0.4501 - acc: 0.7928 - val_loss: 0.4485 - val_acc: 0.7930\n \n Epoch 00018: val_loss improved from 0.44868 to 0.44849, saving model to ./models/baseline-model.h5\n Epoch 19/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4495 - acc: 0.7935 - val_loss: 0.4491 - val_acc: 0.7927\n \n Epoch 00019: val_loss did not improve from 0.44849\n Epoch 20/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4490 - acc: 0.7938 - val_loss: 0.4487 - val_acc: 0.7934\n \n Epoch 00020: val_loss did not improve from 0.44849\n Epoch 21/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4501 - acc: 0.7928 - val_loss: 0.4488 - val_acc: 0.7930\n \n Epoch 00021: val_loss did not improve from 0.44849\n Epoch 22/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4509 - acc: 0.7925 - val_loss: 0.4486 - val_acc: 0.7927\n \n Epoch 00022: val_loss did not improve from 0.44849\n Epoch 23/200\n 4000/4000 [==============================] - 4s 949us/step - loss: 0.4503 - acc: 0.7930 - val_loss: 0.4486 - val_acc: 0.7930\n \n Epoch 00023: val_loss did not improve from 0.44849\n Epoch 24/200\n 4000/4000 [==============================] - 4s 932us/step - loss: 0.4501 - acc: 0.7927 - val_loss: 0.4488 - val_acc: 0.7928\n \n Epoch 00024: val_loss did not improve from 0.44849\n Epoch 25/200\n 4000/4000 [==============================] - 4s 909us/step - loss: 0.4495 - acc: 0.7931 - val_loss: 0.4486 - val_acc: 0.7929\n \n Epoch 00025: val_loss did not improve from 0.44849\n Epoch 26/200\n 4000/4000 [==============================] - 4s 915us/step - loss: 0.4488 - acc: 0.7944 - val_loss: 0.4485 - val_acc: 0.7934\n \n Epoch 00026: val_loss did not improve from 0.44849\n Epoch 27/200\n 4000/4000 [==============================] - 4s 921us/step - loss: 0.4501 - acc: 0.7929 - val_loss: 0.4485 - val_acc: 0.7933\n \n Epoch 00027: val_loss improved from 0.44849 to 0.44846, saving model to ./models/baseline-model.h5\n Epoch 28/200\n 4000/4000 [==============================] - 4s 916us/step - loss: 0.4500 - acc: 0.7933 - val_loss: 0.4488 - val_acc: 0.7932\n \n Epoch 00028: val_loss did not improve from 0.44846\n Epoch 29/200\n 4000/4000 [==============================] - 4s 921us/step - loss: 0.4491 - acc: 0.7935 - val_loss: 0.4486 - val_acc: 0.7932\n \n Epoch 00029: val_loss did not improve from 0.44846\n Epoch 30/200\n 4000/4000 [==============================] - 4s 922us/step - loss: 0.4503 - acc: 0.7932 - val_loss: 0.4487 - val_acc: 0.7934\n \n Epoch 00030: val_loss did not improve from 0.44846\n Epoch 31/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4488 - acc: 0.7935 - val_loss: 0.4495 - val_acc: 0.7932\n \n Epoch 00031: val_loss did not improve from 0.44846\n Epoch 32/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4510 - acc: 0.7918 - val_loss: 0.4484 - val_acc: 0.7934\n \n Epoch 00032: val_loss improved from 0.44846 to 0.44842, saving model to ./models/baseline-model.h5\n Epoch 33/200\n 4000/4000 [==============================] - 4s 934us/step - loss: 0.4496 - acc: 0.7938 - val_loss: 0.4486 - val_acc: 0.7932\n \n Epoch 00033: val_loss did not improve from 0.44842\n Epoch 34/200\n 4000/4000 [==============================] - 4s 915us/step - loss: 0.4492 - acc: 0.7936 - val_loss: 0.4484 - val_acc: 0.7932\n \n Epoch 00034: val_loss did not improve from 0.44842\n Epoch 35/200\n 4000/4000 [==============================] - 4s 917us/step - loss: 0.4507 - acc: 0.7925 - val_loss: 0.4493 - val_acc: 0.7926\n \n Epoch 00035: val_loss did not improve from 0.44842\n Epoch 36/200\n 4000/4000 [==============================] - 5s 1ms/step - loss: 0.4488 - acc: 0.7942 - val_loss: 0.4492 - val_acc: 0.7931\n \n Epoch 00036: val_loss did not improve from 0.44842\n Epoch 37/200\n 4000/4000 [==============================] - 5s 1ms/step - loss: 0.4484 - acc: 0.7941 - val_loss: 0.4487 - val_acc: 0.7932\n \n Epoch 00037: val_loss did not improve from 0.44842\n Epoch 38/200\n 4000/4000 [==============================] - 5s 1ms/step - loss: 0.4487 - acc: 0.7936 - val_loss: 0.4484 - val_acc: 0.7933\n \n Epoch 00038: val_loss did not improve from 0.44842\n Epoch 39/200\n 4000/4000 [==============================] - 5s 1ms/step - loss: 0.4489 - acc: 0.7933 - val_loss: 0.4487 - val_acc: 0.7928\n \n Epoch 00039: val_loss did not improve from 0.44842\n Epoch 40/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4499 - acc: 0.7932 - val_loss: 0.4484 - val_acc: 0.7932\n \n Epoch 00040: val_loss improved from 0.44842 to 0.44842, saving model to ./models/baseline-model.h5\n Epoch 41/200\n 4000/4000 [==============================] - 4s 1ms/step - loss: 0.4502 - acc: 0.7933 - val_loss: 0.4489 - val_acc: 0.7931\n \n Epoch 00041: val_loss did not improve from 0.44842\n Epoch 42/200\n 4000/4000 [==============================] - 4s 877us/step - loss: 0.4486 - acc: 0.7938 - val_loss: 0.4485 - val_acc: 0.7930\n \n Epoch 00042: val_loss did not improve from 0.44842\n Epoch 43/200\n 4000/4000 [==============================] - 4s 979us/step - loss: 0.4481 - acc: 0.7946 - val_loss: 0.4484 - val_acc: 0.7933\n \n Epoch 00043: val_loss improved from 0.44842 to 0.44839, saving model to ./models/baseline-model.h5\n Epoch 44/200\n 4000/4000 [==============================] - 4s 974us/step - loss: 0.4493 - acc: 0.7937 - val_loss: 0.4492 - val_acc: 0.7930\n \n Epoch 00044: val_loss did not improve from 0.44839\n Epoch 45/200\n 4000/4000 [==============================] - 3s 872us/step - loss: 0.4489 - acc: 0.7939 - val_loss: 0.4485 - val_acc: 0.7933\n \n Epoch 00045: val_loss did not improve from 0.44839\n Epoch 46/200\n 4000/4000 [==============================] - 4s 914us/step - loss: 0.4499 - acc: 0.7931 - val_loss: 0.4484 - val_acc: 0.7933\n \n Epoch 00046: val_loss did not improve from 0.44839\n Epoch 47/200\n 4000/4000 [==============================] - 4s 908us/step - loss: 0.4495 - acc: 0.7941 - val_loss: 0.4489 - val_acc: 0.7929\n \n Epoch 00047: val_loss did not improve from 0.44839\n Epoch 48/200\n 4000/4000 [==============================] - 3s 862us/step - loss: 0.4491 - acc: 0.7940 - val_loss: 0.4488 - val_acc: 0.7931\n \n Epoch 00048: val_loss did not improve from 0.44839\n Epoch 49/200\n 4000/4000 [==============================] - 4s 946us/step - loss: 0.4501 - acc: 0.7930 - val_loss: 0.4489 - val_acc: 0.7927\n \n Epoch 00049: val_loss did not improve from 0.44839\n Epoch 50/200\n 4000/4000 [==============================] - 4s 903us/step - loss: 0.4491 - acc: 0.7934 - val_loss: 0.4488 - val_acc: 0.7937\n \n Epoch 00050: val_loss did not improve from 0.44839\n Epoch 51/200\n 4000/4000 [==============================] - 4s 896us/step - loss: 0.4494 - acc: 0.7936 - val_loss: 0.4486 - val_acc: 0.7930\n \n Epoch 00051: val_loss did not improve from 0.44839\n Epoch 52/200\n 4000/4000 [==============================] - 4s 886us/step - loss: 0.4495 - acc: 0.7934 - val_loss: 0.4484 - val_acc: 0.7934\n \n Epoch 00052: val_loss did not improve from 0.44839\n Epoch 53/200\n 4000/4000 [==============================] - 3s 856us/step - loss: 0.4501 - acc: 0.7930 - val_loss: 0.4485 - val_acc: 0.7929\n \n Epoch 00053: val_loss did not improve from 0.44839\n Epoch 54/200\n 4000/4000 [==============================] - 3s 870us/step - loss: 0.4498 - acc: 0.7935 - val_loss: 0.4488 - val_acc: 0.7931\n \n Epoch 00054: val_loss did not improve from 0.44839\n Epoch 55/200\n 4000/4000 [==============================] - 3s 873us/step - loss: 0.4478 - acc: 0.7945 - val_loss: 0.4485 - val_acc: 0.7929\n \n Epoch 00055: val_loss did not improve from 0.44839\n Epoch 56/200\n 4000/4000 [==============================] - 4s 971us/step - loss: 0.4484 - acc: 0.7941 - val_loss: 0.4489 - val_acc: 0.7932\n \n Epoch 00056: val_loss did not improve from 0.44839\n Epoch 57/200\n 4000/4000 [==============================] - 4s 998us/step - loss: 0.4497 - acc: 0.7930 - val_loss: 0.4485 - val_acc: 0.7931\n \n Epoch 00057: val_loss did not improve from 0.44839\n Epoch 58/200\n 4000/4000 [==============================] - 3s 873us/step - loss: 0.4487 - acc: 0.7938 - val_loss: 0.4487 - val_acc: 0.7935\n \n Epoch 00058: val_loss did not improve from 0.44839\n Epoch 00058: early stopping\n\n\n\n\n\n \n\n\n\nIf you were to actually run the training, you would be able to visualize its history. Keras saves the entire training history, keeping track of whatever metric you specify (here accuracy and loss).\n\n\n```python\nbaseline_model\n```\n\n\n\n\n \n\n\n\n\n```python\nhistory = baseline_model.history.history\nhistory.keys()\n```\n\n\n\n\n dict_keys(['loss', 'acc', 'val_loss', 'val_acc'])\n\n\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(history['acc']), label='training')\nplt.plot(100 * np.array(history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(history['loss']), label='training')\nplt.plot(100 * np.array(history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\n# plt.vlines(np.argmin(history['val_loss']), 45, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint('Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(history['val_loss'])))\n```\n\n Loss estimate on unseen examples (from validation set) = 0.448\n\n\n#### Evaluate on test set\n\n\n```python\nbaseline_model.load_weights('./models/baseline-model.h5')\n```\n\n\n```python\nyhat_baseline = baseline_model.predict(features_test, batch_size=512)\n```\n\n\n```python\nbins = np.linspace(0, 1, 20)\n_ = plt.hist(yhat_baseline[labels_test==1],\n histtype='stepfilled', alpha=0.5, color='red', label=r\"Signal ($W' \\rightarrow WZ$)\", bins=bins)\n_ = plt.hist(yhat_baseline[labels_test==0],\n histtype='stepfilled', alpha=0.5, color='blue', label=r'Background (QCD dijets)', bins=bins)\nplt.legend(loc='upper center')\nplt.xlabel('P(signal) assigned by the baseline model')\n```\n\n## Convolutional Neural Network\n\nWe can now instead try to learn a model directly on the pixel space, instead of summarizing the information into engineered features such as mass, tau_21 and delta_R.\n\n\n```python\nfrom keras.layers import Conv2D, Flatten, LeakyReLU\n```\n\n\n```python\n# add channel dimension (1 for grayscale)\nimages_train = np.expand_dims(images_train, -1)\nimages_test = np.expand_dims(images_test, -1)\nimages_val = np.expand_dims(images_val, -1)\n```\n\n\n```python\nx = Input(shape=(images_train.shape[1:]))\nh = Conv2D(32, kernel_size=7, strides=1)(x)\nh = LeakyReLU()(h)\nh = Dropout(0.2)(h)\n\nh = Conv2D(64, kernel_size=7, strides=1)(h)\nh = LeakyReLU()(h)\nh = Dropout(0.2)(h)\n\nh = Conv2D(128, kernel_size=5, strides=1)(h)\nh = LeakyReLU()(h)\nh = Dropout(0.2)(h)\n\nh = Conv2D(256, kernel_size=5, strides=1)(h)\nh = LeakyReLU()(h)\nh = Flatten()(h)\nh = Dropout(0.2)(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\ncnn_model = Model(x, y)\ncnn_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\n\n```python\ncnn_model.summary()\n```\n\n Model: \"model_2\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n input_2 (InputLayer) [(None, 25, 25, 1)] 0 \n _________________________________________________________________\n conv2d (Conv2D) (None, 19, 19, 32) 1600 \n _________________________________________________________________\n leaky_re_lu (LeakyReLU) (None, 19, 19, 32) 0 \n _________________________________________________________________\n dropout (Dropout) (None, 19, 19, 32) 0 \n _________________________________________________________________\n conv2d_1 (Conv2D) (None, 13, 13, 64) 100416 \n _________________________________________________________________\n leaky_re_lu_1 (LeakyReLU) (None, 13, 13, 64) 0 \n _________________________________________________________________\n dropout_1 (Dropout) (None, 13, 13, 64) 0 \n _________________________________________________________________\n conv2d_2 (Conv2D) (None, 9, 9, 128) 204928 \n _________________________________________________________________\n leaky_re_lu_2 (LeakyReLU) (None, 9, 9, 128) 0 \n _________________________________________________________________\n dropout_2 (Dropout) (None, 9, 9, 128) 0 \n _________________________________________________________________\n conv2d_3 (Conv2D) (None, 5, 5, 256) 819456 \n _________________________________________________________________\n leaky_re_lu_3 (LeakyReLU) (None, 5, 5, 256) 0 \n _________________________________________________________________\n flatten (Flatten) (None, 6400) 0 \n _________________________________________________________________\n dropout_3 (Dropout) (None, 6400) 0 \n _________________________________________________________________\n dense_4 (Dense) (None, 1) 6401 \n =================================================================\n Total params: 1,132,801\n Trainable params: 1,132,801\n Non-trainable params: 0\n _________________________________________________________________\n\n\nFeel free to try to train it at home! For this tutorial, we will just load in pre-trained weights.\n\n\n```python\ncnn_model.fit(\n images_train, labels_train,\n epochs=100,\n batch_size=512,\n validation_data=(images_val, labels_val),\n callbacks=[\n EarlyStopping(verbose=True, patience=30, monitor='val_loss'),\n ModelCheckpoint('./models/cnn-model.h5', monitor='val_loss',\n verbose=True, save_best_only=True)\n ]\n)\n```\n\n\n```python\ncnn_history = cnn_model.history.history\n```\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(cnn_history['acc']), label='training')\nplt.plot(100 * np.array(cnn_history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(cnn_history['loss']), label='training')\nplt.plot(100 * np.array(cnn_history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\nplt.vlines(np.argmin(cnn_history['val_loss']), 43, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(cnn_history['val_loss']))\n```\n\n\n```python\ncnn_model.load_weights('models/cnn-model.h5')\nyhat_cnn = cnn_model.predict(images_test, batch_size=512, verbose=True)\n```\n\n## Locally-Connected Neural Network\n\n\n```python\nfrom keras.layers import LocallyConnected2D , MaxPool2D, Flatten\n```\n\n\n```python\nx = Input(shape=(images_train.shape[1:]))\nh = LocallyConnected2D(32, kernel_size=9, strides=2)(x)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = LocallyConnected2D(32, kernel_size=5, strides=1)(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = LocallyConnected2D(64, kernel_size=3, strides=1)(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = LocallyConnected2D(64, kernel_size=3, strides=1)(h)\nh = LeakyReLU()(h)\n\nh = Flatten()(h)\nh = Dropout(0.2)(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\nlcn_model = Model(x, y)\nlcn_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\n\n```python\nlcn_model.summary()\n```\n\nFeel free to try to train it at home! For this tutorial, we will just load in pre-trained weights.\n\n\n```python\n# lcn_model.fit(\n# images_train, labels_train,\n# epochs=100,\n# batch_size=256,\n# validation_data=(images_val, labels_val),\n# callbacks=[\n# EarlyStopping(verbose=True, patience=30, monitor='val_loss'),\n# ModelCheckpoint('./models/lcn-model.h5', monitor='val_loss',\n# verbose=True, save_best_only=True)\n# ]\n# )\n```\n\n\n```python\nlcn_history = lcn_model.history.history\n```\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(lcn_history['acc']), label='training')\nplt.plot(100 * np.array(lcn_history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(lcn_history['loss']), label='training')\nplt.plot(100 * np.array(lcn_history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\nplt.vlines(np.argmin(lcn_history['val_loss']), 43, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(lcn_history['val_loss']))\n```\n\n\n```python\nlcn_model.load_weights('models/lcn-model.h5')\nyhat_lcn = lcn_model.predict(images_test, batch_size=512)\n```\n\n## Fully-Connected network\n\n\n```python\nx = Input(shape=(images_train.shape[1:]))\nh = Flatten()(x)\nh = Dense(25 ** 2, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = Dense(512, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = Dense(256, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\nh = Dense(128, kernel_initializer='he_normal')(h)\nh = LeakyReLU()(h)\n\nh = Dropout(0.2)(h)\ny = Dense(1, activation='sigmoid')(h)\n```\n\n\n```python\ndense_model = Model(x, y)\ndense_model.compile('adam', 'binary_crossentropy', metrics=['acc'])\n```\n\n\n```python\ndense_model.fit(\n images_train, labels_train,\n epochs=100,\n batch_size=256,\n validation_data=(images_val, labels_val),\n callbacks=[\n EarlyStopping(verbose=True, patience=30, monitor='val_loss'),\n ModelCheckpoint('./models/dense-model.h5', monitor='val_loss',\n verbose=True, save_best_only=True)\n ]\n)\n```\n\n\n```python\ndense_history = dense_model.history.history\n```\n\n\n```python\n# accuracy plot\nplt.plot(100 * np.array(dense_history['acc']), label='training')\nplt.plot(100 * np.array(dense_history['val_acc']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('accuracy %')\nplt.legend(loc='lower right', fontsize=20)\nplt.show()\n```\n\n\n```python\n# loss plot\nplt.plot(100 * np.array(dense_history['loss']), label='training')\nplt.plot(100 * np.array(dense_history['val_loss']), label='validation')\nplt.xlim(0)\nplt.xlabel('epoch')\nplt.ylabel('loss')\nplt.legend(loc='upper right', fontsize=20)\n# the line indicate the epoch corresponding to the best performance on the validation set\nplt.vlines(np.argmin(dense_history['val_loss']), 43, 56, linestyle='dashed', linewidth=0.5)\nplt.show()\n```\n\n\n```python\nprint 'Loss estimate on unseen examples (from validation set) = {0:.3f}'.format(np.min(dense_history['val_loss']))\n```\n\n\n```python\ndense_model.load_weights('models/dense-model.h5')\nyhat_dense = dense_model.predict(images_test, batch_size=512, verbose=True)\n```\n\n## Plot ROC Curves\n\nA standard way to visualize the tradeoff between low false positive rate (FPR) and high true positive rate (TPR) is by plotting them on a ROC curve. In Physics, people like to plot the TPR on the x-axis, and 1/FPR on the y-axis.\n\n\n```python\nfrom sklearn.metrics import roc_curve\n```\n\n\n```python\nfpr_cnn, tpr_cnn, _ = roc_curve(labels_test, yhat_cnn)\nfpr_lcn, tpr_lcn, _ = roc_curve(labels_test, yhat_lcn)\nfpr_dense, tpr_dense, _ = roc_curve(labels_test, yhat_dense)\nfpr_baseline, tpr_baseline, _ = roc_curve(labels_test, yhat_baseline)\n```\n\n\n```python\nplt.figure(figsize=(10,10))\nplt.grid(b = True, which = 'minor')\nplt.grid(b = True, which = 'major')\n_ = plt.plot(tpr_cnn, 1./fpr_cnn, label='CNN')\n_ = plt.plot(tpr_lcn, 1./fpr_lcn, label='LCN')\n_ = plt.plot(tpr_dense, 1./fpr_dense, label='FCN')\n_ = plt.plot(tpr_baseline, 1./fpr_baseline, label='Baseline')\nplt.legend()\nplt.xlim((0.1, 0.9))\nplt.ylim((1, 1000))\nplt.yscale('log')\n```\n\n## What is the network learning?\n\n\n```python\ndef get_correlations(images, disc_output):\n '''\n calculate linear correlation between each pixel and the output of the classifier\n to see what pixels are more indicative of a specific class.\n '''\n import pandas as pd\n # -- find the total number of pixels per image, here 25 x 25\n n_pixels = np.prod(images.shape[1:3])\n \n # -- add the pixels as columns to a dataframe\n df = pd.DataFrame(\n {i : np.squeeze(images).reshape(-1, n_pixels)[:, i] for i in range(n_pixels)}\n )\n # -- add a column to the end of the dataframe for the discriminator's output\n df['disc_output'] = disc_output\n # -- pandas offers an easy solution to calculate correlations \n # (even though it's slow because it also calculates the correlation between each pixel and every other pixel)\n correlations = df.corr().values[:-1, -1]\n return correlations\n\ndef plot_correlations(correlations, extent, title='', img_dim=(25, 25), cmap=plt.cm.seismic):\n '''\n call the function about and then plot the correlations in image format\n '''\n max_mag = max(\n abs(np.min(correlations[np.isfinite(correlations)])),\n abs(np.max(correlations[np.isfinite(correlations)])),\n ) # highest correlation value (abs value), to make the plot look nice and on a reasonable scale\n\n f, ax = plt.subplots(figsize=(6, 6))\n im = ax.imshow(\n correlations.reshape(img_dim),\n interpolation='nearest',\n norm=Normalize(vmin=-max_mag, vmax=max_mag),\n extent=extent,\n cmap=cmap\n )\n \n plt.colorbar(im, fraction=0.05, pad=0.05)\n plt.xlabel(r'[Transformed] Pseudorapidity $(\\eta)$')\n plt.ylabel(r'[Transformed] Azimuthal Angle $(\\phi)$')\n plt.title(title)\n# plt.savefig(os.path.join('..', outdir, outname))\n```\n\nYou can now visualize what each network picks up on, at least to first order. These correlation plots tells us whether a specific pixel being strongly activated is a good indicator of that jet image belonging to a class or the other. Red represents the signal (boosted W from W'-->WZ), blue represents the background (QCD).\n\n\n```python\nplot_correlations(\n get_correlations(images_test[:10000], yhat_cnn[:10000]),\n extent=[-1.25, 1.25, -1.25, 1.25],\n title='Correlation between pixels \\n and the CNN prediction'\n)\n```\n\n\n```python\nplot_correlations(\n get_correlations(images_test[:10000], yhat_lcn[:10000]),\n extent=[-1.25, 1.25, -1.25, 1.25],\n title='Correlation between pixels \\n and the LCN prediction'\n)\n```\n\n\n```python\nplot_correlations(\n get_correlations(images_test[:10000], yhat_dense[:10000]),\n extent=[-1.25, 1.25, -1.25, 1.25],\n title='Correlation between pixels \\n and the FCN prediction'\n)\n```\n\n\n```python\nplot_correlations(\n get_correlations(images_test[:10000], yhat_baseline[:10000]),\n extent=[-1.25, 1.25, -1.25, 1.25],\n title='Correlation between pixels \\n and the Baseline prediction'\n)\n```\n\nYou can also look at how the output of each classifier is correlated with known quantities that are known to be discriminative, such as the ones used in the baseline classifier above (mass, tau_21, delta_R). This will inform us as to whether the network has 'learned' to internally calculate a representation that is close to these variables, thus eliminating our need to come up with these features ourselves.\n\n\n```python\ndef plot_output_vs_kin(kin, output, xlabel, ylabel, nbins=30):\n '''\n Plot one output of the discriminator network vs. one of the 1D physics variables that describe jets\n Args:\n -----\n kin : numpy array, kinematic property (such as mass or pT) associated with each image. I.e.: discrete_mass(np.squeeze(generated_images))\n output : numpy array, one of the 2 outputs of the discriminator, evaluated on the same images that `kin` refers to\n xlabel : string, x-axis label that describes the meaning of `kin`\n ylabel : string, y-axis label that describes the meaning og `output`\n outname : name of the output file, to be placed in ../plots/\n nbins : (default = 30) number of bins to use to represent the distributions in a discretized way\n \n '''\n # set the colormap\n plt.set_cmap('jet')\n # draw a 2d histogram of the discriminator's output versus the kinematic variable of choice (mass, pT, etc.)\n h, binx, biny, _ = plt.hist2d(kin, output.reshape(-1,), bins=nbins)\n plt.clf() # we don't want to plot this 2D histogram, we want to normalize it per bin first\n \n # normalize the histogram such that the entries in each column add up to 1, such that the intensity\n # of each corresponds to the percentage of the jets in a given mass (or pT) bin that get assigned a p\n for i in range(nbins):\n h[i, :] = h[i, :] / float(np.sum(h[i, :]))\n # plot the normalized histogram as an image\n f, ax2 = plt.subplots(figsize=(6, 6))\n im = ax2.imshow(\n np.flipud(h.T), \n interpolation='nearest',\n norm=LogNorm(),\n extent=[binx.min(), binx.max(), biny.min(), biny.max()],\n aspect=\"auto\"\n )\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n # add a custom colorbar\n cax = f.add_axes([0.93, 0.1, 0.03, 0.8])\n plt.colorbar(im, cax = cax)\n plt.set_cmap('viridis')\n```\n\n### Mass\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 0], # mass\n yhat_cnn,\n xlabel='Discrete jet image mass (GeV)',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 0], # mass\n yhat_lcn,\n xlabel='Discrete jet image mass (GeV)',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 0], # mass\n yhat_dense,\n xlabel='Discrete jet image mass (GeV)',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 0], # mass\n yhat_baseline,\n xlabel='Discrete jet image mass (GeV)',\n ylabel='P(signal)',\n)\n```\n\n### Tau_21\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 1], # tau21\n yhat_cnn,\n xlabel=r'Discrete jet $\\tau_{21}$',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 1], # tau21\n yhat_lcn,\n xlabel=r'Discrete jet $\\tau_{21}$',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 1], # tau21\n yhat_dense,\n xlabel=r'Discrete jet $\\tau_{21}$',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 1], # tau21\n yhat_baseline,\n xlabel=r'Discrete jet $\\tau_{21}$',\n ylabel='P(signal)',\n)\n```\n\n### Delta R\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 2], # deltaR\n yhat_cnn,\n xlabel=r'Discrete jet $\\Delta R$',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 2], # deltaR\n yhat_lcn,\n xlabel=r'Discrete jet $\\Delta R$',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 2], # deltaR\n yhat_dense,\n xlabel=r'Discrete jet $\\Delta R$',\n ylabel='P(signal)',\n)\n```\n\n\n```python\nplot_output_vs_kin(\n scaler.inverse_transform(features_test)[:, 2], # deltaR\n yhat_baseline,\n xlabel=r'Discrete jet $\\Delta R$',\n ylabel='P(signal)',\n)\n```\n\nSometimes, however, it is not a good idea to have your network learn the mass of a jet and use that to classify jets. In that case, in fact, the network will successfully suppress all jets outside of the signal-like mass window and sculpt the mass of the background to look like a signal peak. \n\nWhat we would like to be able to do, instead, is to have a classifier that is insensitive to mass, and that reduced the background across the entire mass spectrum. \n\nFor reference, see: C. Shimmin et al., Decorrelated Jet Substructure Tagging using Adversarial Neural Networks.\n\n# Training a GAN (WGAN-GP) on jet images\n\nWGAN-GP = a type of GAN that minimizes the Wasserstein distance between the target and generated distributions and enforces the Lipschitz contraint by penalizing the norm of the gradient instead of clipping weights.\n\n\n```python\nfrom keras.layers import Input, Dense, Reshape, Flatten\nfrom keras.layers.merge import _Merge\nfrom keras.layers.convolutional import Convolution2D, Conv2DTranspose\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n```\n\n\n```python\nBATCH_SIZE = 100\n\n# The training ratio is the number of discriminator updates per generator\n# update. The paper uses 5.\nTRAINING_RATIO = 5\nGRADIENT_PENALTY_WEIGHT = 10 # As per the paper\n```\n\nDefine new custom loss functions not included among the standard keras ones:\n\n\n```python\ndef wasserstein_loss(y_true, y_pred):\n return K.mean(y_true * y_pred)\n\n\ndef gradient_penalty_loss(y_true, y_pred, averaged_samples,\n gradient_penalty_weight):\n gradients = K.gradients(K.sum(y_pred), averaged_samples)\n gradient_l2_norm = K.sqrt(K.sum(K.square(gradients)))\n gradient_penalty = gradient_penalty_weight * K.square(1 - gradient_l2_norm)\n return gradient_penalty\n```\n\n\n```python\ndef make_generator():\n \"\"\"Creates a generator model that takes a 100-dimensional latent prior and \n converts to size 25 x 25 x 1\"\"\"\n\n z = Input(shape=(100, ))\n \n x = Dense(1024, input_dim=100)(z)\n x = LeakyReLU()(x)\n\n x = Dense(128 * 7 * 7)(x)\n x = BatchNormalization()(x)\n x = LeakyReLU()(x)\n\n x = Reshape((7, 7, 128))(x)\n\n x = Conv2DTranspose(128, (5, 5), strides=2, padding='same')(x)\n x = BatchNormalization(axis=-1)(x)\n x = LeakyReLU()(x)\n\n x = Convolution2D(64, (5, 5), padding='same')(x)\n x = BatchNormalization(axis=-1)(x)\n x = LeakyReLU()(x)\n\n x = Conv2DTranspose(64, (5, 5), strides=2, padding='same')(x)\n x = BatchNormalization(axis=-1)(x)\n x = LeakyReLU()(x)\n\n y = Convolution2D(1, (4, 4), padding='valid', activation='relu')(x)\n\n return Model(z, y)\n```\n\n\n```python\ndef make_discriminator():\n\n x = Input(shape=(25, 25, 1))\n \n h = Convolution2D(64, (5, 5), padding='same')(x)\n h = LeakyReLU()(h)\n\n h = Convolution2D(128, (5, 5), kernel_initializer='he_normal',\n strides=2)(h)\n h = LeakyReLU()(h)\n\n h = Convolution2D(256, (5, 5), kernel_initializer='he_normal',\n padding='same', strides=2)(h)\n h = LeakyReLU()(h)\n\n h = Flatten()(h)\n h = Dense(1024, kernel_initializer='he_normal')(h)\n h = LeakyReLU()(h)\n\n y = Dense(1, kernel_initializer='he_normal')(h)\n\n return Model(x, y)\n```\n\nBuild individual models:\n\n\n```python\ngenerator = make_generator()\ndiscriminator = make_discriminator()\n```\n\nBuild connected model with only generator trainable:\n\n\n```python\ndiscriminator.trainable = False\nz = Input(shape=(100, ))\ngenerator_model = Model(z, discriminator(generator(z)))\n# We use the Adam paramaters from Gulrajani et al.\ngenerator_model.compile(optimizer=Adam(0.0001, beta_1=0.5, beta_2=0.9),\n loss=wasserstein_loss)\n```\n\nBuild connected model with only discriminator trainable:\n\n\n```python\ndiscriminator.trainable = True\ngenerator.trainable = False\n```\n\n\n```python\nclass RandomWeightedAverage(_Merge): # used for gradient norm penalty\n\n def _merge_function(self, inputs):\n weights = K.random_uniform((K.shape(inputs[0])[0], 1, 1, 1))\n return (weights * inputs[0]) + ((1 - weights) * inputs[1])\n```\n\n\n```python\nreal_samples = Input(shape=(25, 25, 1))\nz = Input(shape=(100,))\nfake_samples = generator(z)\n\ncritic_out_fake = discriminator(fake_samples)\ncritic_out_real = discriminator(real_samples)\n\n# generate weighted-averages of real and generated\n# samples, to use for the gradient norm penalty.\naveraged_samples = RandomWeightedAverage()([real_samples, fake_samples])\n\n# running them thru critic to get the gradient norm for the GP loss.\naveraged_samples_out = discriminator(averaged_samples)\n\n# The gradient penalty loss function requires the input averaged samples\ndef gp_loss(y_true, y_pred):\n return gradient_penalty_loss(\n y_true, y_pred,\n averaged_samples=averaged_samples,\n gradient_penalty_weight=GRADIENT_PENALTY_WEIGHT\n )\n\ndiscriminator_model = Model(\n inputs=[real_samples, z],\n outputs=[critic_out_real, critic_out_fake, averaged_samples_out]\n)\n\n# We use the Adam paramaters from Gulrajani et al.\ndiscriminator_model.compile(\n optimizer=Adam(0.0001, beta_1=0.5, beta_2=0.9),\n loss=[wasserstein_loss, wasserstein_loss, gp_loss]\n)\n```\n\n\n```python\n# positive_y is the label vector for real samples, with value 1.\n# negative_y is the label vector for generated samples, with value -1.\n# dummy_y vector is passed to the gradient_penalty loss function and is\n# not used.\n\npositive_y = np.ones((BATCH_SIZE, 1), dtype=np.float32)\nnegative_y = -positive_y\ndummy_y = np.zeros((BATCH_SIZE, 1), dtype=np.float32)\n```\n\n\n```python\n# do a little bit of scaling for stability\nX_train = np.expand_dims(np.squeeze(images_train[:30000]) / 100, -1)\n```\n\n\n```python\noverall_disc_loss = []\n\nfor epoch in range(200): # train for 200 iterations\n\n # at each epoch, shuffle the training set to get new samples\n np.random.shuffle(X_train)\n print(\"Epoch: \", epoch)\n print(\"Number of batches: \", int(X_train.shape[0] // BATCH_SIZE))\n discriminator_loss = []\n generator_loss = []\n\n # we'll need this many samples per critic update\n critic_nb_samples = BATCH_SIZE * TRAINING_RATIO\n\n # loop through batches\n for i in range(int(X_train.shape[0] // (BATCH_SIZE * TRAINING_RATIO))):\n X_critic = X_train[i * critic_nb_samples:(i + 1) * critic_nb_samples]\n\n # critic gets trained 5 times more per iteration than the generator\n for j in range(TRAINING_RATIO):\n X_minibatch = X_critic[j * BATCH_SIZE:(j + 1) * BATCH_SIZE]\n\n # generate new input noise\n noise = np.random.rand(BATCH_SIZE, 100).astype(np.float32)\n\n # train the discriminator (or critic)\n disc_loss = discriminator_model.train_on_batch(\n [X_minibatch, noise],\n [positive_y, negative_y, dummy_y]\n )\n discriminator_loss.append(disc_loss)\n \n critic_score = np.array(discriminator_loss)[:, 0]\n if i % 10 == 0:\n print('critic score =', critic_score.mean())\n overall_disc_loss.extend(critic_score.tolist())\n # train the generator\n gen_loss = generator_model.train_on_batch(\n np.random.rand(BATCH_SIZE, 100),\n positive_y\n )\n generator_loss.append(gen_loss)\n```\n\n\n```python\n# discriminator.save_weights('./models/wgan-discriminator.h5')\n# generator.save_weights('./models/wgan-generator.h5')\n```\n\nLoad pre-trained wights:\n\n\n```python\ndiscriminator.load_weights('./models/wgan-discriminator.h5')\ngenerator.load_weights('./models/wgan-generator.h5')\n```\n\nNow that we have a trained GAN, we can see if it actually works and what it produces. We can now get rid of the critic (discriminator) and focus only on the part that we really care about, the generator. Let's execute a forward pass on the generator.\n\n\n```python\n# input noise that will be transformed into jet images\nnoise = np.random.rand(1000, 100).astype(np.float32)\n```\n\n\n```python\n# produce some jet images from the generator!\nfake_jets = generator.predict(noise, batch_size=BATCH_SIZE, verbose=True)\n\n# rescale energies and remove redundant dimension for grayscale channel\nfake_jets = np.squeeze(fake_jets * 100)\n```\n\nLet's look at some GAN-generated jet images!\n\n\n```python\nplot_jet_image(fake_jets.mean(0))\n```\n\nWe can also look at the difference between the average generated image and the average real image to identify parts of the image that are not well-captured by the GAN and might need improvement. Green pixels are more strongly activated, on average, in fake images, while purple pixels are more strongly activated in background images.\n\n\n```python\nplot_diff_jet_image(fake_jets.mean(0) - images.mean(0), cmap='PRGn')\n```\n\nThere are multiple ways of imporving this training, such as conditioning on class or attributes, using minibatch discrimination, enforcing physical constraints, etc.\n", "meta": {"hexsha": "fd2c3547505462cad3d372b776f3641644b98d48", "size": 274772, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jet_images.ipynb", "max_stars_repo_name": "trasousa/ENEF21", "max_stars_repo_head_hexsha": "38b948547924e4306aceadbd80c890653d202005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jet_images.ipynb", "max_issues_repo_name": "trasousa/ENEF21", "max_issues_repo_head_hexsha": "38b948547924e4306aceadbd80c890653d202005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jet_images.ipynb", "max_forks_repo_name": "trasousa/ENEF21", "max_forks_repo_head_hexsha": "38b948547924e4306aceadbd80c890653d202005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 103.6093514329, "max_line_length": 35784, "alphanum_fraction": 0.8271039262, "converted": true, "num_tokens": 16451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.3466358157701712}} {"text": "
\n\n \n## [mlcourse.ai](https://mlcourse.ai) – Open Machine Learning Course \n\nAuthor: [Egor Polusmak](https://www.linkedin.com/in/egor-polusmak/). Translated and edited by [Yuanyuan Pao](https://www.linkedin.com/in/yuanyuanpao/). This material is subject to the terms and conditions of the [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license. Free use is permitted for any non-commercial purpose.\n\n#
Topic 9. Time series analysis in Python
\n##
Part 2. Predicting the future with Facebook Prophet
\n\nTime series forecasting finds wide application in data analytics. These are only some of the conceivable predictions of future trends that might be useful:\n- The number of servers that an online service will need next year.\n- The demand for a grocery product at a supermarket on a given day.\n- The tomorrow closing price of a tradable financial asset.\n\nFor another example, we can make a prediction of some team's performance and then use it as a baseline: first to set goals for the team, and then to measure the actual team performance relative to the baseline.\n\nThere are quite a few different methods to predict future trends, for example, [ARIMA](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average), [ARCH](https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity), [regressive models](https://en.wikipedia.org/wiki/Autoregressive_model), [neural networks](https://medium.com/machine-learning-world/neural-networks-for-algorithmic-trading-1-2-correct-time-series-forecasting-backtesting-9776bfd9e589).\n\nIn this article, we will look at [Prophet](https://facebook.github.io/prophet/), a library for time series forecasting released by Facebook and open-sourced on February 23, 2017. We will also try it out in the problem of predicting the daily number of posts published on Medium.\n\n## Article outline\n\n1. Introduction\n2. The Prophet Forecasting Model\n3. Practice with Prophet\n * 3.1 Installation in Python\n * 3.2 Dataset\n * 3.3 Exploratory visual analysis\n * 3.4 Making a forecast\n * 3.5 Forecast quality evaluation\n * 3.6 Visualization\n4. Box-Cox Transformation\n5. Summary\n6. References\n\n## 1. Introduction\n\nAccording to the [article](https://research.fb.com/prophet-forecasting-at-scale/) on Facebook Research, Prophet was initially developed for the purpose of creating high quality business forecasts. This library tries to address the following difficulties common to many business time series:\n- Seasonal effects caused by human behavior: weekly, monthly and yearly cycles, dips and peaks on public holidays.\n- Changes in trend due to new products and market events.\n- Outliers.\n\nThe authors claim that, even with the default settings, in many cases, their library produces forecasts as accurate as those delivered by experienced analysts.\n\nMoreover, Prophet has a number of intuitive and easily interpretable customizations that allow gradually improving the quality of the forecasting model. What is especially important, these paramaters are quite comprehensible even for non-experts in time series analysis, which is a field of data science requiring certain skill and experience.\n\nBy the way, the original article is called \"Forecasting at Scale\", but it is not about the scale in the \"usual\" sense, that is addressing computational and infrastructure problems of a large number of working programs. According to the authors, Prophet should scale well in the following 3 areas:\n- Accessibility to a wide audience of analysts, possibly without profound expertise in time series.\n- Applicability to a wide range of distinct forecasting problems.\n- Automated performance estimation of a large number of forecasts including flagging of potential problems for their subsequent inspection by the analyst.\n\n## 2. The Prophet Forecasting Model\n\nNow, let's take a closer look at how Prophet works. In its essence, this library utilizes the [additive regression model](https://en.wikipedia.org/wiki/Additive_model) $y(t)$ comprising the following components:\n\n$$y(t) = g(t) + s(t) + h(t) + \\epsilon_{t},$$\n\nwhere:\n* Trend $g(t)$ models non-periodic changes.\n* Seasonality $s(t)$ represents periodic changes.\n* Holidays component $h(t)$ contributes information about holidays and events.\n\nBelow, we will consider some important properties of these model components.\n\n### Trend\n\nThe Prophet library implements two possible trend models for $g(t)$.\n\nThe first one is called *Nonlinear, Saturating Growth*. It is represented in the form of the [logistic growth model](https://en.wikipedia.org/wiki/Logistic_function):\n\n$$g(t) = \\frac{C}{1+e^{-k(t - m)}},$$\n\nwhere:\n* $C$ is the carrying capacity (that is the curve's maximum value).\n* $k$ is the growth rate (which represents \"the steepness\" of the curve).\n* $m$ is an offset parameter.\n\nThis logistic equation allows modelling non-linear growth with saturation, that is when the growth rate of a value decreases with its growth. One of the typical examples would be representing the growth of the audience of an application or a website.\n\nActually, $C$ and $k$ are not necessarily constants and may vary over time. Prophet supports both automatic and manual tuning of their variability. The library can itself choose optimal points of trend changes by fitting the supplied historical data. \n\nAlso, Prophet allows analysts to manually set changepoints of the growth rate and capacity values at different points in time. For instance, analysts may have insights about dates of past releases that prominently influenced some key product indicators.\n\nThe second trend model is a simple *Piecewise Linear Model* with a constant rate of growth. It is best suited for problems without saturating growth.\n\n### Seasonality\n\nThe seasonal component $s(t)$ provides a flexible model of periodic changes due to weekly and yearly seasonality.\n\nWeekly seasonal data is modeled with dummy variables. Six new variables are added: `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`, which take values 0 or 1 depending on the day of the week. The feature `sunday` is not added because it would be a linear combination of the other days of the week, and this fact would have an adverse effect on the model.\n\nYearly seasonality model in Prophet relies on Fourier series.\n\nSince [version 0.2](https://github.com/facebook/prophet) you can also use *sub-daily time series* and make *sub-daily forecasts* as well as employ the new *daily seasonality* feature.\n\n### Holidays and Events\n\nThe component $h(t)$ represents predictable abnormal days of the year including those on irregular schedules, e.g., Black Fridays.\n\nTo utilize this feature, the analyst needs to provide a custom list of events.\n\n### Error\n\nThe error term $\\epsilon(t)$ represents information that was not reflected in the model. Usually it is modeled as normally distributed noise.\n\n### Prophet Benchmarking\n\nFor a detailed description of the model and algorithms behind Prophet refer to the paper [\"Forecasting at scale\"](https://peerj.com/preprints/3190/) by Sean J. Taylor and Benjamin Letham.\n\nThe authors also compared their library with several other methods for time series forecasting. They used [Mean Absolute Percentage Error (MAPE)](https://en.wikipedia.org/wiki/Mean_absolute_percentage_error) as a measure of prediction accuracy. In this research, Prophet has shown substantially lower forecasting error than the other models.\n\n\n\nLet's look closer at how the forcasting quality was measured in the article. To do this, we will need the formula of Mean Absolute Percentage Error.\n\nLet $y_{i}$ be the *actual (historical) value* and $\\hat{y}_{i}$ be the *forecast value* given by our model.\n\nThen $e_{i} = y_{i} - \\hat{y}_{i}$ is the *forecast error* and $p_{i} =\\frac{\\displaystyle e_{i}}{\\displaystyle y_{i}}$ is the *relative forecast error*.\n\nWe define\n\n$$MAPE = mean\\big(\\left |p_{i} \\right |\\big)$$\n\nMAPE is widely used as a measure of prediction accuracy because it expresses error as a percentage and thus can be used in model evaluations on different datasets.\n\nIn addition, when evaluating a forecasting algorithm, it may prove useful to calculate [MAE (Mean Absolute Error)](https://en.wikipedia.org/wiki/Mean_absolute_error) in order to have a picture of errors in absolute numbers. Using previously defined components, its equation will be\n\n$$MAE = mean\\big(\\left |e_{i}\\right |\\big)$$\n\nA few words about the algorithms that Prophet was compared with. Most of them are quite simple and often are used as a baseline for other models:\n* `naive` is a simplistic forecasting approach where we predict all future values relying solely on the observation at the last available point of time.\n* `snaive` (seasonal naive) is a model that makes constant predictions taking into account information about seasonality. For instance, in the case of weekly seasonal data for each future Monday, we would predict the value from the last Monday, and for all future Tuesdays we would use the value from the last Tuesday and so on.\n* `mean` uses the averaged value of data as a forecast.\n* `arima` stands for *Autoregressive Integrated Moving Average*, see [Wikipedia](https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average) for details.\n* `ets` stands for *Exponential Smoothing*, see [Wikipedia](https://en.wikipedia.org/wiki/Exponential_smoothing) for more.\n\n## 3. Practice with Facebook Prophet\n\n### 3.1 Installation in Python\n\nFirst, you need to install the library. Prophet is available for Python and R. The choice will depend on your personal preferences and project requirements. Further in this article we will use Python.\n\nIn Python you can install Prophet using PyPI:\n```\n$ pip install fbprophet\n```\n\nIn R you can find the corresponing CRAN package. Refer to the [documentation](https://facebookincubator.github.io/prophet/docs/installation.html) for details.\n\nLet's import the modules that we will need, and initialize our environment:\n\n\n```python\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nfrom scipy import stats\n\n%matplotlib inline\n```\n\n### 3.2 Dataset\n\nWe will predict the daily number of posts published on [Medium](https://medium.com/).\n\nFirst, we load our dataset.\n\n\n```python\ndf = pd.read_csv(\"../../data/medium_posts.csv.zip\", sep=\"\\t\")\n```\n\nNext, we leave out all columns except `published` and `url`. The former corresonds to the time dimension while the latter uniquely identifies a post by its URL. Along the way we get rid of possible duplicates and missing values in the data:\n\n\n```python\ndf = df[[\"published\", \"url\"]].dropna().drop_duplicates()\n```\n\nNext, we need to convert `published` to the datetime format because by default `pandas` treats this field as string-valued.\n\n\n```python\ndf[\"published\"] = pd.to_datetime(df[\"published\"])\n```\n\nLet's sort the dataframe by time and take a look at what we've got:\n\n\n```python\ndf.sort_values(by=[\"published\"]).head(n=3)\n```\n\nMedium's public release date was August 15, 2012. But, as you can see from the data above, there are at least several rows with much earlier publication dates. They have somehow turned up in our dataset, but they are hardly legitimate ones. We will just trim our time series to keep only those rows that fall onto the period from August 15, 2012 to June 25, 2017:\n\n\n```python\ndf = df[\n (df[\"published\"] > \"2012-08-15\") & (df[\"published\"] < \"2017-06-26\")\n].sort_values(by=[\"published\"])\ndf.head(n=3)\n```\n\n\n```python\ndf.tail(n=3)\n```\n\nAs we are going to predict the number of published posts, we will aggregate and count unique posts at each given point in time. We will name the corresponding new column `posts`:\n\n\n```python\naggr_df = df.groupby(\"published\")[[\"url\"]].count()\naggr_df.columns = [\"posts\"]\n```\n\nIn this practice, we are interested in the number of posts **a day**. But at this moment all our data is divided into irregular time intervals that are less than a day. This is called a *sub-daily time series*. To see it, let's print out the first 3 rows:\n\n\n```python\naggr_df.head(n=3)\n```\n\nTo fix this, we need to aggregate the post counts by \"bins\" of a date size. In time series analysis, this process is referred to as *resampling*. And if we *reduce* the sampling rate of data it is often called *downsampling*.\n\nLuckily, `pandas` has a built-in functionality for this task. We will resample our time index down to 1-day bins:\n\n\n```python\ndaily_df = aggr_df.resample(\"D\").apply(sum)\ndaily_df.head(n=3)\n```\n\n### 3.3 Exploratory visual analysis\n\nAs always, it may be helpful and instructive to look at a graphical representation of your data.\n\nWe will create a time series plot for the whole time range. Displaying data over such a long period of time can give clues about seasonality and conspicuous abnormal deviations.\n\nFirst, we import and initialize the `Plotly` library, which allows creating beautiful interactive plots:\n\n\n```python\nfrom plotly import graph_objs as go\nfrom plotly.offline import init_notebook_mode, iplot\n\n# Initialize plotly\ninit_notebook_mode(connected=True)\n```\n\nWe also define a helper function, which will plot our dataframes throughout the article:\n\n\n```python\ndef plotly_df(df, title=\"\"):\n \"\"\"Visualize all the dataframe columns as line plots.\"\"\"\n common_kw = dict(x=df.index, mode=\"lines\")\n data = [go.Scatter(y=df[c], name=c, **common_kw) for c in df.columns]\n layout = dict(title=title)\n fig = dict(data=data, layout=layout)\n iplot(fig, show_link=False)\n```\n\nLet's try and plot our dataset *as is*:\n\n\n```python\nplotly_df(daily_df, title=\"Posts on Medium (daily)\")\n```\n\nHigh-frequency data can be rather difficult to analyze. Even with the ability to zoom in provided by `Plotly`, it is hard to infer anything meaningful from this chart apart from the prominent upward and accelerating trend.\n\nTo reduce the noise, we will resample the post counts down to weekly bins. Besides *binning*, other possible techniques of noise reduction include [Moving-Average Smoothing](https://en.wikipedia.org/wiki/Moving_average) and [Exponential Smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing), among others.\n\nWe save our downsampled dataframe in a separate variable because further in this practice we will work only with daily series:\n\n\n```python\nweekly_df = daily_df.resample(\"W\").apply(sum)\n```\n\nFinally, we plot the result:\n\n\n```python\nplotly_df(weekly_df, title=\"Posts on Medium (weekly)\")\n```\n\nThis downsampled chart proves to be somewhat better for an analyst's perception.\n\nOne of the most useful functions that `Plotly` provides is the ability to quickly dive into different periods of timeline in order to better understand the data and find visual clues about possbile trends, periodic and irregular effects. \n\nFor example, zooming-in on a couple of consecutive years shows us time points corresponding to Christmas holidays, which greatly influence human behaviors.\n\nNow, we're going to omit the first few years of observations, up to 2015. First, they won't contribute much into the forecast quality in 2017. Second, these first years, having very low number of posts per day, are likely to increase noise in our predictions, as the model would be forced to fit this abnormal historical data along with more relevant and indicative data from the recent years.\n\n\n```python\ndaily_df = daily_df.loc[daily_df.index >= \"2015-01-01\"]\ndaily_df.head(n=3)\n```\n\nTo sum up, from visual analysis we can see that our dataset is non-stationary with a prominent growing trend. It also demonstrates weekly and yearly seasonality and a number of abnormal days in each year.\n\n### 3.4 Making a forecast\n\nProphet's API is very similar to the one you can find in `sklearn`. First we create a model, then call the method `fit`, and, finally, make a forecast. The input to the method `fit` is a `DataFrame` with two columns:\n* `ds` (datestamp) must be of type `date` or `datetime`.\n* `y` is a numeric value we want to predict.\n\nTo get started, we'll import the library and mute unimportant diagnostic messages:\n\n\n```python\nimport logging\n\nfrom fbprophet import Prophet\n\nlogging.getLogger().setLevel(logging.ERROR)\n```\n\nLet's convert our dataframe to the format required by Prophet:\n\n\n```python\ndf = daily_df.reset_index()\ndf.columns = [\"ds\", \"y\"]\n# converting timezones (issue https://github.com/facebook/prophet/issues/831)\ndf[\"ds\"] = df[\"ds\"].dt.tz_convert(None)\ndf.tail(n=3)\n```\n\nThe authors of the library generally advise to make predictions based on at least several months, ideally, more than a year of historical data. Luckily, in our case we have more than a couple of years of data to fit the model.\n\nTo measure the quality of our forecast, we need to split our dataset into the *historical part*, which is the first and biggest slice of our data, and the *prediction part*, which will be located at the end of the timeline. We will remove the last month from the dataset in order to use it later as a prediction target:\n\n\n```python\nprediction_size = 30\ntrain_df = df[:-prediction_size]\ntrain_df.tail(n=3)\n```\n\nNow we need to create a new `Prophet` object. Here we can pass the parameters of the model into the constructor. But in this article we will use the defaults. Then we train our model by invoking its `fit` method on our training dataset:\n\n\n```python\nm = Prophet()\nm.fit(train_df);\n```\n\nUsing the helper method `Prophet.make_future_dataframe`, we create a dataframe which will contain all dates from the history and also extend into the future for those 30 days that we left out before.\n\n\n```python\nfuture = m.make_future_dataframe(periods=prediction_size)\nfuture.tail(n=3)\n```\n\nWe predict values with `Prophet` by passing in the dates for which we want to create a forecast. If we also supply the historical dates (as in our case), then in addition to the prediction we will get an in-sample fit for the history. Let's call the model's `predict` method with our `future` dataframe as an input:\n\n\n```python\nforecast = m.predict(future)\nforecast.tail(n=3)\n```\n\nIn the resulting dataframe you can see many columns characterizing the prediction, including trend and seasonality components as well as their confidence intervals. The forecast itself is stored in the `yhat` column.\n\nThe Prophet library has its own built-in tools for visualization that enable us to quickly evaluate the result.\n\nFirst, there is a method called `Prophet.plot` that plots all the points from the forecast:\n\n\n```python\nm.plot(forecast);\n```\n\nThis chart doesn't look very informative. The only definitive conclusion that we can draw here is that the model treated many of the data points as outliers.\n\nThe second function `Prophet.plot_components` might be much more useful in our case. It allows us to observe different components of the model separately: trend, yearly and weekly seasonality. In addition, if you supply information about holidays and events to your model, they will also be shown in this plot.\n\nLet's try it out:\n\n\n```python\nm.plot_components(forecast);\n```\n\nAs you can see from the trend graph, Prophet did a good job by fitting the accelerated growth of new posts at the end of 2016. The graph of weekly seasonality leads to the conclusion that usually there are less new posts on Saturdays and Sundays than on the other days of the week. In the yearly seasonality graph there is a prominent dip on Christmas Day.\n\n### 3.5 Forecast quality evaluation\n\nLet's evaluate the quality of the algorithm by calculating the error metrics for the last 30 days that we predicted. For this, we will need the observations $y_i$ and the corresponding predicted values $\\hat{y}_i$.\n\nLet's look into the object `forecast` that the library created for us:\n\n\n```python\nprint(\", \".join(forecast.columns))\n```\n\nWe can see that this dataframe contains all the information we need except for the historical values. We need to join the `forecast` object with the actual values `y` from the original dataset `df`. For this we will define a helper function that we will reuse later:\n\n\n```python\ndef make_comparison_dataframe(historical, forecast):\n \"\"\"Join the history with the forecast.\n \n The resulting dataset will contain columns 'yhat', 'yhat_lower', 'yhat_upper' and 'y'.\n \"\"\"\n return forecast.set_index(\"ds\")[[\"yhat\", \"yhat_lower\", \"yhat_upper\"]].join(\n historical.set_index(\"ds\")\n )\n```\n\nLet's apply this function to our last forecast:\n\n\n```python\ncmp_df = make_comparison_dataframe(df, forecast)\ncmp_df.tail(n=3)\n```\n\nWe are also going to define a helper function that we will use to gauge the quality of our forecasting with MAPE and MAE error measures:\n\n\n```python\ndef calculate_forecast_errors(df, prediction_size):\n \"\"\"Calculate MAPE and MAE of the forecast.\n \n Args:\n df: joined dataset with 'y' and 'yhat' columns.\n prediction_size: number of days at the end to predict.\n \"\"\"\n\n # Make a copy\n df = df.copy()\n\n # Now we calculate the values of e_i and p_i according to the formulas given in the article above.\n df[\"e\"] = df[\"y\"] - df[\"yhat\"]\n df[\"p\"] = 100 * df[\"e\"] / df[\"y\"]\n\n # Recall that we held out the values of the last `prediction_size` days\n # in order to predict them and measure the quality of the model.\n\n # Now cut out the part of the data which we made our prediction for.\n predicted_part = df[-prediction_size:]\n\n # Define the function that averages absolute error values over the predicted part.\n error_mean = lambda error_name: np.mean(np.abs(predicted_part[error_name]))\n\n # Now we can calculate MAPE and MAE and return the resulting dictionary of errors.\n return {\"MAPE\": error_mean(\"p\"), \"MAE\": error_mean(\"e\")}\n```\n\nLet's use our function:\n\n\n```python\nfor err_name, err_value in calculate_forecast_errors(cmp_df, prediction_size).items():\n print(err_name, err_value)\n```\n\nAs a result, the relative error of our forecast (MAPE) is about 22.6%, and on average our model is wrong by ~70 posts (MAE).\n\n### 3.6 Visualization\n\nLet's create our own visualization of the model built by Prophet. It will comprise the actual values, forecast and confidence intervals.\n\nFirst, we will plot the data for a shorter period of time to make the data points easier to distinguish. Second, we will show the model performance only for the period that we predicted, that is the last 30 days. It seems that these two measures should give us a more legible plot.\n\nThird, we will use `Plotly` to make our chart interactive, which is great for exploring.\n\nWe will define a custom helper function `show_forecast` and call it (for more on how it works please refer to the comments in the code and the [documentation](https://plot.ly/python/)):\n\n\n```python\ndef show_forecast(cmp_df, num_predictions, num_values, title):\n \"\"\"Visualize the forecast.\"\"\"\n\n def create_go(name, column, num, **kwargs):\n points = cmp_df.tail(num)\n args = dict(name=name, x=points.index, y=points[column], mode=\"lines\")\n args.update(kwargs)\n return go.Scatter(**args)\n\n lower_bound = create_go(\n \"Lower Bound\",\n \"yhat_lower\",\n num_predictions,\n line=dict(width=0),\n marker=dict(color=\"gray\"),\n )\n upper_bound = create_go(\n \"Upper Bound\",\n \"yhat_upper\",\n num_predictions,\n line=dict(width=0),\n marker=dict(color=\"gray\"),\n fillcolor=\"rgba(68, 68, 68, 0.3)\",\n fill=\"tonexty\",\n )\n forecast = create_go(\n \"Forecast\", \"yhat\", num_predictions, line=dict(color=\"rgb(31, 119, 180)\")\n )\n actual = create_go(\"Actual\", \"y\", num_values, marker=dict(color=\"red\"))\n\n # In this case the order of the series is important because of the filling\n data = [lower_bound, upper_bound, forecast, actual]\n\n layout = go.Layout(yaxis=dict(title=\"Posts\"), title=title, showlegend=False)\n fig = go.Figure(data=data, layout=layout)\n iplot(fig, show_link=False)\n\n\nshow_forecast(cmp_df, prediction_size, 100, \"New posts on Medium\")\n```\n\nAt first glance, the prediction of the mean values by our model seems to be sensible. The high value of MAPE that we got above may be explained by the fact that the model failed to catch on to increasing peak-to-peak amplitude of weakly seasonality.\n\nAlso, we can conclude from the graph above that many of the actual values lie outside the confidence interval. Prophet may not be suitable for time series with unstable variance, at least when the default settings are used. We will try to fix this by applying a transform to our data.\n\n## 4. Box-Cox Transformation\n\nSo far we have used Prophet with the default settings and the original data. We will leave the parameters of the model alone. But despite this we still have some room for improvement. In this section, we will apply the [Box–Cox transformation](http://onlinestatbook.com/2/transformations/box-cox.html) to our original series. Let's see where it will lead us.\n\nA few words about this transformation. This is a monotonic data transformation that can be used to stabilize variance. We will use the one-parameter Box–Cox transformation, which is defined by the following expression:\n\n$$\n\\begin{equation}\n boxcox^{(\\lambda)}(y_{i}) = \\begin{cases}\n \\frac{\\displaystyle y_{i}^{\\lambda} - 1}{\\displaystyle \\lambda} &, \\text{if $\\lambda \\neq 0$}.\\\\\n ln(y_{i}) &, \\text{if $\\lambda = 0$}.\n \\end{cases}\n\\end{equation}\n$$\n\nWe will need to implement the inverse of this function in order to be able to restore the original data scale. It is easy to see that the inverse is defined as:\n\n$$\n\\begin{equation}\n invboxcox^{(\\lambda)}(y_{i}) = \\begin{cases}\n e^{\\left (\\frac{\\displaystyle ln(\\lambda y_{i} + 1)}{\\displaystyle \\lambda} \\right )} &, \\text{if $\\lambda \\neq 0$}.\\\\\n e^{y_{i}} &, \\text{if $\\lambda = 0$}.\n \\end{cases}\n\\end{equation}\n$$\n\nThe corresponding function in Python is implemented as follows:\n\n\n```python\ndef inverse_boxcox(y, lambda_):\n return np.exp(y) if lambda_ == 0 else np.exp(np.log(lambda_ * y + 1) / lambda_)\n```\n\nFirst, we prepare our dataset by setting its index:\n\n\n```python\ntrain_df2 = train_df.copy().set_index(\"ds\")\n```\n\nThen, we apply the function `stats.boxcox` from `Scipy`, which applies the Box–Cox transformation. In our case it will return two values. The first one is the transformed series and the second one is the found value of $\\lambda$ that is optimal in terms of the maximum log-likelihood:\n\n\n```python\ntrain_df2[\"y\"], lambda_prophet = stats.boxcox(train_df2[\"y\"])\ntrain_df2.reset_index(inplace=True)\n```\n\nWe create a new `Prophet` model and repeat the fit-predict cycle that we have already done above:\n\n\n```python\nm2 = Prophet()\nm2.fit(train_df2)\nfuture2 = m2.make_future_dataframe(periods=prediction_size)\nforecast2 = m2.predict(future2)\n```\n\nAt this point, we need to revert the Box–Cox transformation with our inverse function and the known value of $\\lambda$:\n\n\n```python\nfor column in [\"yhat\", \"yhat_lower\", \"yhat_upper\"]:\n forecast2[column] = inverse_boxcox(forecast2[column], lambda_prophet)\n```\n\nHere we will reuse our tools for making the comparison dataframe and calculating the errors:\n\n\n```python\ncmp_df2 = make_comparison_dataframe(df, forecast2)\nfor err_name, err_value in calculate_forecast_errors(cmp_df2, prediction_size).items():\n print(err_name, err_value)\n```\n\nSo, we can definitely state an increase in the quality of the model.\n\nFinally, let's plot our previous performance with the latest results side-by-side. Note that we use `prediction_size` for the third parameter in order to zoom in on the interval being predicted:\n\n\n```python\nshow_forecast(cmp_df, prediction_size, 100, \"No transformations\")\nshow_forecast(cmp_df2, prediction_size, 100, \"Box–Cox transformation\")\n```\n\nWe see that the forecast of weekly changes in the second graph is much closer to the real values now.\n\n## 5. Summary\n\nWe have taken a look at *Prophet*, an open-source forecasting library that is specifically targeted at business time series. We have also done some hands-on practice in time series prediction.\n\nAs we have seen, the Prophet library does not make wonders, and its predictions out-of-box are not [ideal](https://en.wikipedia.org/wiki/No_free_lunch_in_search_and_optimization). It is still up to the data scientist to explore the forecast results, tune model parameters and transform data when necessary.\n\nHowever, this library is user-friendly and easily customizable. The sole ability to take into account abnormal days that are known to the analyst beforehand might make a difference in some cases.\n\nAll in all, the Prophet library is worth being a part of your analytical toolbox.\n\n## 6. References\n\n- Official [Prophet repository](https://github.com/facebookincubator/prophet) on GitHub.\n- Official [Prophet documentation](https://facebookincubator.github.io/prophet/docs/quick_start.html).\n- Sean J. Taylor, Benjamin Letham [\"Forecasting at scale\"](https://facebookincubator.github.io/prophet/static/prophet_paper_20170113.pdf) — scientific paper explaining the algorithm which lays the foundation of `Prophet`.\n- [Forecasting Website Traffic Using Facebook’s Prophet Library](http://pbpython.com/prophet-overview.html) — `Prophet` overview with an example of website traffic forecasting.\n- Rob J. Hyndman, George Athanasopoulos [\"Forecasting: principles and practice\"](https://www.otexts.org/fpp) – a very good online book about time series forecasting.\n", "meta": {"hexsha": "e1a5b31addb039fe9e277d26ae0059d74de977ac", "size": 42146, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyter_english/topic09_time_series/topic9_part2_facebook_prophet.ipynb", "max_stars_repo_name": "salman394/AI-ml--course", "max_stars_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jupyter_english/topic09_time_series/topic9_part2_facebook_prophet.ipynb", "max_issues_repo_name": "salman394/AI-ml--course", "max_issues_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jupyter_english/topic09_time_series/topic9_part2_facebook_prophet.ipynb", "max_forks_repo_name": "salman394/AI-ml--course", "max_forks_repo_head_hexsha": "2ed3a1382614dd00184e5179026623714ccc9e8c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8330341113, "max_line_length": 489, "alphanum_fraction": 0.6298106582, "converted": true, "num_tokens": 6832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.34660598698258366}} {"text": "### This notebook computes the joint likelihood in 5 dimensions for the parameters of interest (see below). See inference_demo for more details about basic usage\n\n\n```python\nfrom lenslikelihood.measurements import flux_measurements, flux_measurement_uncertainties, all_lens_names, all_param_ranges_version2\nimport numpy as np\n\n# Note that the syntax for the uncertainties is\n# {'lens_name': (1-sigma-uncertainty, reference_index, uncertainty_in_ratio)}\n# where reference_index is the reference image with which to compute the flux ratio, and uncertainty_in_ratio specifies\n# whether the measurement uncertainty refers to the flux or the flux ratio\n\nfor name in all_lens_names:\n print(name)\n print('fluxes/flux ratios measured: ', flux_measurements[name])\n print('uncertainties: ', flux_measurement_uncertainties[name])\n print('\\n')\n```\n\n HE0435\n fluxes/flux ratios measured: [0.96 0.976 1. 0.65 ]\n uncertainties: ([0.05, 0.049, 0.048, 0.056], 0, False)\n \n \n WGD2038\n fluxes/flux ratios measured: [0.86 1. 0.79 0.4 ]\n uncertainties: ([0.01, 0.01724137931034483, 0.021739130434782608, 0.021739130434782608], 0, False)\n \n \n B1422\n fluxes/flux ratios measured: [0.88 1. 0.474 0.025]\n uncertainties: ([0.011363636363636364, 0.01, 0.012765957446808512, None], 0, False)\n \n \n WFI2033\n fluxes/flux ratios measured: [1. 0.65 0.5 0.53]\n uncertainties: ([0.03, 0.046875, 0.04, 0.03773584905660377], 0, False)\n \n \n PSJ1606\n fluxes/flux ratios measured: [1. 1. 0.59 0.79]\n uncertainties: ([0.03, 0.03, 0.03333333333333333, 0.02564102564102564], 0, False)\n \n \n WFI2026\n fluxes/flux ratios measured: [1. 0.75 0.31 0.28]\n uncertainties: ([0.02, 0.02666666666666667, 0.06451612903225806, 0.03571428571428571], 0, False)\n \n \n RXJ0911\n fluxes/flux ratios measured: [0.56 1. 0.53 0.24]\n uncertainties: ([0.07142857142857142, 0.05, 0.07547169811320754, 0.16666666666666669], 0, False)\n \n \n MG0414\n fluxes/flux ratios measured: [1. 0.83 0.36 0.16]\n uncertainties: ([0.06024096385542169, 0.11111111111111112, 0.11764705882352941], 0, True)\n \n \n PG1115\n fluxes/flux ratios measured: [1. 0.93 0.16 0.21]\n uncertainties: ([0.06451612903225806, 0.43750000000000006, 0.1904761904761905], 0, True)\n \n \n RXJ1131\n fluxes/flux ratios measured: [1. 0.61 0.73 0.12]\n uncertainties: ([[0.012345679012345678, 0.024691358024691357], [0.10084033613445378, 0.025210084033613446], None], 1, True)\n \n \n WGDJ0405\n fluxes/flux ratios measured: [0.8 0.52 1. 0.94]\n uncertainties: ([0.04, 0.061538461538461535, 0.024, 0.03418803418803419], 0, False)\n \n \n\n\n### Models implemented for the halo mass function and concentration-mass relation\n\nThe full set of hyper-parameters we're interested in constraining are defined by the parameterizations of the halo mass function and concentration-mass relation. They are $\\Sigma_{\\rm{sub}}$, $\\delta_{\\rm{LOS}}$, $\\Delta \\alpha$, $q$, $c_8$, and $\\beta$. The first four define to the subhalo and field halo mass functions, and the last two define the concentration-mass relation. \n\nThe field halo mass function is parameterized as\n\\begin{equation}\n\\frac{dN_{\\rm{LOS}}}{dm dV} = \\delta_{\\rm{LOS}} \\left(1+\\xi_{\\rm{2halo}}\\right) \\left(\\frac{m}{10^8}\\right)^{\\Delta \\alpha} \\ \\frac{dN_{\\rm{ShethTormen}}}{dm dV}\n\\end{equation}\nwhere $\\delta_{\\rm{LOS}}$ scales the overall normalization, and $\\Delta \\alpha$ parameterizes deviations from the logarithmic slope predicted by CDM around $10^8 M_{\\odot}$. \n\nThe subhalo mass function is parameterized as\n\\begin{equation}\n\\frac{dN_{\\rm{sub}}}{dm dA} \\sim \\Sigma_{\\rm{sub}} \\ \\left(\\frac{m}{10^8}\\right)^{\\alpha + q \\Delta \\alpha}\n\\end{equation}\nwhere $\\Sigma_{\\rm{sub}}$ is the normalization, $\\alpha$ is the logarithmic slope predicted by CDM, $\\Delta \\alpha$ parameterizes deviations from the value predicted by CDM, and $q$ controls the coupling between the line of sight halo mass function slope and the subhalo mass function slope. When $q=1$ the slopes change in the same way, and when $q=0$ the slopes of the subhalo and field halo mass functions are completely decoupled. \n\nThe concentration-mass relation is parameterized as \n\n\\begin{equation}\nc\\left(M, z\\right) = c_8 \\left(1+z\\right)^{\\zeta} \\left(\\frac{\\nu\\left(M, z\\right)}{\\nu\\left(10^8, z\\right)}\\right)^{-\\beta}\n\\end{equation}\ni.e. it is a power-law in the peak height $\\nu$ with normalization $c_8$ at $10^8$ and a logarithmic slope $\\beta$. The parameter $\\zeta$ modifies the redshift evolution and is marginalized over in the sampling. \n\nThe parameter names used in the python code have the following correspondence: \n\n\n1) sigma_sub = $\\Sigma_{\\rm{sub}}$\n\n2) delta_power_law_index = $\\Delta \\alpha$\n\n3) c0 = $c_8$\n\n4) beta = $\\beta$\n\n5) delta_power_law_index_coupling = $q$\n\n6) LOS_normalization = $\\delta_{\\rm{LOS}}$\n\n### Example inference on three parameters with a subset of lenses\n\nFirst load the model samples, define what parameters we want to look at\n\n\n```python\nimport pickle\nimport matplotlib.pyplot as plt\n# specify the parameter names\nparam_names = ['LOS_normalization', 'beta', 'log10c0', 'delta_power_law_index', 'sigma_sub']\n\nparam_ranges = [all_param_ranges_version2[name] for name in param_names]\nprint(param_ranges)\n# specify the lenses to use\nlenses = all_lens_names\nraw_samples_dict = {}\n# load the forward model samples\nfor lens in lenses:\n#for lens in ['HE0435']:\n print(lens)\n f = open('./../raw_samples/power_spectrum/'+lens+'_logprior', 'rb')\n raw_samples = pickle.load(f)\n f.close()\n raw_samples_dict[lens] = raw_samples \n print('number of samples: ', len(raw_samples.samples_dictionary['beta']))\n```\n\n [[0.0, 2.5], [-0.2, 15.0], [0, 4], [-0.6, 0.9], [0, 0.125]]\n HE0435\n number of samples: 2177080\n WGD2038\n number of samples: 1486760\n B1422\n number of samples: 1281430\n WFI2033\n number of samples: 1775092\n PSJ1606\n number of samples: 1774039\n WFI2026\n number of samples: 1383086\n RXJ0911\n number of samples: 1590968\n MG0414\n number of samples: 1724080\n PG1115\n number of samples: 2252901\n RXJ1131\n number of samples: 7832445\n WGDJ0405\n number of samples: 8922308\n\n\nThe next cell computes the joint likelihood without any importance sampling weights.\n\n\n```python\n# compute the summary statistics, retaining the 1500 sets of model parameters with lowest summary statistic\nn_samples_keep_list = [3500] * len(lenses)\n# n_samples_keep_list[-4] = 2500\n# n_samples_keep_list[-3] = 2500\n# n_samples_keep_list[0] = 2500\nsamples_dict = {}\nfig = plt.figure(1)\nfig.set_size_inches(8,8)\nfor n_samples_keep, lens in zip(n_samples_keep_list, lenses):\n#for n_samples_keep, lens in zip([3500], ['B1422']):\n print(n_samples_keep)\n print('working on lens '+str(lens) + '... ')\n measured_fluxes = flux_measurements[lens]\n measurement_uncertainties = flux_measurement_uncertainties[lens][0]\n reference_index = flux_measurement_uncertainties[lens][1]\n uncertaintiy_in_flux_ratios = flux_measurement_uncertainties[lens][2]\n \n importance_sampling_weights = None\n \n samples, full_samples, statistic = raw_samples_dict[lens].sample_with_abc(measured_fluxes, \n param_names, \n measurement_uncertainties, \n reference_index, \n n_samples_keep, \n n_draw=10,\n uncertaintiy_in_ratios=uncertaintiy_in_flux_ratios,\n importance_sampling_weights=importance_sampling_weights,\n stat_cut=0.1)\n plt.hist(statistic, alpha=0.5, label=lens, density=True)\n samples_dict[lens] = samples\n\n# the histogram shows the distribution of the retained summary statistics\nplt.legend(fontsize=12)\nplt.xlim(0., 0.06)\nplt.xlabel('summary statistic', fontsize=14)\nplt.show()\n```\n\nNow we compute the likelihood using the package trikde https://github.com/dangilman/trikde\n\n\n```python\nfrom trikde.pdfs import DensitySamples, IndepdendentLikelihoods\nimport os\n\nnbins = 20\nlikelihoods = []\n\nload_from_pickle = False # if True, will look for a pre-computed DensitySamples class\nsave_to_pickle = True # if True, will pickle each class for accelerated later use; \n# save_to_pickle=True will do nothing if load_from_pickle=True\n\nfilename_extension = '_joint_logprior'\nbase_path = './../lenslikelihood/precomputed_likelihoods/'\n\n#for lens in ['B1422']:\nfor lens in all_lens_names:\n #if lens =='B1422': continue\n \n fname = base_path + lens + filename_extension\n if load_from_pickle and os.path.exists(fname):\n print('loading joint likelihoods for lens '+lens+' ...')\n f = open(fname, 'rb')\n single_lens_likelihood = pickle.load(f)\n f.close()\n else:\n print('computing joint likelihoods for lens '+lens+' ...')\n lens_samples = samples_dict[lens]\n weights=None\n single_lens_likelihood = DensitySamples(lens_samples, param_names, weights, \n param_ranges, nbins=nbins, use_kde=True, bandwidth_scale=0.9)\n if save_to_pickle:\n f = open(fname, 'wb')\n pickle.dump(single_lens_likelihood, f)\n f.close()\n likelihoods.append(single_lens_likelihood)\n \nlikelihood = IndepdendentLikelihoods(likelihoods)\n```\n\n computing joint likelihoods for lens HE0435 ...\n computing joint likelihoods for lens WGD2038 ...\n computing joint likelihoods for lens B1422 ...\n computing joint likelihoods for lens WFI2033 ...\n computing joint likelihoods for lens PSJ1606 ...\n computing joint likelihoods for lens WFI2026 ...\n computing joint likelihoods for lens RXJ0911 ...\n computing joint likelihoods for lens MG0414 ...\n computing joint likelihoods for lens PG1115 ...\n computing joint likelihoods for lens RXJ1131 ...\n computing joint likelihoods for lens WGDJ0405 ...\n\n\n### The joint likelihood/posterior with no modeling assumptions (indepedent, uniform priors on all model parameters). \n\n\n```python\nfrom trikde.triangleplot import TrianglePlot\nprint(param_ranges)\ntriangle_plot = TrianglePlot([likelihood])\ntriangle_plot.set_cmap('magma')\naxes = triangle_plot.make_triplot(filled_contours=False, show_intervals=False, show_contours=False\n )\n# can change axis labels\n```\n\n\n```python\nfrom trikde.pdfs import CustomPriorHyperCube\nfrom trikde.kde import KDE \n \ndef couple_mass_functions(samples, sigma_sub_theory=0.05, coupling_strength=0.2, edge_coupling=0.2):\n \n delta_los_samples = samples[:, 0]\n sigma_sub_samples = samples[:, -1]\n delta_sigma_sub = sigma_sub_samples/sigma_sub_theory\n \n edge_dlos = 2.5/10\n edge_sigma_sub = 0.1/10\n \n cond1 = delta_los_samples < edge_dlos\n cond2 = sigma_sub_samples < edge_sigma_sub\n inds_1 = np.logical_and(cond1, cond2)\n cond1 = delta_los_samples > 2.5 - edge_dlos\n cond2 = sigma_sub_samples > 0.1 - edge_sigma_sub\n inds_2 = np.logical_and(cond1, cond2)\n \n chi2 = (delta_sigma_sub - delta_los_samples)**2/coupling_strength**2 \n chi2[inds_1] *= coupling_strength ** 2 / edge_coupling ** 2\n chi2[inds_2] *= coupling_strength ** 2 / edge_coupling ** 2\n \n return chi2\n\nkwargs_1 = {'sigma_sub_theory': 0.05}\nprior_on_mass_functions_1 = CustomPriorHyperCube(couple_mass_functions, param_names, param_ranges, \n nbins, kwargs_1)\nlikelihoods_coupled_with_prior_mass_functions = likelihoods + [prior_on_mass_functions_1]\nlikelihood_coupled_with_prior_mass_functions_1 = IndepdendentLikelihoods(likelihoods_coupled_with_prior_mass_functions)\n\nkwargs_2 = {'sigma_sub_theory': 0.025}\nprior_on_mass_functions_2 = CustomPriorHyperCube(couple_mass_functions, param_names, param_ranges, nbins, kwargs_2)\nlikelihoods_coupled_with_prior_mass_functions = likelihoods + [prior_on_mass_functions_2]\nlikelihood_coupled_with_prior_mass_functions_2 = IndepdendentLikelihoods(likelihoods_coupled_with_prior_mass_functions)\n```\n\n\n```python\ntriangle_plot = TrianglePlot([likelihood_coupled_with_prior_mass_functions_1])\ntriangle_plot.set_cmap('jet')\naxes = triangle_plot.make_triplot(filled_contours=False, show_intervals=False, show_contours=False\n )\n```\n\n\n```python\ntriangle_plot = TrianglePlot([likelihood_coupled_with_prior_mass_functions_2])\ntriangle_plot.set_cmap('jet')\naxes = triangle_plot.make_triplot(filled_contours=False, show_intervals=False, show_contours=False\n )\n```\n\n\n```python\nedge_effect_likelihood = IndepdendentLikelihoods([DensitySamples()])\ntriangle_plot = TrianglePlot([edge_effect_likelihood])\ntriangle_plot.set_cmap('magma')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "21a4d0a599115ae6b68eabb71371ff38e197d797", "size": 234009, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/inference_5D_from_scratch_logprior.ipynb", "max_stars_repo_name": "dangilman/lenslikelihood", "max_stars_repo_head_hexsha": "1490ee9756b4d2ed108a2478977609bbe0ba2e17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/inference_5D_from_scratch_logprior.ipynb", "max_issues_repo_name": "dangilman/lenslikelihood", "max_issues_repo_head_hexsha": "1490ee9756b4d2ed108a2478977609bbe0ba2e17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/inference_5D_from_scratch_logprior.ipynb", "max_forks_repo_name": "dangilman/lenslikelihood", "max_forks_repo_head_hexsha": "1490ee9756b4d2ed108a2478977609bbe0ba2e17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 417.128342246, "max_line_length": 63188, "alphanum_fraction": 0.9313317009, "converted": true, "num_tokens": 3631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3464639026463391}} {"text": "# Use Python in Advanced Statistics\n\n*這個學期剛剛學完了概率論與數理統計,這好趁這個機會複習一下並複習一下 `python`*\n
\n\n\n\n\n## Chapter One Probability \n\n### 隨機試驗與樣本空間(Random Experiment and Sample Space)\n\n#### 隨機試驗\n隨機試驗是概率論中一個基本的概念。概括的講,在概率論中把符合下面三個特點的試驗叫做隨機試驗:\n* 可以在向空的條件下重複進行;\n* 每次試驗的可能結果不只一個,並且事先明確試驗的所有可能結果;\n* 進行一次試驗之前不能確定哪一個結果會出現。\n\n隨機試驗有很多種,例如常出現的擲骰子,摸球,射擊等。所有的隨機試驗的結果可以分為兩類來表示:
\n* 數量化表示:射擊命中的次數,商場每個小時的客流量,每天經過某個收費站的車輛等,這個結果本事就是數字;\n* 非數量化表示:拋硬幣的結果(正面/反面),化驗的結果(陽性/陰性)等,這些結果是定型的,非數量化的。但是可以用示性函數來表示,例如可以規定正面(陽性)為$1$,反面為$0$,這樣就可以實現了非數量化結果的數量化。\n\n#### 樣本空間(Sample Space):\n\n* 隨機試驗的所有可能結果構成的集合。一般即為$S$(capital S);\n* $S$ 中的元素$e$稱為樣本點(也可以叫基本事件);\n* 事件是樣本空間的子集,同樣是一個集合。\n\n#### 事件的關係\n* 事件的包含:$A \\subseteq B$;\n* 事件的相等:$A = B$;\n* 互斥事件(互不相容事件):不能同時出現;\n* 事件的和(並):$A cup B$\n* 事件的差: $A - B$,$A$發生,$B$不發生;\n* 對立事件(逆事件):互斥,必須出現其中一個。\n\n
\n事件的運算性質就是集合的性質\n\n### 頻率和概率\n\n#### 頻率:\n\n頻率是指$0~1$之間的一個實數,在大量重複試驗的基礎上給出了隨機事件發生可能性的估計。
\n概率的穩定性:在充分多次試驗中,事件的頻率總在一個定值附近擺動,而且,試驗次數越多擺動越小。這個性質叫做頻率的穩定性。\n\n#### 概率:\n\n概率的統計性定義:當試驗次數增加時,隨機時間$A$發生的頻率的穩定值為$p$就稱為概率。記為$P(A) = P$
\n概率的公理化定義:設隨機試驗對於的樣本空間為$S$。對每一個事件$A$,定義為$P(A)$,滿足:
\n1. 非負性:$P(A) \\geq 0$;\n2. 規範性:$P(S) = 1;\n3. 可列可加性:$A_1, A_2, \\dots 兩兩互斥,及$A_iA_j = \\oslash, i \\neq j$則 $P(\\cup A_i) = \\sum P(A_i)$ \n\n#### 條件概率(Conditional Probability):\n$P(A|B)$表示在事件$B$發生的條件下,事件$A$發生的概率,相當於$A$在$B$所佔的比例。此時,樣本空間從原來的完整樣本空間$S$縮小到了$B$,由於有了條件的約束(事件$B$),使得原本的樣本空間減少了。\n\n下面我們可以通過韋恩圖做示例:
\nplot one:條件概率的樣本空間;
\nplot two:條件概率應如何計算\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport sympy\n\n\nfrom matplotlib_venn import venn3, venn3_circles\nplt.figure(figsize=(4,4))\nv = venn2(subsets=(2,2,1), set_labels = ('A', 'B'))\n\n\n\nplt.title(\"Sample Venn diagram - plot one\")\nplt.annotate('P(AB)', xy=v.get_label_by_id('11').get_position() - np.array([0, 0.05]), xytext=(-70,-70),\n ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1),\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color='gray'))\nplt.show()\n\n```\n\n\n```python\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport sympy\n\n\nfrom matplotlib_venn import venn3, venn3_circles\nplt.figure(figsize=(4,4))\nv = venn2(subsets=(2,2,1), set_labels = ('A', 'B'))\n\nc = venn2_circles(subsets=(2, 2, 1), linestyle='dashed')\nc[0].set_lw(1.0)\nc[0].set_ls('dotted')\nplt.title(\"Sample Venn diagram\")\nplt.annotate('P(AB)', xy=v.get_label_by_id('11').get_position() - np.array([0, 0.05]), xytext=(-70,-70),\n ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1),\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color='gray'))\nplt.show()\n```\n\n$P(B|A) = \\frac{P(AB)}{P(A)}$
\n$P(A|B) = \\frac{P(AB)}{P(B)}$
\n\n例題:一個家庭中有兩個小孩,已知至少一個是女孩,問兩個都是女孩的概率是多少?(假設生男生女是等可能的)
\n**解**:由題意可得:樣本空間為\n \n S = {(兄,弟), (兄,妹),(姐,弟),(姐,妹)}
\n B = {(兄,妹), (姐,弟),(姐,妹)}
\n A = {(姐,妹)}
\n \n由於,事件 $B$ 已經發生了,所以這時試驗的所有可能只有三種,而事件 $A$ 包含的基本事件只占其中的一種,所以有:$P(A|B) = \\frac{1}{3}$
\n即,在已知至少一個是女孩的請卡滾下,兩個都是女孩的概率為$\\frac{1}{3}$。在這個例子中,如果不知道事件 $B$ 發生,則事件 $A$ 發生的概率為 $P(A) = \\frac{1}{4}$ 這裡的 $P(A) \\neq P(A|B)$,其中的原因在於事件 $B$ 的發生改變了樣本空間,使它由原來的 $S$ 縮減為新的樣本空間 $S_B = B$ \n\n### 全概率公式和 Bayes 公式\n\n了解完了條件概率,那我了解一下什麼是**聯合概率(Joint Probability)**和**邊緣概率(Marginal Probability)**
\n**聯合概率**表示兩者同時發生的概率,表示為$P(A\\cap B)$或者$P(A,B)$或者$P(AB)$
\n**邊緣概率**表示某單一事件發生的概率。边缘概率是這樣得到的:在聯合概率中,把最終結果中不需要的那些事件合并成其事件的全概率而消失(對离散隨机變量用求和得全概率,對連續隨机變量用積分得全概率)。這稱為邊緣化(marginalization)。A的边缘概率表示为$P(A)$,B的边缘概率表示为$P(B)$\n\n\n#### 全概率公式(Law of Total Probability)\n\n設$B_1,B_2,\\dots B_n$ 是樣本空間$\\Omega$中的兩兩不相容的一組事件,即,$B_i B_j = \\emptyset, \\ i \\neq j$,且 滿足$U^n_{i = 1} = B_i = \\Omega$,則稱$B_1,B_2,\\dots B_n$是樣本空間$\\Omega$的一個分割。\n
\n**全概率公式:**設$\\{B_1,B_2,\\dots B_n\\}$是樣本空間$\\Omega$的一個分割,且$P(B_i)>0(i = 1,\\dots,n)$,$A$為$\\Omega$中的一個事件,則:\n
\n
\n $P(A) = \\displaystyle \\sum^n_{i=1}P(A|B_i)P(B_i)$\n
\n
\n\n#### Bayes 公式\n設$\\{B_1,B_2,\\dots B_n\\}$是樣本空間的一個分割,$A$為$\\Omega$中的一個事件,$P(B-i)>0,i =1,2,\\dots,n,P(A)>0$,則:\n
\n
\n $P(B_i|A) = \\frac{P(A|B_i)P(B_i)}{\\sum^b_{i=1}P(A|B_j)P(B_j)}$\n
\n
\n\n什麼時候我們會使用 Bayes 公式呢? 由公式可得,分母就是事件$A$的概率,而份子和等式左邊的條件概率中的條件正好反過來,所以我們知道在因果關係互換時,必須使用 Bayes 公式。\n\n\n#### 隨機變量(Random Variable)\n\n在幾乎所有教材裡,介紹概率論都是從事件和樣本空間說起的,但是後面的概率論都是圍繞著隨機變量展開的。可以說前面的事件和樣本空間都是引子,引出了隨機變量這個概率論的核心概念。後面的統計學是建立在概率論的理論基礎之上的,因此可以說理解隨機變量這個概念是學習和運用概率論與數理統計的關鍵。
\n**隨機變量**:
\n\n* 首先這是一個變量,變量與常數相對,也就是說其取值是不明確的,其實隨機變量的整個取值範圍就是前面說的樣本空間;\n* 其次這個量是隨機的,也就是說它的去職代有不確定性,讓然是在樣本空間這個範圍內的。\n\n\n**定義:**\n> 設隨機試驗的樣本空間是 $S$ ,若對 $S$ 中的每一個樣本點 $e$ ,都有唯一的實數值 $X(e)$ 為隨機變量,間記為 $X$\n\n隨機變量的定義並不複雜,但是理解起來去不是這麼直觀。\n\n* 首先,隨即變量與之前定義的事件是有關係的,因為每個樣本點本身就是一個基本事件;\n* 在前面隨機試驗結果的表示中提到,無論是數量化的結果還是非數量化的結果,即不管試驗結果是否與數值有關,都可以引入變量,使試驗結果與數建立對應關係;\n* 隨機變量本質上是一種函數,其目的就是建立試驗結果(樣本中的點,同基本事件$e$)與實數之間的對應關係(例如將“正面”影射為$1$,“反面”影射為$0$);\n* 自變量為基本事件$e$,定義域為樣本空間$S$,值域為某個實數集合,多個自變量可以對應同一個函數值,但不允許一個自變量對應多個函數值;\n* 隨機變量$X$取某個值或某些值就表示某種事件,且具有一定的概率;\n* 隨機變量中的隨機來源於隨機試驗結果的不確定性。\n\n我們可以通過引入隨機變量,我們簡化了隨機試驗結果(事件)的表示,從而可以更加方便的對隨機試驗進行研究。\n\n**隨機變量的分類**:
\n* 離散隨機變量;\n* 連續隨機變量;\n* 每類隨機變量都有其獨特的概率密度函數和概率分佈函數。\n\n**隨機變量的數字特徵**:
\n* 期望(均值),眾數,分位數,中位數;\n* 方差;\n* 協方差;\n* 相關係數。\n\n\n### 隨機變量(Random Variable)\n\n*對隨機變量以及其取值規律的研究是概率的核心內容。在上一個小結中,總結了隨機變量的概念以及隨機變量與事件的聯繫。這個小結會更加深入的討論隨機變量。*\n\n#### 隨機變量與事件\n\n隨機變量的本質是一種函數(映射關係),在古典概率模型中,“事件和事件的概率”是核心概念;但是在現代概率論中,“隨機變量及其取值規律”是核心概念。\n
\n**隨機變量與事件的聯繫與區別**\n
\n小結 1 中對著練歌概念的聯繫進行了非常詳細的描述。隨機變量實際上只是事件的另一種表達方式,這種表達方式更加的形式化和符號化,也更佳便於理解以及進行邏輯運算。不同的事件,其實就是隨機變量不同取值的組合。在陈希孺先生的書中,有一個很好的例子來說明這兩者的區別:
\n> 對於隨機試驗,我們所關心的往往是與所研究的特定問題有關的某個或某些變量,而這些量就是隨機變量。當然,有事我們所關心的是某個或某些特定的隨機時間。例如,在特定一群人中,年收入在萬元以上的高收入者,以及年收入在$3000$元以下的低收入者,各自比率如何?者看上去是兩個孤立的事件。可是當我們引入一個隨機變量$X$: \n> \n>
\n>
$X = $ 隨機抽出一個人其年收入
\n>
\n> \n>則$X$是我們關心的隨機變量。上述兩個事件可以分表表示為$\\{X > 10000\\}$或$\\{X < 3000\\}$。這就看出:**隨機事件**這個概念實際上包容在**隨機變量**這個更廣的概念之中。也就是說,隨機事件是靜態的觀點來研究隨機現象,而隨機變量則是一種動態的觀點。「概率論能從計算一些孤立事件的概率發展成為一個更高的理論體系,其根本概念就是隨機變量\n\n*這段話,非常清楚的解釋了隨機變量與事件的區別:就跟變量和常量之間的區別那樣*\n\n#### 隨機變量的分類(The Classification of the Random Variable)\n\n**隨機變量從其可能的取值的性質分為兩大類:離散型隨機變量(Discrete Random Variable)和連續性隨機變量(Continuous Random Variable)**
\n##### 離散型隨機變量(Discrete Random Variable)\n\n離散型隨機變量的取值在整個實數軸上是有間隔的,要麼只有有限個取值,要麼就是無限可數。
\n如下圖:\n\n\n```python\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\ndef poisson_pmf(mu=3):\n \n poisson_dis = stats.poisson(mu)\n x = np.arange(poisson_dis.ppf(0.001), poisson_dis.ppf(0.999))\n print(x)\n \n fig, ax = plt.subplots(1, 1)\n ax.plot(x, poisson_dis.pmf(x), 'bo', ms=8, label='poisson pmf')\n ax.vlines(x, 0, poisson_dis.pmf(x), colors='b', lw=5, alpha=0.5)\n ax.legend(loc='best', frameon=False)\n plt.ylabel('Probability')\n plt.title('PMF of poisson distribution(mu={}) - plot three'.format(mu))\n plt.show()\n \npoisson_pmf(mu=8)\n```\n\n\n```python\ndef binom_pmf(n=1, p=0.1):\n binom_dis = stats.binom(n, p)\n x = np.arange(binom_dis.ppf(0.0001), binom_dis.ppf(0.9999))\n print(x) \n \n fig, ax = plt.subplots(1, 1)\n ax.plot(x, binom_dis.pmf(x), 'bo', label='binom pmf')\n ax.vlines(x, 0, binom_dis.pmf(x), colors='b', lw=5, alpha=0.5)\n ax.legend(loc='best', frameon=False)\n plt.ylabel('Probability')\n plt.title('PMF of binomial distribution(n={}, p={}) - plot four'.format(n, p))\n \n plt.show()\n \n\nbinom_pmf(n=20, p=0.6)\n```\n\n* Plot three 是 Poisson Distribution\n* Plot four 是 Binomal Distribution\n\n常見的**離散型隨機變量**包括以下這幾種:
\n\n* 0-1分佈(Bernoulli Distribution)\n* 二項分布(Binomial Distribution)\n* 幾何分佈(Geometric Distribution)\n* 泊松分佈(Poisson Distribution)\n* 超幾何分佈(Hyper-geometric Distribution)\n\n\n\n##### 連續型隨機變量(Continuous Random Variable)\n\n連續型隨機變量的取值要麼包括了整個實數集$(-\\infty, \\infty)$,要麼在一個區間內連續,總之,這一類的隨機變量的可能取值要比離散型隨機變量的取值多得多,個數是無窮不可數的。
\n\n**常見的連續型隨機變量包括以下幾種**:
\n\n* 均勻分布\n* 指數分佈\n* 正態分佈($\\gamma$分佈, $\\beta$分佈,$\\chi^2$分佈等)\n\n##### 概率密度函數的性質\n\n所有的概率密度函數$f(x)$都滿足一下的兩條性質;所有滿足下面兩條性質的一元函數也都可以作為概率密度函數。
\n$f(x) \\geq 0$,以及$\\int_{-\\infty}^{+\\infty}f(x)dx = 1$.\n\n#### 隨機變量的基本性質\n\n隨機變量最主要的性質是其所有可能取到的這些值的取值規律,即取到的概率大小。如果我們把一個隨機變量的所有可能的取值的規律都研究透徹了,那麼這個隨機變量也就研究透徹了。隨機案變量的性質只要有兩類:一類是大而全的性質,這類性質可以詳細描述所有可能取值的概率,律如**累積分佈函數(Cumulative Distribution Funtion)**和**概率密度函數(Probability Density Function)**;另一類是找到該隨機變量的一些特徵或者代表值,例如隨機變量的方差或者期望等數字特徵。常見的隨機變量的性質如下表:\n\n\n| name | 解釋 |\n| :---: | :---: |\n| CDF: Cumulative Distribution Function | 連續型和離散型隨機變量都有,一般以$F(X)$表示 |\n| PDF: Probability Density Function | 連續型隨機變量在各點的取值規律,用$f(x)$表示 |\n| PDF: Probability Density Function | 連續型隨機變量在各點的取值規律,用$f(x)$表示 |\n| PMF: Probability Mass Function | 離散型型隨機變量在各特定取值上的概率 |\n| RVS: Random Variate Sample | 從一個給定分佈取樣 |\n| PPF: Percentile Point Function | CDF 的反函數 |\n| IQR: Inter Quartile Range | $25%$分位數與$75%$ 分位數之差 |\n\n*PDF 只有**連續型隨機變量**才有, PMF 只有**離散型隨機變量**才有;一個分佈的 CDF 求導等於 PDF, 一個分佈的 PDF 積分後就是 CDF*\n\n### 一維離散型隨機變量及其 Python 實現\n\n上一小節,對隨機變量做了一個概述,這一節主要紀錄以為離散變量以及關於他們的一些性質。對於概率論與數理統計方面的計算以及可視化,主要的`pyhton`包有`scipy`,`numpy`和`matplotlib`等。
\n\n\n```python\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n```\n\n`scipy` 是 `python` 中使用最為廣泛的科學計算工具包,在加上`numpy`和`matplotlib`,基本可以處理大多數的計算和作圖任務。下面是`wikipedia`對`scipy`的介紹:
\n\n> SciPy是一个开源的Python算法库和数学工具包。SciPy包含的模块有最优化、线性代数、积分、插值、特殊函数、快速傅里叶变换、信号处理和图像处理、常微分方程求解和其他科学与工程中常用的计算。与其功能相类似的软件还有MATLAB、GNU Octave和Scilab。SciPy目前在BSD许可证下发布。它的开发由Enthought资助。\n\n我們使用的是 `scipy`中的 `stats`模塊,這個模塊包歡樂概率論以及統計相關的函數。\n相關函數可以查詢: scipy stats\n\n#### 伯努利分佈(Bernoulli Distribution)\n\n又名兩點分佈或者$0-1$分佈,是一個離散型概率分佈。若伯努利試驗成功,則伯努利隨機變量取值為$1$,如果失敗則取值為$0$。記其成功概率為$p(0\\leq p \\leq 1)$,失敗概率為:$q = 1-p$。其概率質量函數(PMF) 為:
\n
\n $\\begin{equation} \\nonumber P_X(x) = \\left\\{ \\begin{array}{l l} p& \\quad \\text{for } x=1\\\\ 1-p & \\quad \\text{ for } x=0\\\\ 0 & \\quad \\text{ otherwise } \\end{array} \\right. \\end{equation}$\n
\n\n\n```python\nfrom scipy.stats import bernoulli\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig, ax = plt.subplots(1, 1)\n\np = 0.8\nx = np.linspace(0,1)\n\nplt.plot(x,bernoulli.pmf(x,p),'o-',label='bernoulli pmf')\n\nplt.title('bernoulli pmf')\nplt.xlim(-0.1,1.1)\nplt.ylim(0,1)\n\nplt.show()\n```\n\n伯努利分佈只有一個參數$p$,記做$X ~ Bernuolli(p)$,或$X ~ B(1,p)$,讀做$X$服從參數為$p$的伯努利分佈。伯努利分佈適合於試驗結果只有兩種可能的單次試驗。例如拋一次硬幣,其結果只有正面或者反面兩種可能;一次產品質量檢測,結果只有合格還是不合格這兩種可能。
\n\n\n\n```python\nimport scipy.stats as stats\nfrom scipy.stats import bernoulli\nimport matplotlib.pyplot as plt\n\ndef bernoulli_pmf(p=0.0):\n\n ber_dist = stats.bernoulli(p)\n x = [0, 1]\n x_name = ['0', '1']\n pmf = [ber_dist.pmf(x[0]), ber_dist.pmf(x[1])]\n plt.bar(x, pmf, width=0.15)\n plt.xticks(x, x_name)\n plt.ylabel('Probability')\n plt.title('PMF of bernoulli distribution')\n plt.show()\n\nbernoulli_pmf(p=0.8)\n```\n\n上面兩幅圖都是表示伯努利分佈的 PMF;我們為了得到比較準確的某個服從伯努利分佈的隨機變量的期望,需要大量重複伯努利試驗,例如重複$n$次,然後利用$\\frac{正面朝上的次數}{n}$來估計$p$值,當我們重複$n$次以後,這就變成了二項分布,就是下面會提到的**二項分布**。\n\n#### 二项分布(Binomial Distribution)\n\n二項分布是指$n$個獨立的是/非試驗中成功的次數的離散概率分佈,其中每次試驗的成功概率為$p$。這樣的單詞成功/失敗試驗又稱為伯努利試驗。實際上,當$n = 1$時,二項分布就是伯努利分佈。二項分布時顯著性差異的二項試驗的基礎。\n\n\n```python\nimport scipy.stats as stats\ndef binom_pmf(n=1, p=0.1):\n\n binom_dis = stats.binom(n, p) \n x = np.arange(binom_dis.ppf(0.0001), binom_dis.ppf(0.9999))\n #print(x) # [ 0. 1. 2. 3. 4.]\n fig, ax = plt.subplots(1, 1)\n ax.plot(x, binom_dis.pmf(x), 'bo',label='binom pmf')\n ax.vlines(x, 0, binom_dis.pmf(x), colors='b', lw=5, alpha=0.5)\n ax.legend(loc='best', frameon=False)\n plt.ylabel('Probability')\n plt.title('PMF of binomial distribution(n={}, p={})'.format(n, p))\n plt.show()\n\nbinom_pmf(n=20, p=0.6)\n```\n\n##### 二項分布和其他分佈的關係\n\n1. 二項分布的和
\n 如果$X~B(n,p)$ 和$Y~B(n,p)$,且$X$和$Y$相互獨立,那麼$X + Y$ 也服從二項分佈:\n $X + Y~B(n+m, p)$\n \n2. 伯努利分佈
\n 二項分布就是$n$重伯努利試驗\n \n3. 泊松分佈
\n 泊松分佈實際上可以通過二項分布推導出來,當$n$很大,$p$很小的時候,我們可以通過極限\n 去證明(證明見下方)\n \n
我們首先先畫圖來看,當$n = 100,p = 0.1$時\n\n\n```python\nbinom_pmf(n=1000000,p=0.00001)\n```\n\n\n```python\n# poisson_distribution_PMF\ndef poisson_pmf(mu=1):\n \n poisson_dis = stats.poisson(mu)\n x = np.arange(poisson_dis.ppf(0.001), poisson_dis.ppf(0.999))\n #print(x)\n fig, ax = plt.subplots(1, 1)\n ax.plot(x, poisson_dis.pmf(x), 'bo', ms=8, label='poisson pmf')\n ax.vlines(x, 0, poisson_dis.pmf(x), colors='b', lw=5, alpha=0.5)\n ax.legend(loc='best', frameon=False)\n plt.ylabel('Probability')\n plt.title('PMF of poisson distribution(mu={})'.format(mu))\n plt.show()\n\npoisson_pmf(mu=10)\n```\n\n由圖可得:兩者近似相等;下面是數學證明:\n\nLet $X$ be as described,\nLet $ k \\geq 0$ be fixed, we write $p = \\frac{\\lambda}{n}$ and suppose \nthat $n$ is large.
\nThen:
\n\n
\n $\\begin{align*}\n Pr(X = k) &= \\binom n k p^k \\left({1 - p}\\right)^{n-k} \\\\& \\simeq \\frac {n^k} {k!} \\left({\\frac \\lambda n}\\right)^k \\left({1 - \\frac \\lambda n}\\right)^n \\left({1 - \\frac \\lambda n}\\right)^{-k} \\\\ &= \\frac 1 {k!} \\lambda^k \\left({1 + \\frac {-\\lambda} n}\\right)^n \\left({1 - \\frac \\lambda n}\\right)^{-k} \\\\ &= \\frac 1 {k!} \\lambda^k \\left({1 + \\frac {-\\lambda} n}\\right)^n \\\\ &\\simeq \\frac{1}{k}\\lambda^k e^{-\\lambda} \\end{align*}$\n
\n \n\nwhen $n \\gg k$ it's a reasonable approximation for $\\binom n k $, as $ 1-p = (1 - \\frac{\\lambda}{n})$ is very close to $1$. Hence the result.\n
\n
\n**Comment:**\nOkay wise guy, exactly what constitutes \"very large\", \"very small\", and \"of a reasonable size\"?\nWell, if $n = 10^6$ and $p = 10^{-5}$, we have np = 10 = \\lambda$\nThat's the sort of order of magnitude we're talking about here.\n \n\n#### 泊松分佈(Poisson Distribution)\n\n泊松分佈有一個參數$\\lambda$(或$\\mu$),表示單位事件內隨機事件的平均發生次數,其 PMF 表示為:
\n\n
\n $\\begin{equation}\\nonumber P_X(k) = \\left\\{\\begin{array}{l l}\\frac{e^{-\\lambda} \\lambda^k}{k!}& \\quad \\text{for } k \\in R_X\\\\ 0 & \\quad \\text{ otherwise} \\end{array} \\right. \\end{equation}$\n
\n
\n\n以上表示單位時間上的泊松分佈,即$t = 1$,如果表示時間$t$上的泊松分佈,則需要將$\\lambda$乘以$t$ $\\Rightarrow\\lambda t$\n
\n\n一個隨機變量$X$服從參數為$\\lambda$的柏松分佈,記做$X~Poisson(\\lambda)$,或$X~P(\\lambda)$。\n\n泊松分佈適合於描述單位時間內隨機時間發生的次數的概率分佈。如,某一服務設施在一定時間內收到的服務請求的次數,電話交換機接到胡椒的次數,機器出現的故障數,DNA序列的變異數等等。\n\n### 一維連續型隨機變量及其 Python 實現\n\n上一小節總結了幾種離散型隨機變量,這個小節總結連續型隨機變量。離散型隨機變量的可能取值為有限多個或者無限可數,而連續型隨機變量的可能取值則為一段連續的區域或者整個實數軸,是不可數的。最常見的連續型隨機變量有三種:均勻分布、指數分佈和正太分佈。\n\n#### 均勻分佈(Uniform Distribution)\n\n如果連續型隨機變量$X$具有如下的概率目睹函數,則稱$X$服從$[a,b]$上的菊允分佈,記做$X~U[a,b]$
\n
\n $\\begin{equation} \\nonumber f_X(x) = \\left\\{ \\begin{array}{l l} \\frac{1}{b-a} & \\quad a < x < b\\\\ 0 & \\quad x < a \\textrm{ or } x > b \\end{array} \\right. \\end{equation}$\n
\n
\n\n均勻分佈具有等可能性,也就是說服從$U(a,b)$上的均勻分佈的隨機變量$X$落入$(a,b)$中國年的任意子區間的概率只與其取件長度有關,與取件所處的位置無關。
\n\n由於是均勻分佈的概率函數是一個常數,因此,其累積分佈函數是一條直線,隨著其取值在定義域內增加,累積分佈函數值均勻增加。\n
\n\n
\n $\\begin{equation} \t\t\t\t\t\t \\hspace{70pt} F_X(x) = \\left\\{ \\begin{array}{l l} 0 & \\quad \\textrm{for } x < a \\\\ \\frac{x-a}{b-a} & \\quad \\textrm{for }a \\leq x \\leq b\\\\ 1 & \\quad \\textrm{for } x > b \\end{array} \\right. \t\t\t\t\t\t \\hspace{70pt} \\end{equation}$\n
\n
\n\n\n\n\n```python\nfrom scipy.stats import uniform\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 1)\n\nx = np.linspace(-2, 2)\nax.plot(x, uniform.cdf(x),'r-', lw=5, alpha=0.6)\nplt.title(\"CDF of uniform distribution\")\n\nplt.show()\n```\n\n均勻分佈主要可以用在:\n* 設通過某站的汽車10分鐘一輛,則乘客候車時間$X$,在$[0,10]$上服從均勻分佈;\n* 某電台每20分鐘發一個信號,我們隨手打開收音機,等待的時間$X$在$[0,20]$上服從均勻分佈 \n\n\n```python\ndef uniform_distribution(loc=0, scale=1):\n \"\"\"\n 均匀分布,在实际的定义中有两个参数,分布定义域区间的起点和终点[a, b]\n :param loc: 该分布的起点, 相当于a\n :param scale: 区间长度, 相当于 b-a\n :return:\n \"\"\"\n uniform_dis = stats.uniform(loc=loc, scale=scale)\n x = np.linspace(uniform_dis.ppf(0.01),\n uniform_dis.ppf(0.99), 100)\n fig, ax = plt.subplots(1, 1)\n\n # 直接传入参数\n ax.plot(x, stats.uniform.pdf(x, loc=2, scale=4), 'r-',\n lw=5, alpha=0.6, label='uniform pdf')\n\n # 从冻结的均匀分布取值\n ax.plot(x, uniform_dis.pdf(x), 'k-',\n lw=2, label='frozen pdf')\n\n # 计算ppf分别等于0.001, 0.5, 0.999时的x值\n vals = uniform_dis.ppf([0.001, 0.5, 0.999])\n print(vals) # [ 2.004 4. 5.996]\n\n # Check accuracy of cdf and ppf\n print(np.allclose([0.001, 0.5, 0.999], uniform_dis.cdf(vals))) # Ture\n\n r = uniform_dis.rvs(size=10000)\n ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2)\n plt.ylabel('Probability')\n plt.title(r'PDF of Unif({}, {})'.format(loc, loc+scale))\n ax.legend(loc='best', frameon=False)\n plt.show()\n\nuniform_distribution(loc=2, scale=4)\n```\n\n從定義式中可以看出,定義一個均勻分佈需要兩個參數:定義域的起點$a$和終點$b$,但是在`Python`中是`localtion`是`scale`,分別表示起點和區間長度: scripy.stats.uniform
\n\n上面的代碼採用了兩種方式$\\Rightarrow$直接傳入參數和先凍結了一個分佈,然後畫出均勻分佈的概率分佈函數。此外還從該分佈中選取了10000個值做直方圖。\n\n上圖是一個均勻分佈:$U(2,6)$的概率密度函數曲線\n\n#### 指數分佈(Exponentinal Distribution)\n\n在概率論和統計學中,指數分佈(Exponential Distribution)是一種連續型的概率分佈。可以用來表示獨立隨機時間發生的時間間隔,比如旅客進入機場的時間間隔,打進客服中心電話的時間間隔、中文維基百科新條目出現的時間等等。其實,指數分佈和離散型的泊松分佈有很大關係。泊松分佈表示的是單位時間(或單位面積)內隨機時間的平均發生次數,指數分佈則可以用來表示獨立隨機事件發生的時間間隔。由於發生次數之能事自然數,所以泊松分佈很自然就是離散型的隨機變量;而時間間隔則可以是任意的實數,因此其定義域為:$(0, +\\infty)$\n\n如果一個隨機變量$X$的概率密度函數滿足以下形式,就稱$X$為服從參數$\\lambda$的指數分佈(Exponential\nDistribution),記做$X~E(\\lambda)$或$X~Exp(\\lambda)$
\n\n指數函數只有一個參數$\\lambda$,且$\\lambda > 0$\n
\n
\n $\\begin{equation} \\nonumber f_X(x) = \\left\\{ \\begin{array}{l l} \\lambda e^{-\\lambda x} & \\quad x > 0\\\\ 0 & \\quad \\textrm{otherwise} \\end{array} \\right. \\end{equation}$\n
\n
\n\n##### 主要用途:\n\n* 表示獨立隨機案時間發生的時間間隔;\n* 在排隊輪中,一個顧客接受服務的時間段也可以用指數分佈來近似;\n* 無記憶性的現象(連續時間)\n\n##### 性質\n\n指數分佈的一個顯著的特點就是具有無記憶性。例如如果排隊的顧客接受服務的時間長短服從指數分佈,那麼無論你已經排了多久的隊伍,在排$t$分鐘的概率始終是相同的。\n
\n\n用公式表達則為:
\n
\n $P(X \\geq s + t | X \\geq s) = P(X \\geq t) \\text{ for all } s,t > 0$\n
\n
\n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\n\ndef exponential_dis(loc=0, scale=1.0):\n \"\"\"\n 指数分布,exponential continuous random variable\n 按照定义,指数分布只有一个参数lambda,这里的scale = 1/lambda\n :param loc: 定义域的左端点,相当于将整体分布沿x轴平移loc\n :param scale: lambda的倒数,loc + scale表示该分布的均值,scale^2表示该分布的方差\n :return:\n \"\"\"\n exp_dis = stats.expon(loc=loc, scale=scale)\n x = np.linspace(exp_dis.ppf(0.000001),\n exp_dis.ppf(0.999999), 100)\n fig, ax = plt.subplots(1, 1)\n\n # 直接传入参数\n ax.plot(x, stats.expon.pdf(x, loc=loc, scale=scale), 'r-',\n lw=5, alpha=0.6, label='uniform pdf')\n\n # 从冻结的均匀分布取值\n ax.plot(x, exp_dis.pdf(x), 'k-',\n lw=2, label='frozen pdf')\n\n # 计算ppf分别等于0.001, 0.5, 0.999时的x值\n vals = exp_dis.ppf([0.001, 0.5, 0.999])\n print(vals) \n\n # Check accuracy of cdf and ppf\n print(np.allclose([0.001, 0.5, 0.999], exp_dis.cdf(vals)))\n\n r = exp_dis.rvs(size=10000)\n ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2)\n plt.ylabel('Probability')\n plt.title(r'PDF of Exp(0.5)')\n ax.legend(loc='best', frameon=False)\n plt.show()\n\nexponential_dis(loc=0, scale=2)\n```\n\n上圖是,$Exp(0,5)$的概率分佈函數圖
\n\n下面是對不同參數的指數分佈的概率分佈函數圖的比較:\n\n\n```python\ndef diff_exp_dis():\n \"\"\"\n 不同参数下的指数分布\n :return:\n \"\"\"\n exp_dis_0_5 = stats.expon(scale=0.5)\n exp_dis_1 = stats.expon(scale=1)\n exp_dis_2 = stats.expon(scale=2)\n\n x1 = np.linspace(exp_dis_0_5.ppf(0.001), exp_dis_0_5.ppf(0.9999), 100)\n x2 = np.linspace(exp_dis_1.ppf(0.001), exp_dis_1.ppf(0.999), 100)\n x3 = np.linspace(exp_dis_2.ppf(0.001), exp_dis_2.ppf(0.99), 100)\n fig, ax = plt.subplots(1, 1)\n ax.plot(x1, exp_dis_0_5.pdf(x1), 'b-', lw=2, label=r'lambda = 2')\n ax.plot(x2, exp_dis_1.pdf(x2), 'g-', lw=2, label='lambda = 1')\n ax.plot(x3, exp_dis_2.pdf(x3), 'r-', lw=2, label='lambda = 0.5')\n plt.ylabel('Probability')\n plt.title(r'PDF of Exponential Distribution')\n ax.legend(loc='best', frameon=False)\n plt.show()\n\ndiff_exp_dis()\n```\n\n#### 正態分佈(Normal Distribution)\n\n正態分佈,又名高斯分佈(Gaussian Distribution),是一種非常常見的連續概率分佈,經常用在自然和社會科學中表示一種不明的隨機變量。由於中心極限定理的存在,正太分佈也是所有分佈中應用最廣泛的分佈。
\n\n##### 定義:\n\n若隨機變量$X$的概率密度符合以下形式,就稱$X$服從參數為$\\mu, \\sigma$的正態分佈,記做:$X~N(\\mu,\\sigma^2)$.\n
\n
\n $f_X (x) = \\frac{1}{\\sqrt{2 \\pi } \\sigma} \\exp \\left\\{-\\frac{(x - \\mu)^2}{2 \\sigma^2} \\right\\}, \\hspace{20pt} \\textrm{for all } x \\in \\mathbb{R}.$\n
\n
\n\n如果上式公式中$\\mu = 0, \\sigma = 1$,就叫做標準正態分佈(Standard Normal Distribution),一般記做$Z~N(0,1)$
\n\n由於標準正態分佈在統計學中的重要地位,它的累積分佈函數(CDF)有一個專門的表示符號:$\\Phi$,一般在統計相關的書籍附錄中的“標準正太分佈函數值表”就是該值與隨機變量的取值之間的對應關係。\n\n\n```python\nimport scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(-3,3)\ny = stats.norm.cdf(x, loc=0, scale=1)\ny1 = stats.norm.pdf(x, loc=0, scale=1)\nax.plot(x,y,'-',label='cdf of standard norm')\nax.plot(x,y1,'-',label='pdf of standard norm')\nax.legend( loc='best',frameon=False)\n\nplt.title(r'Standard Normal Distribution')\n\nplt.show()\n```\n\n##### 正態分佈兩個參數含義:\n* 當固定$\\sigma$,改變$\\mu$時,$f(x)$圖形的形狀不變,只是沿著$x$軸做平移變換,因此$\\mu$被稱為位置參數(決定了(對稱軸的位置);\n*當固定$\\mu$,改變$\\sigma$時,$f(x)$圖形的對稱軸不變,形狀改變,$\\sigma$越小,圖形越高越瘦;$\\sigma$越大,圖形越矮越胖,因此$\\sigma$被稱為尺度參數(決定曲線的分散程度)
\n\n下面是示例:\n\n\n```python\nimport scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(-5,5)\ny = stats.norm.pdf(x, loc=0, scale=1)\ny1 = stats.norm.pdf(x, loc=2, scale=1)\nax.plot(x,y,'-',label='pdf of norm with mu = 0')\nax.plot(x,y1,'-',label='pdf of norm with mu = 2')\nax.legend(loc='best',frameon=True)\n\nplt.title(r'Normal Distribution')\n\nplt.show()\n```\n\n\n```python\nimport scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(-5,5)\ny = stats.norm.pdf(x, loc=0, scale=1)\ny1 = stats.norm.pdf(x, loc=0, scale=2)\nax.plot(x,y,'-',label='pdf of norm with sigma = 1')\nax.plot(x,y1,'-',label='pdf of norm with sigma = 2')\nax.legend(loc='best',frameon=True)\n\nplt.title(r'Normal Distribution')\n\nplt.show()\n```\n\n##### 性質:\n\n* $f(x)$關於$x = \\mu$對稱;\n* 當$x \\leq \\mu$時,$f(x)$ 時嚴格單調遞增函數;\n* $f_max = f(\\mu) = \\frac{1}{\\sqrt{2\\pi}\\sigma}$;\n* 當$X~N(\\mu,\\sigma^2)$時,$\\frac{X - \\mu}{\\sigma} \\sim N(0, 1)$\n
\n\n*利用第四點,我們在計算一般的正態分佈時,可以轉化成標準正態分佈進行計算*\n\n\n```python\ndef diff_normal_dis():\n\n norm_dis_0 = stats.norm(0, 1) # 标准正态分布\n norm_dis_1 = stats.norm(0, 0.5)\n norm_dis_2 = stats.norm(0, 2)\n norm_dis_3 = stats.norm(2, 2)\n\n x0 = np.linspace(norm_dis_0.ppf(1e-8), norm_dis_0.ppf(0.99999999), 1000)\n x1 = np.linspace(norm_dis_1.ppf(1e-10), norm_dis_1.ppf(0.9999999999), 1000)\n x2 = np.linspace(norm_dis_2.ppf(1e-6), norm_dis_2.ppf(0.999999), 1000)\n x3 = np.linspace(norm_dis_3.ppf(1e-6), norm_dis_3.ppf(0.999999), 1000)\n fig, ax = plt.subplots(1, 1)\n ax.plot(x0, norm_dis_0.pdf(x0), 'r-', lw=2, label=r'miu=0, sigma=1')\n ax.plot(x1, norm_dis_1.pdf(x1), 'b-', lw=2, label=r'miu=0, sigma=0.5')\n ax.plot(x2, norm_dis_2.pdf(x2), 'g-', lw=2, label=r'miu=0, sigma=2')\n ax.plot(x3, norm_dis_3.pdf(x3), 'y-', lw=2, label=r'miu=2, sigma=2')\n plt.ylabel('Probability')\n plt.title(r'PDF of Normal Distribution')\n ax.legend(loc='best', frameon=False)\n plt.show()\n\ndiff_normal_dis()\n```\n\n### 隨機變量的數字特徵(Numerical Characteristic)\n\n如果說一個隨機變量的分佈函數(累積分佈函數或概率密度分佈)是對隨機變量最完整,最具體的描述,那麼隨機變量的數字特徵就是對該隨機變量特徵的描述。分佈函數就如同一個人的全身像,而數字特徵就像一個人的局部特寫。\n\n#### 常見的數字特徵:\n\n* 數學期望(Expectation)\n* 方差(Variance)\n* 矩(Moments)\n* 協方差和相關係數(Covariance and Correlative Coefficient )\n\n前面三個數字特徵都是耽擱隨機變量自身的特徵,第四個數字特徵則是表示兩個隨機變量之間的關係,其他數學特種還有中位數,眾數等等\n\n#### 數學期望(Matematical Expectation)\n\n一個隨機變量$X$的數學期望,簡稱期望,也叫做均值(Mean),記做E(X)。常見於隨機變量的定義中,都直接或間接包含了“期望”這個參數,該參數一般於分佈在座標軸上的位置有關。期望與我們平時說的平均值不多,體現的是隨機變量中的“大碩鼠”的取值情況或趨勢。\n
\n\n在計算中,隨機變量$X$的平均值E(X)並不等於一個具體樣本集$x$的均值E(x)$\\Rightarrow$計算一個具體樣本集的均值時,是將所有的值求和然後除以樣本個數,因為此時的$x$已經是一個具體的數列,而不再具有隨機性$\\Rightarrow$隨機變量$X$的均值是加權平均數。\n
\n\n例如,一個離散型隨機變量$X$的概率質量分佈列如下:\n
\n\n|X|0|1|2|3|4|\n|------|----|----|----|----|----|\n|P(X=x)|0.15|0.30|0.25|0.20|0.10|\n
\n\n那麼,根據定義,我們可以算出:$E(X) = \\displaystyle \\sum_{ i = 1 }^{ n } x_i p_i = 0 \\times 0.15 + 1 \\times 0.3 + 2 \\times 0.25 + 3 \\times 0.2 + 4 \\times 0.1 = 1.8$;如果我們從該隨機變量中取1個樣本集$x_1 = 1,1,2,4,4$,那麼$E(x_1) = \\frac{1 + 1 + 2 + 4 + 4}{5} = 2.4$\n\n此外,正是定義中對期望是否存在給出了明確的定義:在求離散型隨機變量的期望時,需要其和式構成的級數是收斂的;在連續型隨機變量時,也有類似的要求。一個典型的例子:連續型隨機變量「柯西分佈」因為不滿足此條件,所以不具有均值,具體解釋可以參考: Comparing the Cauchy and Gaussian (Normal) density function Why does the Cauchy distribution have no mean ? \n\n##### 期望的性質:\n\n* 設$c$為一個常數,則$E(c) = c$;\n* 設$X$是一個隨機變量,$c$是常數,則$E(cX) = cE(X)$;\n* 設$X,Y$是兩個隨機變量,則有$E(X + Y) = E(X) + E(Y)$;
\n\n將上面三個性質結合起來,則有:$E(aX + bY + c) = aE(X) + bE(Y) + c$,可以推廣到任意有限個隨機變量線性組合的情況;\n\n* 設$X,Y$是相互獨立的兩個隨機變量,則有$E(XY) = E(X)E(Y)$,可以推廣到任意有限個相互獨立的隨機變量之積的情況。\n\n##### 常見分佈的期望\n\n下面這些分佈的期望是指隨機變量的期望,而不是某個隨機變量抽樣得到的樣本集的期望。在離散隨機變量中,數學期望的物理意義是「一維離散質點系的重心坐標“,在連續型隨機變量中,數學期望的物理意義是「一維連續質點系的重心坐標”。\n
\n\n* 0-1 分佈:$X~B(1,p), E(X) = p$;\n* 二項分佈:$X~B(n,p), E(X) = np$;\n* 泊松分佈:$X~P(\\lambda), E(X) = \\lambda$;\n* 幾何分佈:$X~G(p), E(X) = \\frac{1}{p}$;\n* 均勻分佈:$X~N(a, b), E(X) = \\frac{a+b}{2}$;\n* 正態分佈:$X~N(\\mu, \\sigma^2), E(X) = \\mu$;\n* 指數分佈,$X~E(\\lambda), E(X) = \\frac{1}{\\lambda}$\n\n##### 樣本均值的計算\n\n在實際的應用中,我們一般都是已知某個分佈的一組樣本,需要求這組樣本的均值。在計算時,定義中的平均值時算術平均值;還有一種是計算幾何平均值,及所有樣本值相乘後開$N$次方,$N$為樣本數。\n
\n\n算術平均值和幾何平均值最大的區別在於:如果樣本中有$0$存在,幾何平均值就等於$0$;如果樣本中不包含$0$,通常算數平均值$\\geq$幾何平均值。下面是 $Python$的實現方法\n\n\n```python\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\n\n## 计算平均值\nx = np.arange(1, 11)\nprint(x) # [ 1 2 3 4 5 6 7 8 9 10]\nmean = np.mean(x)\nprint(mean) # 5.5\n\n# 对空值的处理,nan stands for 'Not-A-Number'\nx_with_nan = np.hstack((x, np.nan))\nprint(x_with_nan) # [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. nan]\nmean2 = np.mean(x_with_nan)\nprint(mean2) # nan,直接计算没有结果\nmean3 = np.nanmean(x_with_nan)\nprint(mean3) # 5.5\n\n## 计算几何平均值\nx2 = np.arange(1, 11)\nprint(x2) # [ 1 2 3 4 5 6 7 8 9 10]\ngeometric_mean = stats.gmean(x2)\nprint(geometric_mean) # 4.52872868812,几何平均值小于等于算数平均值\n```\n\n [ 1 2 3 4 5 6 7 8 9 10]\n 5.5\n [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. nan]\n nan\n 5.5\n [ 1 2 3 4 5 6 7 8 9 10]\n 4.52872868812\n\n\n#### 方差(Variance)\n\n一個隨機變量$X$的方差,刻畫了$X$取值的波動性,是衡量該隨機變量取值分散程度的數字特徵。方差越大,就表示該隨機變量越分散;方差越小,表示該隨機變量越集中。在實際應用中,例如常見的「QC」問題,如果一個工廠的出場的合格評分方差大,說明了優質品和劣質品都比較多,**出品不穩定**;相反,如果方差比較小,說明了合格品比較多,優質品和劣質品較少,**出品穩定**\n\n##### 性質:\n1. 設$c$為常數,則$Var(c) = 0$;\n2. 設$X$是一個隨機變量,$c$是常數,則$Var(cX) = c^2 Var(X)$;特例,$D(-X) = D(X)$;\n3. 設$X, Y$是兩個隨機變量,則有$Var(X + Y) = Var(X) + Var(Y) + 2\\cdot tail$,其中,$tail = E[X-E(X)][Y-E(Y)]$. 特別的,如果$X, Y$相互獨立,則$tail = 0$\n4. $Var(X) = 0 \\Leftrightarrow P(X = c) =1,$ 且$c = E(X)$ ;\n5. 當$X, Y$相互獨立時,$Var(XY) = Var(X)Var(Y) + Var(X)[E(Y)]^2 +Var(Y)[E(X)]^2$\n
\n\n還有一個常用的計算方差的公式:$D(X) = E(X^2) - [E(X)]^2$\n\n##### 常見分佈的方差:\n\n* 0-1 分佈:$X~B(1,p), Var(X) = p(1-p)$;\n* 二項分佈:$X~B(n,p), Var(X) = np(1-p)$;\n* 泊松分佈:$X~P(\\lambda), Var(X) = \\lambda$;\n* 幾何分佈:$X~G(p), Var(X) = \\frac{1-p}{p^2}$;\n* 均勻分佈:$X~N(a, b), Var(X) = \\frac{(b-a)^2}{12}$;\n* 正態分佈:$X~N(\\mu, \\sigma^2), Var(X) = \\sigma^2, (\\sigma > 0)$;\n* 指數分佈,$X~E(\\lambda), Var(X) = \\frac{1}{\\lambda^2}$\n\n##### 樣本方差的計算\n\n就如同計算均值一樣,通常我們的計算都是從某個分佈中抽樣得到的一組樣本的方差,樣本方差一般使用$S^2$表示,按照方差的定義:\n
\n
\n $Var(X) = E{[X - E(X)]^2} = \\frac{1}{n} \\displaystyle \\sum_{i=1}^{n}(X_i - \\bar{X})^2$\n
\n
\n\n其中:$\\bar{X} = E(X)$。如果直接用上面的公式計算$S^2$,等同於使用樣本的二階中心距。但是樣本的二階中心距並不是隨機變量$X$這個總體分佈的無偏估計,將上式中的$n$換成$n-1$就得到了樣本方差計算公式,這也是總體方差無偏估計。\n
\n
\n $S^2 = \\frac{1}{n - 1} \\displaystyle \\sum_{i=1}^{n}(X_i - \\bar{X})^2$\n
\n
\n\n從直觀來說,由於樣本方差中多了一個約束條件 ——樣本的均值時固定的,$E(X) = \\bar{X} \\Rightarrow $如果已知$n-1$樣本,那麼根據均值可以直接計算出第$n$哥樣本的值,因此自由度比計算總體方差的時候減少了$1$個。\n\n\n```python\nimport numpy as np\n\n# 参考\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html\n# https://docs.scipy.org/doc/numpy/reference/generated/numpy.var.html\n\n\ndata = np.arange(7, 14)\nprint(data) # [ 7 8 9 10 11 12 13]\n\n## 计算方差\n# 直接使用样本二阶中心距计算方差,分母为n\nvar_n = np.var(data) # 默认,ddof=0\nprint(var_n) # 4.0\n# 使用总体方差的无偏估计计算方差,分母为n-1\nvar_n_1 = np.var(data, ddof=1) # 使用ddof设置自由度的偏移量\nprint(var_n_1) # 4.67\n\n\n## 计算标准差\nstd_n = np.std(data, ddof=0)\nstd_n_minus_1 = np.std(data, ddof=1) # 使用ddof设置自由度的偏移量\nprint(std_n, std_n_minus_1) # 2.0, 2.16\nprint(std_n**2, std_n_minus_1**2) # 4.0, 4.67\n```\n\n [ 7 8 9 10 11 12 13]\n 4.0\n 4.66666666667\n 2.0 2.16024689947\n 4.0 4.66666666667\n\n\n#### 矩\n\n矩是一個非常廣泛的概念,期望和方差都是矩的特例。
\n\n##### 定義:\n\n* 若$E(X^k), k = 1, 2, \\dots $存在,則稱$E(X^k)$為$X$的$k$階原點矩,記做$\\alpha_k = E(X^k)$;\n* 若$E[X - E(X)]^k, k = 1, 2, \\dots$存在,則稱$E[X-E(X)]^k$為$X$的$k$階中心距,記做$\\beta_k = E[X-E(X)]^k$ \n\n根據定義,期望$E(X)$ 是1階原點矩,方差$D(X)$是2階中心距。需要注意的是,就跟上面提到的一樣,樣本的2屆中心距並不是總體方差的無偏估計,樣本方差$S^2$的時機計算公式中分母為$n-1$,而不是樣本2階中心距中的$n$。\n
\n\n**符號說明**:\n\n* 總體k阶原點矩:$α_k$;\n* 總體k阶中心矩:$β_k$;\n* 樣本k阶原點矩:$A_k$;\n* 樣本k阶中心矩:$B_k$;\n\n#### 協方差(Covariance)\n\n上面介紹了幾種隨機變量的數字特徵都是描述耽擱隨機變量拘捕性質的量,協方擦好和相關係數則是用來度量兩個不同的隨機變量之間的相關程度。
\n\n##### 協方差\n\n如上面介紹方差的性質時,第(3)條提到的那樣:\n
\n\n設$X, Y$是兩個隨機變量,則有$ Var(X + Y) = Var(X) + Var(Y) + 2\\cdot tail$,其中,$tail = E[X - E(X)][Y - E(Y)].$ 特別的,若$X, Y$相互獨立,那麼$tial = 0$,那麼$tail$不等於$0$,就代表了這兩個隨機變量不相互獨立。$tail$就是$X$與$Y$的協方差。\n\n##### 定義:\n\n數值$E[X-E(Y)][Y-E(Y)]$為隨機變量$X$與$Y$的協方差,記做$Cov(X,Y)$,即:\n
\n
\n $Cov(X, Y) = E{[X - E(X)][Y - E(Y)]}$\n
\n
\n\n此時,$Var(X + Y) = Var(X) + Var(Y) + 2Cov(X,Y)$,協方差$Cov(X, Y)$反映了隨機變量的$X$與$Y$的線性相關性:
\n\n* 當$Cov(X,Y0 > 0$時,稱$X$與$Y$正相關;\n* 當$Cov(X,Y0 < 0$時,稱$X$與$Y$負相關;\n* 當$Cov(X,Y0 = 0$時,稱$X$與$Y$無關;\n\n協方差的計算公式可以簡化成:$Cov(X,Y) = E(XY) - E(X)E(Y)$\n\n##### 相關係數\n\n協方差時有量綱的數字特徵,為了消除其量綱的影響,引入了相關係數,在平時的數據分析中協方差很少出現,先港係數出現的頻率非常高。\n
\n
\n $\\rho_{XY} = \\frac{Cov(X, Y)}{\\sqrt{D(X)D(Y)}}$\\\n
\n
\n\n稱為隨機變量$X$與$Y$的相關係數。\n\n##### 相關係數的性質\n\n* $|\\rho XY|\\leq 1$(相關係數的值位於區間[-1,1]);\n* $|\\rho XY| = 1 \\Rightarrow$ 存在常數$a,b$使得$P(Y = a+bX)=1$. 特別的,$\\rho XY = 1$時,$b > 0$;$\\rho = 1$時,$b < 0$. 與協方差,相關係數也是用來表徵兩個隨機變量之間線性關係密切程度的特徵數,有時也稱為「線性相關係數」\n\n#### 樣本均值的期望和方差\n\n設隨機變量$X$的一組樣本為$x$,則樣本的矩陣$\\bar{x} = \\frac{1}{n} \\displaystyle \\sum_{i=1}^{n}x_i$。此時的樣本$x$與樣本均值$\\bar{x}$都是確定的數值,不具有隨機行。但是,如果我們卻了很多組樣本L:$x^{(1)}, x^{(2)}, ...$那麼這些樣本的均值$\\bar{x}^{(1)}, \\bar{x}^{(2)}, ...$就可以組成一個新的隨機變量,可以記做$\\bar{X}$,每一個樣本均值也可以看作從該隨機變量中抽樣所得。
\n\n樣本均值$\\bar{X}$這個隨機變量時隨機變量$X$的函數。根據期望和方差的定義,我們可以求出樣本均值的期望和方差。
\n假設隨機變量$X$的期望和方差分別是:$\\mu$和$\\sigma^2$\n\n* E($\\bar{X}$) = $\\mu$,樣本均值的期望與原隨機變量的期望相同;\n* Var($\\bar{X}$) = $\\frac{\\sigma^2}{n}$,其中$n$為每次取樣的樣本量,\n\n\n\n```python\nimport numpy as np\nfrom scipy import stats\n\ndef mean_and_std_of_sample_mean(ss=[], group_n=100):\n \"\"\"\n 不同大小样本均值的均值以及标准差\n \"\"\"\n norm_dis = stats.norm(0, 2) # 定义一个均值为0,标准差为2的正态分布\n for n in ss:\n sample_mean = [] # 收集每次取样的样本均值\n for i in range(group_n):\n sample = norm_dis.rvs(n) # 取样本量为n的样本\n sample_mean.append(np.mean(sample)) # 计算该组样本的均值\n print(np.std(sample_mean), np.mean(sample_mean))\n\nsample_size = [1, 4, 9, 16, 100] # 每组试验的样本量\ngroup_num = 10000\nmean_and_std_of_sample_mean(ss=sample_size, group_n=group_num)\n```\n\n 1.99008474793 -0.0208546895623\n 1.00750814281 0.00347718092382\n 0.672067720702 0.00687662521186\n 0.503784014261 0.00284508641179\n 0.20016653808 0.000791586359448\n\n\n#### 樣本均值的期望和方差\n\n設隨機變量$X$的一組樣本為$x$,則樣本的均值$\\bar{x} = \\frac{1}{n} \\displaystyle \\sum_{i=1}^{n}x_i$。此時的樣本$x$與樣本均值$x$都是確定的數值,不具有隨機行。但是,如果我們取了很多組樣本:$x^{(1)}, x^{(2)}, ...$那麼這些樣本的均值$\\bar{x}^{(1)}, \\bar{x}^{(2)}, ...$就可以組成一個新的隨機變量,可以記做$\\bar{X}$,每一個樣本均值也可以看做是從該隨機變量中抽樣所得。
\n\n樣本均值$\\bar{X}$這個隨機變量$X$的函數。根據期望和方差的定義,我們可以求出樣本均值的期望和方差。假設隨機變量$X$的期望和方差分別為$\\mu$和$\\sigma^2$\n* $E(\\bar{X}) = \\mu$,樣本均值的期望與原隨機變量的期望相同;\n* $D(\\bar{X}) = \\frac{\\sigma^2}{n}$,其中$n$ 為每次取樣的樣本量,這裡的$n$不表示樣本組數,而是單組中的樣本量;樣本組數在這裡並沒有體現。這是因為**$\\bar{X}$的随机性是在获取单组样本时体现出来的(即结果的不确定性),跟组数无关(当每组样本获得之后,数据就不在具有随机性了)。由此可见,每次采样的样本量越多,得到的样本均值的方差也越小,也就表示更加准确,但是取样所用的时间和成本也同时增加了。这就需要在准确型和成本之间做一个权衡。
\n\n
\n下面用程序做一個測試,測試的是樣本均值的標準差隨著樣本量的變化而發生的變化,如果方差縮小$n$倍,那麼理論上標準差會縮小$\\sqrt n$倍。\n\n\n```python\nimport numpy as np\nfrom scipy import stats\n\ndef mean_and_std_of_sample_mean(ss=[], group_n=100):\n \"\"\"\n 不同大小样本均值的均值以及标准差\n \"\"\"\n norm_dis = stats.norm(0, 2) # 定义一个均值为0,标准差为2的正态分布\n for n in ss:\n sample_mean = [] # 收集每次取样的样本均值\n for i in range(group_n):\n sample = norm_dis.rvs(n) # 取样本量为n的样本\n sample_mean.append(np.mean(sample)) # 计算该组样本的均值\n print(np.std(sample_mean), np.mean(sample_mean))\n\nsample_size = [1, 4, 9, 16, 100] # 每组试验的样本量\ngroup_num = 10000\nmean_and_std_of_sample_mean(ss=sample_size, group_n=group_num)\n```\n\n 1.99183803618 0.0461229296359\n 1.00674682296 0.0177540329668\n 0.668143024892 0.00299211910315\n 0.498323040688 -0.00523627140067\n 0.201260608929 0.00134588313727\n\n\n具體的證明過程,可以參考Mean and Variance of Sample Mean\n\n## Chapter Two Statistics \n\n### 大數定理與中心極限定理\n\n這兩個定理可以說是概率論中最重要的兩個定理,也是因為中心極限定理的存在,才使得正態分佈稱為應用最為廣泛的分佈。\n\n#### 大數定理(Law of Large Numbers, LLN)\n\n大數定理可以說是整個數理統計學的一塊基石,最早的大數定理是由伯努利在他的著作中提出並給予證明的。數理統計中包含了兩類問題$\\Rightarrow$對於概率$p$的檢驗和估計。大數定律的本事是一類極限定理,它是由概率的統計定義“頻率收斂與概率“引申而來。簡單的說就是$n$個獨立同分佈的隨機變量的觀察值的均值$\\bar{X}$依概率收斂與這些隨機變量所屬分佈的理論均值,也就是總體均值。

\n假設我們現在有兩種大小質地相同的球:紅球a個,白球b個,放入一個盒子,隨機抽出一個球,這個球是紅球的概率$p = \\frac{a}{a+b}$。但是,如果我們不清楚$a$和$b$,則無法得出$p$,這時,我們可以反覆的抽球(有放回)。設我們抽了$N$次,發現白球出現了$M$次,則用$\\frac{M}{N}$去估計$p$值。這個估計是會有誤差的,但是我們會認為,當$N$越大,則誤差會縮小。

\n**從現實(實用)的角度去看,概率的統計定義無非是通過試驗去估計時間概率的方法**\n\n##### 定義:\n\n設$X_1, X_2, ..., X_n$是獨立同分佈(i.i.d)的隨機變量,記它們的共喔過年均值為$\\mu$。又設它們的方擦好存在並記做$\\sigma^2$。則對任意給定的$\\varepsilon > 0$,有\n
\n
\n $\\displaystyle \\lim_{ n \\to \\infty } P(| \\bar{X}_n - \\mu| \\geq \\varepsilon) = 0 \\hspace{ 10pt } \\ldots (1-1)$\n
\n
\n\n這個式子指出了「當$n$很大時,$\\bar{X}_n$接近$\\mu$」的確切含義。這裡的“接近”時概率上的嗎,也就是說概率非常小,但還是由一定的概率出現意外情況(例如上式的概率大於$\\epsilon$)。只是這樣的可能性越來越小,這樣的收斂型,在概率論中叫做”$\\bar{X}_n$依概率收斂與$\\mu$“。\n\n下面是用 python 來模擬拋硬幣:\n
\n用 random 模塊生成區間$[0,1)$之間的隨機數,如果生成的數小於0.5,就記為硬幣正面朝上,否則幾位硬幣反面朝上。由於`random.random()`生成的數可以看做服從在區間`[0,1)`上的均勻分佈,所以以0.5為界線,隨機生成的數大於0.5或小於0.5的概率應該是相同的(相當於硬幣為均勻的)。這樣就用隨機數模擬了時機拋硬幣試驗。理論上試驗次數越多(拋硬幣次數越多),正反面出現次數之比越接近1。\n\n\n```python\nimport random\nimport matplotlib.pyplot as plt\n\n\ndef flip_plot(minExp, maxExp):\n \"\"\"\n Assumes minExp and maxExp positive integers; minExp < maxExp\n Plots results of 2**minExp to 2**maxExp coin flips\n \"\"\"\n # 两个参数的含义,抛硬币的次数为2的minExp次方到2的maxExp次方,\n #也就是一共做了(2**maxExp - 2**minExp)批次实验,每批次重复抛硬币2**n次\n\n ratios = []\n xAxis = []\n for exp in range(minExp, maxExp + 1):\n xAxis.append(2**exp)\n for numFlips in xAxis:\n numHeads = 0 # 初始化,硬币正面朝上的计数为0\n for n in range(numFlips):\n if random.random() < 0.5: # random.random()从[0, 1)随机的取出一个数\n numHeads += 1 # 当随机取出的数小于0.5时,正面朝上的计数加1\n numTails = numFlips - numHeads # 得到本次试验中反面朝上的次数\n ratios.append(numHeads/float(numTails)) #正反面计数的比值\n plt.title('Heads/Tails Ratios')\n plt.xlabel('Number of Flips')\n plt.ylabel('Heads/Tails')\n plt.plot(xAxis, ratios)\n plt.hlines(1, 0, xAxis[-1], linestyles='dashed', colors='r')\n plt.show()\n\nflip_plot(4, 16)\n```\n\n#### 中心極限定理(Central Limit Theorem,CLT)\n\n中心極限定理描述的是某種形式變量之和的分佈。
\n\n##### 從大數定理倒中心極限定理\n\n> 简单来说,大数定律(LLN)和中心极限定理(CLT)的联系与区别在于:\n共同点:都是用来描述独立同分布(i.i.d)的随机变量的和的渐进表现(asymptotic behavior)\n区别:首先,它们描述的是在不同的收敛速率(convergence rate)之下的表现,其次LLN前提条件弱一点:$E(X^2)<\\infty$ CLT成立条件强一点:$E(X_2)<∞$\n\n摘自知乎:**Detian Deng** 的回答\n\n##### 定理\n\n假設${X_n}$為$i.i.d$的隨機變量序列,具有公共的數學期望$\\mu$和方差$\\sigma^2$,則$X_1 + \\dots + X_n$ 的標準形式$\\frac{1}{\\sqrt n} \\sigma (X_1 + X_2 + \\dots X_n - n\\mu)$滿足中心極限定理。即,對任意$x\\in R$,有:\n
\n
\n $\\lim_{n\\rightarrow \\infty} F_n(x) = \\Phi(x)$\n
\n
\n\n其中$F_n(x)$為$\\frac{1}{\\sqrt n} \\sigma (X_1 + X_2 + \\dots X_n - n\\mu)$的分佈函數,而$\\Phi(x)$為標準正態分佈$N(0,1)$的分佈函數,記做:\n
\n
\n $\\frac{1}{\\sqrt n} \\sigma (X_1 + X_2 + \\dots X_n - n\\mu) \\stackrel{d}{\\longrightarrow} N(0,1)$\n
\n
\n\n這個定理說明了:**任何獨立同分佈的隨機變量序列,不論它的分佈是什麼,只要存在有限的方差,那麼它們的標準化部分和都會逐漸近於正態分佈**,這也說明了正態分佈的普遍性。由這個定理,我們可以得到下面這個推論:
\n\n設$X_1, \\dots,X_n$相互獨立且具有相同的分佈:\n
\n
\n$P(X_1 = 1) = 1-P(X_1 = 0)=p, 0\n
\n\n則有:\n
\n
\n$\\frac{X_1, \\dots,X_n}{\\sqrt{np(1-p)}} \\stackrel{d}{\\longrightarrow} N(0,1)$\n
\n
\n\n即:\n
\n
\n$\\lim_{n\\rightarrow \\infty}\\frac{X_1, \\dots,X_n}{\\sqrt{np(1-p)}} \\stackrel{d}{\\longrightarrow} N(0,1)$\n
\n
\n\n這就是棣莫弗-拉普拉斯定理,最早的中心極限定理。\n\n題目:
\n\n设一考生参加 100 道题的英语标准化考试 (每道题均为有两个备选答案的选择题,有且仅有一个答案是正确的),每道题他都随机地选择一个答案,假设评分标准为:选对得一分,选错或不选不得分。 试给出该考生最终得分大于等于 50 的概率.\n
\n\n解答:每一題都是一個伯努利分佈,既然是隨機選擇,那麼選擇正確的概率就是$\\frac{1}{2}$,100道題,說明這是一個$n = 100$的$n$重伯努利分佈。分數則是這個樣本數據的期望。$X~B(100,0.5)$,通過`python`畫出圖像:\n\n\n```python\nbinom_pmf(n=100, p=0.5)\n```\n\n\n```python\nimport scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(-20,120)\ny = stats.norm.pdf(x, loc=50, scale=25)\nax.plot(x,y,'-',label='pdf of norm ')\nax.legend(loc='best',frameon=True)\n\nplt.title(r'Normal Distribution')\n\nbinom_pmf(n=100, p=0.5)\nplt.show()\n```\n\n我們把它們放在一起看實際上,兩服圖已經長的十分相近了。\n\n\n```python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\n\"\"\"\nCreated on Sun Nov 12 08:44:37 2017\n\n@author: Belter\n\"\"\"\n\n\ndef sampling2pmf(n, dist, t=10000):\n \"\"\"\n n: sample size for each experiment\n t: how many times do you do experiment, fix in 10000\n dist: frozen distribution\n \"\"\"\n ber_dist = dist\n sum_of_samples = []\n for i in range(t):\n samples = ber_dist.rvs(size=n) # 与每次取一个值,取n次效果相同\n sum_of_samples.append(np.sum(samples))\n val, cnt = np.unique(sum_of_samples, return_counts=True)\n pmf = cnt / len(sum_of_samples)\n return val, pmf\n\n\ndef plot(n, dist, subplot, plt_handle):\n \"\"\"\n :param n: sample size\n :param dist: distribution of each single sample\n :param subplot: location of sub-graph, such as 221, 222, 223, 224\n :param plt_handle: plt object\n :return: plt object\n \"\"\"\n bins = 10000\n plt = plt_handle\n plt.subplot(subplot)\n mu = n * dist.mean()\n sigma = np.sqrt(n * dist.var())\n samples = sampling2pmf(n=n, dist=dist)\n plt.vlines(samples[0], 0, samples[1],\n colors='g', linestyles='-', lw=3)\n plt.ylabel('Probability')\n plt.title('Sum of bernoulli dist. (n={})'.format(n))\n # normal distribution\n norm_dis = stats.norm(mu, sigma)\n norm_x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, bins)\n pdf1 = norm_dis.pdf(norm_x)\n plt.plot(norm_x, pdf1, 'r--')\n return plt\n\nsize = [1, 4, 20, 80, 200, 1000]\n\n# sum of bernoulli distribution\ndist_type = 'bern'\nbern_para = [0.5]\nsingle_sample_dist = stats.bernoulli(p=bern_para[0]) # 定义一个伯努利分布\n\n# 下面是利用matplotlib画图\nplt.figure(1)\nplt = plot(n=size[0], dist=single_sample_dist, subplot=321, plt_handle=plt)\nplt = plot(n=size[1], dist=single_sample_dist, subplot=322, plt_handle=plt)\nplt = plot(n=size[2], dist=single_sample_dist, subplot=323, plt_handle=plt)\nplt = plot(n=size[3], dist=single_sample_dist, subplot=324, plt_handle=plt)\nplt = plot(n=size[4], dist=single_sample_dist, subplot=325, plt_handle=plt)\nplt = plot(n=size[5], dist=single_sample_dist, subplot=326, plt_handle=plt)\nplt.tight_layout()\nplt.savefig('sum_of_{}_dist.png'.format(dist_type), dpi=200)\n```\n\n由上圖可以看出,增加試驗次數和x軸上的分割區間的個數後,隨機變量之和與正態分佈之間的重合度隨著樣本量的增加而增高。這就很容易解釋:對於隨機變量的分佈,抽樣次數(試驗次數)越多,最終畫出來的圖越能代表整個分佈。但是抽樣次數本事卻不影響該分佈的類型和參數。**抽樣不會影響真實分佈,只會影響樣本分佈**\n\n### 三大抽樣分佈\n\n抽樣分佈就是統計量的分佈其特點是不包含位置參數且儘可能多的去包含樣本信息。除了常見的整台分佈之外,還有卡方分佈、t分佈和F分佈為最常見的描述抽樣分佈的分佈函數。我們常說的卡方檢驗、t檢驗和F檢驗和這三個分佈有關。\n\n#### $\\chi^2$分佈\n\n##### 定義\n\n設$X_1,X_2,\\dots, X_n$ i.i.d.~$N(0,1)$,令$X = \\displaystyle \\sum^n_{i=1}X^2_i$,則稱$X$是自由度為$n$的$\\chi^2$變量,其分佈稱為自由度為$n$的$\\chi^2$分佈,記做$X~\\chi^2_n$
\n\n我們設隨機變量$X$是自由度為$n$的$\\chi^2$隨機變量,則其概率密度函數為:\n
\n
\n $\\begin{equation}\ng_n(x) = \n\\left\\{\n \\begin{array}{lr}\n \\frac{1}{2^{\\frac{n}{2}}\\Gamma(\\frac{n}{2})} x^{\\frac{n}{2}-1} e^{-\\frac{x}{2}} \\ \\ & x > 0 \\\\ \n 0 \\ \\ & x \\leq 0\n \\end{array}\n\\right.\n\\end{equation}$\n
\n
\n\n$\\chi^2_n$的密度函數$g_n(x)$形狀如下:\n\n\n```python\ndef chi2_distribution(df = 1):\n fig, ax = plt.subplots(1, 1)\n\n x = np.linspace(stats.chi2.ppf(0.001, df),\n stats.chi2.ppf(0.999, df), 200)\n ax.plot(x, stats.chi2.pdf(x, df), 'r-',\n lw=5, alpha=0.6, label=r'$\\chi^2$ pdf')\n \n chi2_dis = stats.chi2(df=df)\n ax.plot(x, chi2_dis.pdf(x), 'k-',\n lw=2, label='frozen pdf')\n vals = chi2_dis.ppf([0.001, 0.5, 0.999])\n print(vals) # [ 2.004 4. 5.996]\n\n r = chi2_dis.rvs(size=1000)\n ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2)\n plt.ylabel('Probability')\n plt.title(r'PDF of $\\chi^2$({})'.format(df))\n ax.legend(loc='best', frameon=False)\n plt.show()\n \nchi2_distribution(df=10)\n\n```\n\n\n```python\ndef diff_chi2_dis():\n \"\"\"\n 不同参数下的卡方分布\n :return:\n \"\"\"\n # chi2_dis_0_5 = stats.chi2(df=0.5)\n chi2_dis_1 = stats.chi2(df=1)\n chi2_dis_4 = stats.chi2(df=4)\n chi2_dis_10 = stats.chi2(df=10)\n chi2_dis_20 = stats.chi2(df=20)\n\n # x1 = np.linspace(chi2_dis_0_5.ppf(0.01), chi2_dis_0_5.ppf(0.99), 100)\n x2 = np.linspace(chi2_dis_1.ppf(0.65), chi2_dis_1.ppf(0.9999999), 100)\n x3 = np.linspace(chi2_dis_4.ppf(0.000001), chi2_dis_4.ppf(0.999999), 100)\n x4 = np.linspace(chi2_dis_10.ppf(0.000001), chi2_dis_10.ppf(0.99999), 100)\n x5 = np.linspace(chi2_dis_20.ppf(0.00000001), chi2_dis_20.ppf(0.9999), 100)\n fig, ax = plt.subplots(1, 1)\n # ax.plot(x1, chi2_dis_0_5.pdf(x1), 'b-', lw=2, label=r'df = 0.5')\n ax.plot(x2, chi2_dis_1.pdf(x2), 'g-', lw=2, label='df = 1')\n ax.plot(x3, chi2_dis_4.pdf(x3), 'r-', lw=2, label='df = 4')\n ax.plot(x4, chi2_dis_10.pdf(x4), 'b-', lw=2, label='df = 10')\n ax.plot(x5, chi2_dis_20.pdf(x5), 'y-', lw=2, label='df = 20')\n plt.ylabel('Probability')\n plt.title(r'PDF of $\\chi^2$ Distribution')\n ax.legend(loc='best', frameon=False)\n plt.show()\n\ndiff_chi2_dis()\n```\n\n通過上圖可以看出,當自由度df等於1時,函數突襲那個呈現單調遞減的趨勢;當df大於等於3後,呈現先增後減的缺失。從定義中得出,$df \\geq 0$\n\n#### t分佈\n\nt分佈又名「學生t分佈(Student's t-distribution),用於根據小樣本來估計呈正態分佈且方差位置的總體的均值。如果總體方差已知(例如在樣本數量足夠多時),則應該用正態分佈來估計總體均值。\n\n##### 定義:\n\n設隨機變量$X~N(0,1),Y~\\chi^2_n$,且$X$和$Y$獨立,則稱:\n
\n
\n $T = \\frac{X}{\\sqrt{Y/n}}$\n
\n
\n\n為自由度為$n$的$t$變量,其分佈稱為由為$n$的t分佈,記做$T~t_n$\n
\n\n設隨機變量$T~t_n$,則其密度函數為:\n
\n
\n $t_n(x) = \\frac{\\Gamma(\\frac{n+1}{2})}{\\Gamma(\\frac{n}{2}\\sqrt{n\\pi}} (1 + \\frac{x^2}{n})^{-\\frac{n+1}{2}}, \\ -\\infty < x < \\infty$\n
\n
\n\n\n```python\ndef diff_t_dis():\n \"\"\"\n 不同参数下的t分布\n :return:\n \"\"\"\n norm_dis = stats.norm()\n t_dis_1 = stats.t(df=1)\n t_dis_4 = stats.t(df=4)\n t_dis_10 = stats.t(df=10)\n t_dis_20 = stats.t(df=20)\n\n x1 = np.linspace(norm_dis.ppf(0.000001), norm_dis.ppf(0.999999), 1000)\n x2 = np.linspace(t_dis_1.ppf(0.04), t_dis_1.ppf(0.96), 1000)\n x3 = np.linspace(t_dis_20.ppf(0.001), t_dis_20.ppf(0.999), 1000)\n \n fig, ax = plt.subplots(1, 1)\n ax.plot(x1, norm_dis.pdf(x1), '--', lw=2, label=r'N(0, 1)')\n ax.plot(x2, t_dis_1.pdf(x2), 'b-', lw=2, label='t(1)')\n ax.plot(x3, t_dis_20.pdf(x3), 'y-', lw=2, label='t(20)')\n \n plt.ylabel('Probability')\n plt.title(r'PDF of t Distribution')\n ax.legend(loc='best', frameon=False)\n plt.show()\n\ndiff_t_dis()\n```\n\n$t_n$的密度函數與標準正態分佈$N(0,1)$密度很相似,他們都是關於原點對稱,單峰的偶函數,在$x=0$處達到極大,但$t_n$的峰值低於$N(0,1)$的峰值,$t_n$的密度函數圍捕都要比$N(0,1)$的兩側尾部促一些。容易證明:$\\lim_{n\\rightarrow \\infty}t_n(x) = \\varphi (x)$\n\n#### F 分佈\n在概率論和統計學中,F-分佈(F-Distribution)是一種連續概率分佈,被廣泛應用於死然比率檢驗。\n
\n\n設隨機變量$X~\\chi^2_m$,$Y~\\chi^2_n$,且$X$ 和 $Y$ 獨立,則稱:\n
\n
\n $F=\\frac{X/m}{Y/n}$\n
\n
\n\n為自由度分別為$m$和$n$的$F$變量,其分佈稱為自由度分別是$m$和$n$的F分佈,記做$F~F_{m,n}$
\n\n若隨機變量$Z~F_{m,n}$,則其密度函數為:\n
\n
\n $\\begin{equation}\nf_{m,n}(x) = \n\\left\\{\n \\begin{array}{lr}\n \\frac{\\Gamma(\\frac{m+n}{2}\\Gamma(\\frac{n}{2})\\Gamma(\\frac{m}{2})}m^{\\frac{m}{2}} n^{\\frac{n}{2}} x {\\frac{m}{2} - 1}(n+mx)^{-\\frac{m+n}{2}}, \\ & x>0 \\\\ \n 0 \\ \\ & elsewhere\n \\end{array}\n\\right.\n\\end{equation}$\n
\n
\n\n\n\n\n```python\ndef diff_f_dis():\n \"\"\"\n 不同参数下的F分布\n :return:\n \"\"\"\n# f_dis_0_5 = stats.f(dfn=10, dfd=1)\n f_dis_1_30 = stats.f(dfn=1, dfd=30)\n f_dis_30_5 = stats.f(dfn=30, dfd=5)\n f_dis_30_30 = stats.f(dfn=30, dfd=30)\n f_dis_30_100 = stats.f(dfn=30, dfd=100)\n f_dis_100_100 = stats.f(dfn=100, dfd=100)\n\n# x1 = np.linspace(f_dis_0_5.ppf(0.01), f_dis_0_5.ppf(0.99), 100)\n x2 = np.linspace(f_dis_1_30.ppf(0.2), f_dis_1_30.ppf(0.99), 100)\n x3 = np.linspace(f_dis_30_5.ppf(0.00001), f_dis_30_5.ppf(0.99), 100)\n x4 = np.linspace(f_dis_30_30.ppf(0.00001), f_dis_30_30.ppf(0.999), 100)\n x6 = np.linspace(f_dis_30_100.ppf(0.0001), f_dis_30_100.ppf(0.999), 100)\n x5 = np.linspace(f_dis_100_100.ppf(0.0001), f_dis_100_100.ppf(0.9999), 100)\n fig, ax = plt.subplots(1, 1, figsize=(20, 10))\n# ax.plot(x1, f_dis_0_5.pdf(x1), 'b-', lw=2, label=r'F(0.5, 0.5)')\n ax.plot(x2, f_dis_1_30.pdf(x2), 'g-', lw=2, label='F(1, 30)')\n ax.plot(x3, f_dis_30_5.pdf(x3), 'r-', lw=2, label='F(30, 5)')\n ax.plot(x4, f_dis_30_30.pdf(x4), 'm-', lw=2, label='F(30, 30)')\n ax.plot(x6, f_dis_30_100.pdf(x6), 'c-', lw=2, label='F(30, 100)')\n ax.plot(x5, f_dis_100_100.pdf(x5), 'y-', lw=2, label='F(100, 100)')\n\n plt.ylabel('Probability')\n plt.title(r'PDF of f Distribution')\n ax.legend(loc='best', frameon=False)\n plt.savefig('f_diff_pdf.png', dip=500)\n plt.show()\n\ndiff_f_dis()\n```\n\nF 變量具有如下**性質**:\n1. 若$Z~F_{m,n}$,則$1/Z~F_{n,m}$
\n2. 若$T~t_n$,則$T^2~F_{1,n}$
\n3. $F_{m,n}(1-\\alpha) = 1/F_{n,m}(\\alpha)$\n\n### 正態總體樣本均值和樣本方差的分佈\n\n為了方便討論正態總題樣本均值和樣本方差的分佈,我們先給出正態隨機變量的線性函數的分佈。\n
\n\n#### 正態變量線性函數的分佈\n\n設隨機變量$X_1,\\dots,X_n \\ i.i.d.~N(a,\\sigma^2), c_1,c_2,\\dots,c_n$為常數,則有\n
\n
\n $T = \\displaystyle \\sum^n_{k=1}c_k X_k ~N(a \\sum^n_{k=1}c_k, simga^2\\sum^n_{k=1}c_k^2)$\n
\n
\n\n特別的,當$c_1 = \\dots = c_n = \\frac{1}{n}$,即:$T = \\frac{1}{n} \\displaystyle \\sum^n_{i=1}X_i = \\bar{X}$時,有\n
\n
\n $\\bar{X}~N(a,\\sigma^2/n)$\n
\n
\n\n#### 正態分佈樣本均值和樣本方差的分佈\n\n設$X_1,\\dots,X_n \\ i.i.d.~N(\\mu,\\sigma^2),\\bar{X} = \\frac{1}{n} \\displaystyle \\sum^n_{i=1}X_i$ 和 樣本方差,則有
\n1. $\\bar{X}~N(a,\\frac{1}{n}\\sigma^2)$;\n2. $(n-1)S^2/sigma^2~\\chi^2_{n-1}$;\n3. $\\bar{X}$和$S^2$獨立.\n\n### 正態分佈(Normal Distribution)\n\n在生活中,我們經常會用到正態分佈,這是一個墳場常見的連續概率分佈(Continuous probability distribution),這是因為 CLT 的存在(Central Limited Theorem)。\n\n#### 定義\n如果一個隨機變量(Random Variable) $X$ 服從一個位置參數為$\\mu$, 尺度參數為 $\\sigma$ 的正態分佈,那麼我們記做:\n\n$$ X \\sim N(\\mu, \\sigma^2)$$\n\n她的概率密度函數(PDF:Probability Density Function):\n\n$$f(x) = \\frac{1}{\\sigma^2 \\sqrt{2\\pi}} e^ {-\\frac{(x - \\mu)^2}{2\\sigma^2}}$$\n\n在正態分佈中,她的 expectation 等於她的位置參數,決定了分佈曲線的中心位置;其方差 $\\sigma^2$ 則決定了尺度、決定了分佈的幅度:「高矮胖瘦」\n常態分布的機率密度函數曲線呈鐘形,因此人們又經常稱之為鐘形曲線(类似于寺庙里的大钟,因此得名)。我們通常所說的標準常態分布是位置參數\n$\\mu =0$,尺度參數 $\\sigma^2 = 1$的正態分佈。\n\n\n```python\nimport scipy.stats as stats\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nfig, ax = plt.subplots(1, 1)\nx = np.linspace(-5,5)\ny_1 = stats.norm.pdf(x, loc = 0, scale = 1) #loc \ny_2 = stats.norm.pdf(x, loc = 3, scale = 1)\ny_3 = stats.norm.pdf(x, loc = 0, scale = 3)\nax.plot(x,y_1,'-',label='pdf of norm,\\n mu = 0, sd = 1 ')\nax.plot(x,y_2,'-',label='pdf of norm,\\n mu = 3, sd = 1 ')\nax.plot(x,y_3,'-',label='pdf of norm,\\n mu = 0, sd = 3 ')\nax.legend(loc='best',frameon=True)\n\nplt.title(r'Normal Distribution')\n\n\nplt.show()\n```\n\n我們需要證明 $n(x;\\mu,\\sigma)$ 的確是一個分佈密度:\n* 需要證明$n(x;\\mu,\\sigma) > 0$ 對 $\\forall x \\in (-\\infty,+\\infty)$ 成立\n* 求積分:$\\displaystyle \\int_{-\\infty}^{+\\infty} n(x;\\mu, \\sigma)\\ dx = \\frac{1}{\\sqrt{2\\pi}\\sigma} \\int_{-\\infty}^{+\\infty} exp\\left[-\\frac{1}{2\\sigma^2} (x - \\mu)^2\\right] dx$\n\n\n*這裡,證明過程詳見(方開泰教授)《統計分佈》p102 - 103*\n\n#### 性質\n\n正態分佈有許多非常好的性質,這裡僅列出一些基本的性質:\n\n##### 性質一:\n* $n(x;\\mu, \\sigma)$ 的圖形如上所示,它很像一個鐘,它是一個單峰分佈(Unimodal Distribution),峰值在 $x = \\mu$, 這是因為 $e^{-x^2}$ 在 $x = 0$ 是達到最大,所以,$n(x;\\mu, \\sigma)$ 在 $ x = \\mu$ 處達到最大值,從而她的眾數:$\\mu$;\n* 圖形關於 $x = \\mu$ 對稱;\n* $y = 0$ 是 $f(x) / p(x)$ 的漸近線(Asymptote);\n\n#### 性質二: 歸一化(Normallization)\n\n**若 $X \\sim N(\\mu, \\sigma^2)$, 則 $Z = (X - \\mu)/\\sigma \\sim N(0,1)$. 反之,如果 $Z \\sim N(0,1),則 X = \\mu + \\sigma Z \\sim N(\\mu, \\sigma^2)$**\n\n**證明**:若 $X \\sim N(\\mu, \\sigma^2)$, 則對一切 $a < b$有: \n\n$\\begin{align*}\n P(a < Z < b) &= P(a < \\frac{X - \\mu}{\\sigma} < b) \\\\ \n &= P(\\mu + \\sigma a < X < \\mu + \\sigma b) \\\\\n &= \\int_{\\mu + \\sigma a}^{\\mu + \\sigma b} \\frac{1}{\\sqrt{2 \\pi}\\sigma} exp\\left[-\\frac{1}{2\\sigma^2}(x - \\mu)^2\\right] \\ dx \\text{Let $t = \\frac{x - \\mu}{\\sigma}$} \\\\\n &= \\int_{a}^{b} \\frac{1}{\\sqrt{2\\pi}}exp\\left[-\\frac{1}{2}t^2\\right] dt\\\\\n \\end{align*}$\n\n這表明了 $Z \\sim N(0,1)$, 其逆命題的證明正好是上面推倒的逆序。\n\n$\\Phi = (x;0,1) \\ Z ~ N(\\frac{x - \\mu}{\\sigma}; 0,1)$ \n\n歸一化的好處是我們只需要研究$\\Phi(x)$ 就足夠了,$\\Phi(x)$有如下性質:\n* $\\Phi(0) = \\frac{1}{2}, \\Phi(x)$ 有兩條漸近線 $y = 0$ 和 $y = 1$. 從而, $\\Phi(x)$ 的中位數是 $x = 0$\n* $\\Phi(-x) = 1 - \\Phi(x)$ \n\n##### 性質三:可加性 (additivity)\n**若$X_1 \\sim N(\\mu_1, \\sigma_1^2)$ 與 $x_2 \\sim N(\\mu_2, \\sigma_2^2)$獨立,則**:\n$$X_1 + X_2 \\sim N(\\mu_1 + \\mu_2, \\sigma_1^2 + \\sigma_2^2)$$\n\n這個性質可以推廣到多個隨機變量的情況:\n\n$X = \\{X_1, X_2, X_3, \\dots, X_n\\}$, 則,$\\bar{X} = \\frac{1}{n}(X_1 + \\dots + X_n)$,對於每一個隨機變量:$X_i \\sim N(\\mu_i, \\sigma_i^2)$,則: \n$$\\bar{X} = \\frac{1}{n}(X_1 + \\dots + X_n) \\sim N(\\mu, \\frac{\\sigma^2}{n})$$\n\n### 對數正態分佈(logrithm-Normal Distribution)\n**對數正態分佈**是對數為正態分佈的任意隨機變量的概率分佈;在地址勘探中,岩石的某種化學成分(用$X$表示),它的對數服從正態分佈,所以得名對數正態分佈。\n\n#### 定義\n設$X$是取值為正數的隨機變量,若$log(X) \\sim N(\\mu, \\sigma^2)$,則稱$X$服從對數正態分佈,並記作:$X \\sim LN(\\mu, \\sigma^2)$\n
\n*這裡的對數是以自然對數$e$為底的,一般記作 $ln$*\n\n\n\n```python\nfrom scipy.stats import lognorm\nimport numpy as np\nimport matplotlib.pyplot as plot\n\nfig, ax = plt.subplots(1, 1)\ns = 1\nmean, var, skew, kurt = lognorm.stats(s, moments='mvsk')\nx = np.linspace(lognorm.ppf(0.01, s),\n lognorm.ppf(0.99, s), 100)\nax.plot(x, lognorm.pdf(x, s),\n 'r-', lw=5, alpha=0.6, label='lognorm pdf')\nrv = lognorm(s)\nax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')\nvals = lognorm.ppf([0.001, 0.5, 0.999], s)\nnp.allclose([0.001, 0.5, 0.999], lognorm.cdf(vals, s))\nr = lognorm.rvs(s, size=1000)\nax.hist(r, density=True, histtype='stepfilled', alpha=0.2)\nax.legend(loc='best', frameon=False)\nplt.show()\n```\n\n$\\begin{equation}\nf_X(x) = \\left\\{\n \\begin{array}{lr}\n \\frac{1}{\\sqrt{2\\pi}\\sigma x} exp\\left[-\\frac{1}{2\\sigma^2}(ln(x) - \\mu)^2\\right] \\ \\ &\\text{if $x > 0$}\\\\\n 0 \\ \\ &\\text{if $x \\leq 0$} \\\\\n \\end{array}\n\\right.\n\\end{equation}$\n\n\n#### 性質\n為了方便討論,我們就用 $ln(x;\\mu,\\sigma^2)$ 表示上式子。\n\n*因為$X$取了自然對數後,自然的,不再是對稱的了,圖如上*\n\n##### 性質一\n由上面的PDF可以看出,在$ln(x) = \\mu$或者$x = e^{\\mu}$時,取得極大值,即分佈的眾數為$e^{\\mu}$\n\n##### 性質二\n跟正態分佈同樣的是,對數正態分佈也具有可加性.\n\n\n#### 例題:\n若一直某種花崗岩中的$Fe_2O_3$(三氧化二鐵)的含量服從對數分佈:$LN(\\mu, \\sigma^2)$今天從岩石樣本中測的$Fe_2O_3$的含量分別為:\n\n$$5.98, 3.13, 6.75, 4.60, 10.31, 4.78, 6.15, 3.09, 0.84, 1.07$$\n\n希望知道$Fe_2O_3$的含量落在$(3,9)$的概率。\n\n解題:\n若$X\\sim LN(\\mu, \\sigma^2)$,則 $Y = ln(X) \\sim N(\\mu,\\sigma^2)$,可以用正態分佈來估計$\\mu,\\sigma^2$:\n$$ Y = [1.78842057, 1.141033, 1.9095425, 1.5260563, 2.3331143, 1.56444055, \n 1.81645208, 1.12817109, -0.17435339, 0.06765865]$$\n\n$\\mu = \\bar{Y} = 1.310, \\ \\ \\hat{\\sigma^2} = 0.646, \\ \\ \\hat{\\sigma^2} = 0.804$\n\n\n\n```python\nfrom math import log\nx = np.array([5.98, 3.13, 6.75, 4.60, 10.31, 4.78, 6.15, 3.09, 0.84, 1.07], dtype=np.float32)\nlog_x = np.log(x)\nmean = np.mean(log_x)\nvar = np.var(log_x, ddof = 1)\nsd = np.std(log_x, ddof = 1)\nprint(log_x,'\\n',mean,'\\n',sd)\n# ddof means delta degree of freedom\n```\n\n [ 1.7884206 1.141033 1.9095426 1.5260563 2.3331144 1.5644406\n 1.8164521 1.1281711 -0.17435342 0.0676587 ] \n 1.3100536 \n 0.8035576\n\n\n\n```python\nfrom math import exp\nfrom scipy import stats\n\ndef lognorm_cdf(x, mu, sigma):\n shape = sigma\n loc = 0\n scale = exp(mu)\n return stats.lognorm.cdf(x, shape, loc, scale)\n\nx_1 = 3\nx_2 = 9\nmu = mean\nsigma = sd\np_1 = lognorm_cdf(x_1, mu, sigma) #yields the expected 0.74341\np_2 = lognorm_cdf(x_2, mu, sigma)\nprint(\"The probability that drop in 3 to 9 is\",format((p_2 - p_1) * 100, '.5g'),\"%\")\n```\n\n The probability that drop in 3 to 9 is 46.899 %\n\n\n## Discrete Distribution \n\n通常的,我們將隨機變量分為兩類:連續隨機變量和離散隨機變量,在這裏我們首先介紹由離散隨機變量構成的離散型分佈:兩點分佈、二項分佈、泊松分佈、超幾何分佈、幾何分佈、負二項分佈等等,我們將會介紹他們的基本性質。\n\n### 兩點分佈 (Bernoulli Distirubtion)\n\n也被稱為「伯努利分佈」或者「0-1分佈」。這個分佈是指:若「伯努利實驗」成功,則變量取值為$1$,反之,則記為$0$。所以我們將其成功的概率記為$p, \\ \\ p \\in (0,1)$,失敗的概率為$q = (1 - p)$。\n\n#### 伯努利實驗 (Bernoulli trail) \n這個實驗是指單詞實驗中,這個事件的結果是兩個可能性結果中的一個。這樣的事件都可以表達成「是」或者「否」(Yes or No): \n* 拋起一個硬幣,落下時是正面還是反面?\n* 生下一個孩子,是男孩還是女孩(不考慮特殊情況)?\n* etc.\n\n#### 性質\n\n任意的兩點分佈,均可以變換成如下標準概型:\n\n$\\begin{align*}\n \\begin{pmatrix}\n 0 & 1 \\\\\n q & p \n \\end{pmatrix} \n , \\ \n p + q = 1 \n \\end{align*}$\n\n* 其概率質量函數(probability mass function)為:\n $$ f_X(x) = p^x(1-p)^x $$\n* 其期望值(可以通過原始矩(moments)進行證明)為:\n $$\\displaystyle E(X) = \\sum_{i = 0}^1 x_i f_X(x) = 0 + p = p$$ \n* 其方差值(同樣可以通過矩進行證明)為:\n $$\\displaystyle Var(X) = \\sum_{i = 0}^1 x_i - E(X)^2 f_X(x) = p \\times q = p \\times (p - 1)$$ \n\n### 二項分佈\n\n假設我們有五個小孩,根據遺傳學的研究發現生男孩的概率是$p = 0.5116$,我們需要猜測三男兩女的概率,這有幾種可能?**排列組合問題**:$\\binom{5}{3} p^3 (1-p)^2$,其中 $p$ 是生男孩的概率,$(1 - p)$就是生女孩的概率。\n\n一般的,若我們進行了$n$次獨立實驗,每次實驗只有兩個可能的結果(生男「事件:A」還是生女「事件:非A」),且$p = P(A), \\ q = P(A^C) $,$p + q = 1, \\ p \\in (0,1)$,用 $X$ 來表示這$n$次實驗中$A$發生的次數:\n\n$$P(X = m) = C^m_n p^m q^{n-m}, \\ \\ m = 0,1,\\dots,n,$$\n\n\n```python\nimport numpy as np\nfrom scipy.stats import binom\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 1)\nn, p = 5, 0.5116\nmean, var, skew, kurt = binom.stats(n, p, moments='mvsk')\nx = np.arange(binom.ppf(0.01, n, p),\n binom.ppf(0.99, n, p))\nax.plot(x, binom.pmf(x, n, p), 'bo', ms=8, label='binom pmf')\nax.vlines(x, 0, binom.pmf(x, n, p), colors='b', lw=5, alpha=0.5)\nrv = binom(n, p)\nax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,\n label='frozen pmf')\nax.legend(loc='best', frameon=False)\nplt.show()\n```\n\n\n```python\nimport numpy as np\nfrom scipy.stats import binom\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 1)\nn, p = 5, 0.5116\nx = np.arange(5)\ny = binom.pmf(x,n,p)\nax.plot(x,y,'bo')\nax.vlines(x, 0, binom.pmf(x, n, p), colors='b', lw=5, alpha=0.5)\nplt.show()\n```\n\n#### 性質\n\n為了方便討論,我們把二項分佈簡單的記做:$b(m;n,p)$ \n\n##### 性質一 \n$\\begin{align*}\n&b(m;n,p) > 0 , \\ \\ m = 0,1,\\dots, n: \\\\\n&\\sum_{m=0}^n b(m;n,p) = \\sum_{m=0}^n C^m_n p^m (1-p)^{n-m} = (p + q)^n = 1 \\\\\n\\end{align*}$\n\n#### 性質二\n\n若 $p = 0.5$,則二項分佈是對稱的;若$p \\neq 0.5$ 則不是對稱的,且$n$越大越明顯。下圖便是對比,三條線:「樣本量一樣,概率不同」做對比;「樣本量不同,概率相同」做對比。\n\n\n```python\nimport numpy as np\nfrom scipy.stats import binom\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 1)\n\nn , p = 10, 0.5\nn_1, p_1 = 5, 0.70\nn_2, p_2 = 10, 0.70\n\nx = np.arange(n + 1)\ny = binom.pmf(x,n,p)\nax.plot(x,y,'co', label = \"n = 10, p = 0.5\")\nax.vlines(x, 0, y, colors='c', lw=5, alpha=0.5)\n\nx_1 = np.arange(n_1 + 1)\ny_1 = binom.pmf(x_1,n_1,p_1)\nax.plot(x_1,y_1,'bo', label = \"n = 5, p = 0.70\")\nax.vlines(x_1, 0, y_1, colors='b', lw=5, alpha=0.5)\n\nx_2 = np.arange(n_2 + 1)\ny_2 = binom.pmf(x_2,n_2,p_2)\nax.plot(x_2,y_2,'ro', label = \"n = 10, p = 0.70\")\nax.vlines(x_2, 0, y_2, colors='r', lw=5, alpha=0.5)\n\nax.legend(loc='best', frameon=False)\nplt.show()\n```\n\n#### 性質三 \n二項分佈$b(m;n,p)$的均值、方差、便準差分別為:\n$$ \\left\\{\n\\begin{aligned}\nE(X) &=& np \\\\\nVar(X) &=& npq \\\\\nsd(X) &=& \\sqrt{npq} \\\\\n\\end{aligned}\n\\right.\n$$\n\n#### 性質四\n\n* 二項分佈可以用不完全$\\beta$函數(Normalized Beta Distribution) 來表示:在 Bayesian Inference 裡,$\\beta$函數可以作為二項分佈的unconjugated prior,這個會留在 Bayesian Analysis 裡講,敬請關注;\n* 二項分佈有一個近似計算的方法:(Stirling Formula) 當$m, n$和 $m - np$都比較大的時候,我們可以使用泊松分佈去估計二項分佈,具體證明詳見:《統計分佈》(方開泰,王元)p59 - 61\n\n### 泊松分佈(Poisson Distribution)\n\n泊松分佈適合於描述單位時間內隨機時間發生的次數的分佈。比如說:某交換台在一段時間內所接收到的呼喚次數、某個公交車站在一個固定時間內來到的乘客數量$\\dots$ \n\n泊松分佈的概率質量函數為:\n\n$$P(X = k) = \\frac{e^{-\\lambda}\\lambda^k}{k!}$$ \n\n泊松分佈的參數$\\lambda$是單位時間(或者單位面積)內隨機事件的平均發生率。\n\n#### 性質\n\n為了方便敘述,我們記做 $\\displaystyle p(k;\\lambda) = \\frac{e^\\lambda \\lambda^k}{k!}, \\ \\ P(x;\\lambda) = \\sum_{k=0}^{|x|}p(k;\\lambda), \\ k = 0,1,2,\\dots,n,$\n\n##### 性質一\n$\\begin{align*}\n&p(k; \\lambda) > 0 , \\ \\ k = 0,1,2, \\dots, \\\\ \n&\\sum_{k=0}^{\\infty} p(k;\\lambda) = e^{-\\lambda} \\sum_{k = 0}^{\\infty} \\frac{\\lambda^k}{k!} = e^{-\\lambda} e^{\\lambda} = 1\n\\end{align*}$\n\n##### 性質二\n\n當$k < \\lambda$時, $p(k, \\lambda) > p(k -1; \\lambda)$;$p(k, \\lambda) < p(k -1; \\lambda)$; 如果$\\lambda$ 不是整數,則$p(k;\\lambda)$,在 $k = [\\lambda] \\equiv k_0$處達到極大值,這裡$[\\lambda]$為不超過$\\lambda$的最大證書,如果$\\lambda$為整數,則$p(k;\\lambda)$在$k = \\lambda$在$k = \\lambda$及$ k = \\lambda - 1$處同時達到極大值。\n\n\n\n\n```python\nfrom scipy import stats\nmu, k = 2, 10\nx = np.arange(0, k + 1, 1)\n\npmf_poisson = stats.poisson.pmf(x, mu)\n\nplt.plot(x, pmf_poisson, 'bo')\nplt.vlines(x,0,pmf_poisson)\nplt.vlines(x, 0, pmf_poisson, colors='b', lw=5, alpha=0.5)\nplt.xlabel(\"there are 1000 accident\")\nplt.ylabel('probability')\nplt.title('poisson probability: mean = %i'%mu)\n\nplt.show()\n```\n\n#### 性質三\n\n泊松分佈是非對稱的,當$\\lambda$越來越大時非對稱性越明顯,是當$n$增大時,非對稱性也會太明顯。\n\n$\\begin{align*}\n E(X) &=& \\lambda \\\\\n Var(X) &=& \\lambda \\\\\n sd(X) &=& \\sqrt{\\lambda} \\\\\n\\end{align*}$\n\n\n```python\nfrom scipy import stats\nfig, ax = plt.subplots(1, 2)\nmu, k = 2, 5\nx = np.arange(0, k + 1, 1)\n\npmf_poisson = stats.poisson.pmf(x, mu)\n\nplt.subplot(221)\nplt.plot(x, pmf_poisson, 'bo')\nplt.vlines(x,0,pmf_poisson)\nplt.vlines(x, 0, pmf_poisson, colors='b', lw=5, alpha=0.5)\nplt.xlabel(\"there are 1000 accident\")\nplt.ylabel('probability')\nplt.title('poisson probability: mean = %i'%mu)\n\nplt.subplot(222)\nmu_1, k_1 = 10, 5\nx_1 = np.arange(0, k_1 + 1, 1)\n\npmf_poisson_1 = stats.poisson.pmf(x_1, mu_1)\n\nplt.plot(x_1, pmf_poisson_1, 'ro')\nplt.vlines(x_1,0, pmf_poisson_1)\nplt.vlines(x_1, 0, pmf_poisson_1, colors='r', lw=5, alpha=0.5)\nplt.xlabel(\"there are 1000 accident\")\nplt.ylabel('probability')\nplt.title('poisson probability: mean = %i'%mu_1)\n\nplt.show()\n```\n\n#### 性質四 \n\n* 若$X_1, \\dots, X_n$是獨立同分佈的隨機變量,則 $X_1\\sim P(\\lambda)$等價於 $\\sum_{i=1}^n X_i \\sim P(n\\lambda)$.\n* 設$X_1, \\dots, X_n$相互獨立,且$X_i \\sim P(\\lambda_i), i = 1,2,\\dots,n$, 則$\\sum_{i=1}^n X_i \\sim P(\\lambda)$,其中$\\lambda = \\lambda_1 + \\dots \\lambda_n$ \n\n### 超幾何分佈 (Hypergeometric Distirbution) \n\n**超幾何分佈**描述了由有限物件中抽出$n$個物件,成功抽出制定種類的物件的個數(不歸還(without replacement))。例如,在由$N$個紅球之中,其中有$K$個藍球。超幾何分佈描述了在$N$個樣本中抽出$n$個,其中$k$個是籃球的概率:\n\n$$f(k;n,K,N) = \\frac{\\binom{K}{k} \\binom{N - K}{n - k}}{\\binom{N}{n}}$$\n\n其實,很容易看出這氣勢就是一個「排列」問題:從$N$個紅球中抽出$k$個籃球的可能性有$\\binom{k}{K}$種,$(n - k)$件紅球從$N - K$個紅球中抽取的一切可能性是$\\binom{n - k}{N - K}$種, 所抽出的$n$個球中出現的次序總共有$n!$種可能的排列,於是所求的概率為:\n\n$$P(X = k) = \\frac{\\binom{K}{k} \\binom{N - K}{n - k}}{\\binom{N}{n}}$$\n\n所以,我們可以給出一個新定義:若隨機變量$X$的取值是閉區間:$[max(0, M + n - N), min(M,n)]$內的一切整數, 且$X = k$的概率應該是P(X = k)$,則響應的分佈叫做超幾何分佈,記做$X\\sim H(M, N, n)$. \n\n\n```python\nfrom scipy.stats import hypergeom\nimport matplotlib.pyplot as plt\n\n[M, n, N] = [20, 7, 12]\nrv = hypergeom(M, n, N)\nx = np.arange(0, n+1)\npmf_dogs = rv.pmf(x)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x, pmf_dogs, 'bo')\nax.vlines(x, 0, pmf_dogs, lw=2)\nax.set_xlabel('# of dogs in our group of chosen animals')\nax.set_ylabel('hypergeom PMF')\nplt.show()\n```\n\n### 負二項分佈 (Negative Binormial Distribution)\n\n負二項分佈描述在一系列獨立筒分佈的伯努利實驗中,失敗次數達到指定次數(記為$r$)時臣工次數的離散概率分佈。比如,如果我們定義擲骰子隨機變量$x$值為$x = 1$時為失敗,所以$x \\neq 1$為成功,這時我們反覆擲骰子知道$1$出現三次,此時非$1$數字出現的概率分佈為負二項分佈。\n\n負二項分佈也被稱為帕斯卡分佈(Pascal Distribution),時幾何分佈的直接推廣,正如幾何分佈可以用伯努利實驗來定義一樣,負二項分佈也可用伯努利實驗來定義。\n\n顯然,事件$X = k$等價於“第$k$次試驗出現成功,前面$k - 1$實驗中成功“$r - 1$次”故:\n\n$$P(X = k) = p C_{k - 1}^{r - 1} p^{r - 1} q^{k-r} = C_{k - 1}^{r - 1} p^rq^{k - r}, \\ \\ k = r, r + 1, \\dots$$\n\n令$Y= X - r$, 則$Y$的分佈的: \n\n$$P(Y = k) = P(X = k + r) = C_{k + r - 1}^k p^r q^k, \\ \\ k = 0,1, \\dots$$\n\n通常我們稱它為「等待時間分佈」, 記做$Y \\sim NB(r, p)$\n", "meta": {"hexsha": "4707b548f0c404f513217006dca5c2bcc696e330", "size": 714586, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "jupyterfiles/Use PY in Advanced Statistics .ipynb", "max_stars_repo_name": "ecwu/Using-Python-Series", "max_stars_repo_head_hexsha": "e6408f92516a7146d572b1d95403ec0c1c90097d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2020-01-04T09:17:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:52:44.000Z", "max_issues_repo_path": "jupyterfiles/Use PY in Advanced Statistics .ipynb", "max_issues_repo_name": "ecwu/Using-Python-Series", "max_issues_repo_head_hexsha": "e6408f92516a7146d572b1d95403ec0c1c90097d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-11-25T09:15:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-25T09:15:17.000Z", "max_forks_repo_path": "jupyterfiles/Use PY in Advanced Statistics .ipynb", "max_forks_repo_name": "ecwu/Using-Python-Series", "max_forks_repo_head_hexsha": "e6408f92516a7146d572b1d95403ec0c1c90097d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2020-02-23T16:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T07:23:12.000Z", "avg_line_length": 224.1486825596, "max_line_length": 68596, "alphanum_fraction": 0.9047000641, "converted": true, "num_tokens": 38033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.3462784684960046}} {"text": "```python\n%%capture\n## compile PyRoss for this notebook\nimport os\nowd = os.getcwd()\nos.chdir('../../')\n%run setup.py install\nos.chdir(owd)\n%matplotlib inline\n```\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyross\n```\n\nIn this notebook we consider a control protocol consisting of an initial lockdown, which is then partly released. For our numerical study we generate synthetic data using the deterministic SEkIkIkR model.\n\nWhile we use the UK age structure and contact matrix, we emphasise that **the model parameters considered in this notebook have NOT been obtained from real data, but rather are chosen ad-hoc**.\n\n**Outline of this notebook:**\n\n1. We briefly summarize the SEkIkIkR model (still to do).\n2. We load the age structure and contact matrix for UK. The contact matrix is generally given as\n\\begin{equation}\n C = C_{H} + C_{W} + C_{S} + C_{O},\n\\end{equation}\nwhere the four terms denote the number of contacts at home, work, school, and all other remaining contacts.\n3. We define the other model parameters of the SEkIkIkR model **(again, these are not fitted to any real data, but rather chosen ad-hoc)**.\n4. We define a \"lockdown-protocol\":\n 1. After a fixed time, a lockdown is imposed. The contact matrix is reduced to \n \\begin{equation}\n C = C_{H} + 0.1\\cdot C_W + 0.4 \\cdot C_O,\n \\end{equation}\n i.e. the \"home\" contacts $C_H$, and 10% of the \"work\" as well as 40% of the \"other\" contacts are reainted. The latter two model that even in lockdown, people go to work, and that initially people might be lenient in following the lockdown advice.\n 2. 5 Days after the initial lockdown, the 40% \"social interaction\" part of the contact matrix is removed, and the contact matrix becomes\n \\begin{equation}\n C = C_{H} + 0.1\\cdot C_W.\n \\end{equation}\n This models that people take the lockdown seriously and seize to interact socially.\n 3. 50 Days after the initial lockdown, 50% of the \"school\" contacts are added to the contact matrix,\n \\begin{equation}\n C = C_{H} + 0.1\\cdot C_W + 0.5 \\cdot C_S.\n \\end{equation}\n This models an opening of schools, with a social distancing protocol in place such that the number of contacts at school is halved.\n5. We run a deterministic simulation of this lockdown protocol, and find that in Stage 2 (only home and 10% of work contacts), the total number of known active infectives (the sum of the stages symptomatic infective, hospitalised, and in ICU) shows a maximum and then decreases. After schools are opened, the total number of known active infectives continues to decrease.\n6. Finally, we consider the protocol from point 4 again, but this time with a prefactor 0.7 in front of $C_S$, signifying a more strict social distancing protocol. Running a deterministic simulation with this protocol, we find that this time the total number of active infectives starts to increase again after schools have been reopened.\n\n## 2. Load UKage structure and contact matrix\n\n\n```python\nmy_data = np.genfromtxt('../data/age_structures/UK.csv', delimiter=',', skip_header=1)\naM, aF = my_data[:, 1], my_data[:, 2]\n\nNi0=aM+aF;\n\nM=16 ## number of age classes\n\nNi = Ni0[:M]\nN=np.sum(Ni)\n\nprint(\"Age groups are in brackets of 5 (i.e. 0-4, 5-9, 10-14, .. , 75-79).\")\nprint(\"Number of individuals in each bracket:\")\nprint(Ni.astype('int'))\nprint(\"Total number of individuals: {0}\".format(np.sum(Ni.astype('int'))))\n```\n\n Age groups are in brackets of 5 (i.e. 0-4, 5-9, 10-14, .. , 75-79).\n Number of individuals in each bracket:\n [3951046 4114237 3884626 3684534 4120269 4510345 4683636 4519933 4270785\n 4353894 4674918 4463447 3799485 3406990 3329496 2343961]\n Total number of individuals: 64111602\n\n\n\n```python\n# Get individual contact matrices\nCH, CW, CS, CO = pyross.contactMatrix.UK()\n\n# By default, home, work, school, and others contribute to the contact matrix\nC = CH + CW + CS + CO\n\n# Illustrate the individual contact matrices:\nfig,aCF = plt.subplots(2,2);\naCF[0][0].pcolor(CH, cmap=plt.cm.get_cmap('GnBu', 10));\naCF[0][1].pcolor(CW, cmap=plt.cm.get_cmap('GnBu', 10));\naCF[1][0].pcolor(CS, cmap=plt.cm.get_cmap('GnBu', 10));\naCF[1][1].pcolor(CO, cmap=plt.cm.get_cmap('GnBu', 10));\n```\n\nThe above contact matrices illustrate the interactions at home (upper left), work (upper right), school (lower left), and the other remaining contacts (lower right). x- and y- axes denote the age groups, a darker color indicates more interaction.\n\n## 3. Define model parameters\n\n**Note: These have not been fitted to real data.**\n\n\n```python\nalpha=0.3 # fraction of symptomatics who self-isolate\nbeta = 0.0165 # probability of infection on contact \ngE = 1/2.72 # removal rate of exposeds\nkI = 4; # # of stages of I class\nkE = 4; # # of stages of E class \ngIa = 1./7 # removal rate of infectives \ngIs = 1./17.76\nfsa = 0.8\n\nS0 = np.zeros(M) \nI0 = np.zeros((kI,M));\nE0 = np.zeros((kE,M));\nfor i in range(kI):\n I0[i, 6:13]=10; I0[i, 2:6]=10\nfor i in range(kE):\n E0[i, 0:16]=10\nfor i in range(M) :\n S0[i] = Ni[i] - np.sum(I0[:,i]) - np.sum(E0[:,i])\nI0 = np.reshape(I0, kI*M)/kI;\nE0 = np.reshape(E0, kE*M)/kE;\n```\n\n## 4. Define events for protocol\n\n\n```python\n# Dummy event for initial (standard) contact matrix\nevents = [lambda t: 1]\ncontactMatrices = [C]\n\n# After 20 days, start lockdown\nlockdown_threshold_0 = 40\ndef event0(t,rp):\n return t - lockdown_threshold_0\nevents.append(event0)\ncontactMatrices.append( CH + 0.1*CW + 0.4*CO )\n\n# After 25 days, decrease contacts even further\nlockdown_threshold_1 = 45\ndef event1(t,rp):\n return t- lockdown_threshold_1\nevents.append(event1)\ncontactMatrices.append( CH + 0.1*CW)\n\n# After 70 days, add 50% of school contacts to contact matrix\nlockdown_threshold_2 = 90\ndef event2(t,rp):\n return t - lockdown_threshold_2\nevents.append(event2)\ncontactMatrices.append( CH + 0.1*CW + 0.5*CS ) # everybody in lockdown\n```\n\n## 5. Simulate protocol and analyse results\n\n#### Initialise pyross.control, run and plot a single test simulation\n\n\n```python\n# duration of simulation\nTf=500; Nf=Tf+1; \n\n# intantiate model\nparameters = {'beta':beta, 'gE':gE, 'gIa':gIa, 'gIs':gIs, \n 'kI':kI, 'kE' : kE, 'fsa':fsa, 'alpha':alpha}\nmodel = pyross.control.SEkIkIkR(parameters, M, Ni)\n\n# run model once\ndata=model.simulate(S0, E0, 0*I0, I0,\n events,contactMatrices, Tf, Nf)\n```\n\n\n```python\n# Plot result\n\nt = data['t']; \n\n# get total population in classes\n# - symptomatic infective,\n# - hospitalised,\n# - in ICU\n#y_plot = np.sum ( data['X'][:,4*M:7*M], axis = -1)\nIs = model.Is(data)\ny_plot = np.sum(Is,axis=-1)\n\nlw=2\nfig,ax = plt.subplots(1,1,figsize=(8,5))\nax.plot(t,y_plot,lw=lw,)\nax.axvline(data['events_occured'][0][0],\n color='crimson',lw=lw,\n label='Beginning of lockdown',ls='--')\nax.axvline(data['events_occured'][-1][0],\n color='limegreen',lw=lw,\n label='Schools re-opened',ls='--')\nax.set_xlim(0,Tf)\nfs=20\nax.legend(loc='best',fontsize=fs,framealpha=1)\nax.set_xlabel('time since first infection [days]',fontsize=fs)\nax.set_ylabel('Number of known active cases',fontsize=fs)\nplt.show()\nplt.close()\n```\n\n#### Run 50 simulations with protocol, then\n\n* plot trajectories,\n* plot mean trajectory + standard deviation,\n* plot distribution of delay between interventions (lockdown, re-opening of schools) until subsequent maximum/minimum.\n\n\n```python\n# Run 50 simulations with this protocol\nN_simulations = 1\n\ndata_results = np.zeros([N_simulations,Nf,(1+2*kI+kE)*M],\n dtype=int)\nfor i in range(N_simulations):\n print('Running simulation {0} of {1}'.format(i+1,N_simulations),end='\\r')\n data=model.simulate(S0, E0, 0*I0, I0,\n events,contactMatrices, Tf, Nf)\n data_results[i] = data['X']\n```\n\n Running simulation 1 of 1\r\n\n\n```python\n# Plot result\n\nt = data['t']; \nfig,ax = plt.subplots(1,1,figsize=(8,5))\nfor i,e in enumerate(data_results):\n # get total population in classes\n # - symptomatic infective,\n # - hospitalised,\n # - in ICU\n y_plot = np.sum ( e[:,(1+kE+kI)*M:(1+kE+2*kI)*M], axis = -1)\n ax.plot(t,y_plot,lw=3) #lw=0.5,)\nax.axvline(data['events_occured'][0][0],\n color='crimson',lw=lw,\n label='Beginning of lockdown',ls='--')\nax.axvline(data['events_occured'][-1][0],\n color='limegreen',lw=lw,\n label='Schools re-opened',ls='--')\nax.set_xlim(0,Tf)\nfs=20\nax.legend(loc='best',fontsize=fs,framealpha=1)\nax.set_xlabel('time since first infection [days]',fontsize=fs)\nax.set_ylabel('Number of known active cases',fontsize=fs)\nplt.show()\nplt.close()\n```\n\n#### Mean and standard deviation\n\n\n```python\n'''\n# For all simulations, plot total population in classes\n# - symptomatic infective,\n# - hospitalised,\n# - in ICU\n\n# mean and standard deviation of trajectories at every time\ny_mean = np.mean( ( np.sum(data_results[:,:,4*M:7*M], axis = -1) ), axis=0)\ny_std = np.std ( np.sum( data_results[:,:,4*M:7*M], axis = -1), axis =0)\n\nt = data['t']; \nfig,ax = plt.subplots(1,1,figsize=(8,5)) \nax.fill_between(t,y_mean - y_std,y_mean+y_std,\n label='Standard deviation',\n color='grey',alpha=0.4)\nax.plot(t,y_mean,\n label='Mean',\n color='black',alpha=1) \nax.axvline(data['events_occured'][0][0],\n color='crimson',lw=lw,\n label='Beginning of lockdown',ls='--')\nax.axvline(data['events_occured'][-1][0],\n color='limegreen',lw=lw,\n label='Schools re-opened',ls='--')\nax.set_xlim(0,Tf)\nfs=20\nax.legend(loc='upper left',fontsize=17,framealpha=1)\nax.set_xlabel('time since first infection [days]',fontsize=fs)\nax.set_ylabel('Number of known active cases',fontsize=fs)\nplt.show()\nplt.close()\n''';\n```\n\n#### Plot distributions for both \n\n* time from beginning of lockdown to subsequent peak, and\n* time from opening of schools to subsequent minimum.\n\n\n```python\n'''\n# calculate time from lockdown to local maximum for each trajectory\nmask = (t > lockdown_threshold_0)*(t < lockdown_threshold_2)\nt_mask = t[(mask)]\ndurations_from_lockdown_to_local_maximum = np.zeros(N_simulations,\n dtype=float)\nfor i,e in enumerate(data_results):\n y_plot = np.sum ( e[:,4*M:7*M], axis = -1)\n index = np.argmax( y_plot[(mask)])\n durations_from_lockdown_to_local_maximum[i] = t_mask[index] - lockdown_threshold_0\nprint('Mean time from beginning of lockdown to subsequent peak = {0:3.1f} days'.format(np.mean(durations_from_lockdown_to_local_maximum)))\n\n\nhist, bin_edges = np.histogram(durations_from_lockdown_to_local_maximum,10 ,density=True)\nbin_centers = (bin_edges[1:] + bin_edges[:-1])/2.\nbin_widths = bin_edges[1]-bin_edges[0]\nfig, ax =plt.subplots(1,1,figsize=(10,6))\nax.axvline(np.mean(durations_from_lockdown_to_local_maximum),ls='--',color='black',\n label='Mean')\nax.bar(bin_centers,hist,bin_widths,color='dodgerblue',\n label='Distribution',alpha=0.7)\nax.set_xlabel('Time from beginning of lockdown until subsequent peak [days]',fontsize=fs)\nax.set_ylabel('Probability',fontsize=fs)\nax.legend(loc='best',fontsize=fs)\nplt.show()\nplt.close()\n\n\n\n\n\n# calculate time from opening of schools to local minimum for each trajectory\n# (recall lockdown_threshold_2 = time at which schools are opened)\nmask = (t > lockdown_threshold_2)*(t < Tf)\nt_mask = t[(mask)]\ndurations_from_school_opening_to_local_minimum = np.zeros(N_simulations,\n dtype=float)\nfor i,e in enumerate(data_results):\n y_plot = np.sum ( e[:,4*M:7*M], axis = -1)\n index = np.argmin( y_plot[(mask)])\n durations_from_school_opening_to_local_minimum[i] = t_mask[index] - lockdown_threshold_2\nprint('Mean time from opening of schools to subsequent minimum = {0:3.1f} days'.format(np.mean(durations_from_school_opening_to_local_minimum)))\n\n\nhist, bin_edges = np.histogram(durations_from_school_opening_to_local_minimum,10 ,density=True)\nbin_centers = (bin_edges[1:] + bin_edges[:-1])/2.\nbin_widths = bin_edges[1]-bin_edges[0]\nfig, ax =plt.subplots(1,1,figsize=(10,6))\nax.axvline(np.mean(durations_from_school_opening_to_local_minimum),ls='--',color='black',\n label='Mean')\nax.bar(bin_centers,hist,bin_widths,color='dodgerblue',\n label='Distribution',alpha=0.7)\nax.set_xlabel('Time from school re-opening until subsequent minimum [days]',fontsize=fs)\nax.set_ylabel('Probability',fontsize=fs)\nax.legend(loc='best',fontsize=fs)\nplt.show()\nplt.close()\n''';\n```\n\n## 6. Redo simulations and analysis of point 5, but with more social distancing at school\n\n\n```python\n# we modify only the last contact matrix of the previous protocol:\ncontactMatrices[-1] = CH + 0.1*CW + 0.7*CS\n```\n\n\n```python\n# Run 50 simulations with this protocol\nN_simulations = 1\n\ndata_results2 = np.zeros([N_simulations,Nf,(1+kE+2*kI)*M],\n dtype=int)\nfor i in range(N_simulations):\n print('Running simulation {0} of {1}'.format(i+1,N_simulations),end='\\r')\n data=model.simulate(S0, E0, 0*I0, I0,\n events,contactMatrices, Tf, Nf)\n data_results2[i] = data['X']\n```\n\n Running simulation 1 of 1\r\n\n\n```python\n# Plot results\n\nprint(\"Simulated trajectories:\")\nt = data['t']; \nfig,ax = plt.subplots(1,1,figsize=(8,5))\nfor i,e in enumerate(data_results2):\n # get total population in classes\n # - symptomatic infective,\n # - hospitalised,\n # - in ICU\n y_plot = np.sum ( e[:,(1+kE+kI)*M:(1+kE+2*kI)*M], axis = -1)\n ax.plot(t,y_plot,lw=3) #lw=0.5,)\nax.axvline(data['events_occured'][0][0],\n color='crimson',lw=lw,\n label='Beginning of lockdown',ls='--')\nax.axvline(data['events_occured'][-1][0],\n color='limegreen',lw=lw,\n label='Schools re-opened',ls='--')\nax.set_xlim(0,Tf)\nfs=20\nax.legend(loc='best',fontsize=15,framealpha=1)\nax.set_xlabel('time since first infection [days]',fontsize=fs)\nax.set_ylabel('Number of known active cases',fontsize=fs)\nplt.show()\nplt.close()\n\n'''\nprint(\"Mean trajectory and standard deviation:\")\n# mean and standard deviation of trajectories at every time\ny_mean = np.mean( ( np.sum(data_results2[:,:,4*M:7*M], axis = -1) ), axis=0)\ny_std = np.std ( np.sum( data_results2[:,:,4*M:7*M], axis = -1), axis =0)\nt = data['t']; \nfig,ax = plt.subplots(1,1,figsize=(8,5)) \nax.fill_between(t,y_mean - y_std,y_mean+y_std,\n label='Standard deviation',\n color='grey',alpha=0.4)\nax.plot(t,y_mean,\n label='Mean',\n color='black',alpha=1) \nax.axvline(data['events_occured'][0][0],\n color='crimson',lw=lw,\n label='Beginning of lockdown',ls='--')\nax.axvline(data['events_occured'][-1][0],\n color='limegreen',lw=lw,\n label='Schools re-opened',ls='--')\nax.set_xlim(0,Tf)\nfs=20\nax.legend(loc='upper right',fontsize=15,framealpha=1)\nax.set_xlabel('time since first infection [days]',fontsize=fs)\nax.set_ylabel('Number of known active cases',fontsize=fs)\nplt.show()\nplt.close()\n\n\n\nprint(\"Time from lockdown to local maximum:\")\n# calculate time from lockdown to local maximum for each trajectory\nmask = (t > lockdown_threshold_0)*(t < lockdown_threshold_2)\nt_mask = t[(mask)]\ndurations_from_lockdown_to_local_maximum2 = np.zeros(N_simulations,\n dtype=float)\nfor i,e in enumerate(data_results2):\n y_plot = np.sum ( e[:,4*M:7*M], axis = -1)\n index = np.argmax( y_plot[(mask)])\n durations_from_lockdown_to_local_maximum2[i] = t_mask[index] - lockdown_threshold_0\nprint('Mean time from beginning of lockdown to subsequent peak = {0:3.1f} days'.format(np.mean(durations_from_lockdown_to_local_maximum2)))\n\nhist, bin_edges = np.histogram(durations_from_lockdown_to_local_maximum2,10 ,density=True)\nbin_centers = (bin_edges[1:] + bin_edges[:-1])/2.\nbin_widths = bin_edges[1]-bin_edges[0]\nfig, ax =plt.subplots(1,1,figsize=(10,6))\nax.axvline(np.mean(durations_from_lockdown_to_local_maximum2),ls='--',color='black',\n label='Mean')\nax.bar(bin_centers,hist,bin_widths,color='dodgerblue',\n label='Distribution',alpha=0.7)\nax.set_xlabel('Time from beginning of lockdown until subsequent peak [days]',fontsize=fs)\nax.set_ylabel('Probability',fontsize=fs)\nax.legend(loc='best',fontsize=fs)\nplt.show()\nplt.close()\n''';\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "eb9af4f832ee38be9b4d115504191417efa8babd", "size": 152918, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/control/ex07 - SEkIkIkR - UK - partial release.ipynb", "max_stars_repo_name": "hidekb/pyross", "max_stars_repo_head_hexsha": "6f309fc8739d98ce54ad1f478ecf5aeda1ff7ab1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/control/ex07 - SEkIkIkR - UK - partial release.ipynb", "max_issues_repo_name": "hidekb/pyross", "max_issues_repo_head_hexsha": "6f309fc8739d98ce54ad1f478ecf5aeda1ff7ab1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/control/ex07 - SEkIkIkR - UK - partial release.ipynb", "max_forks_repo_name": "hidekb/pyross", "max_forks_repo_head_hexsha": "6f309fc8739d98ce54ad1f478ecf5aeda1ff7ab1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 220.0258992806, "max_line_length": 41080, "alphanum_fraction": 0.9015354635, "converted": true, "num_tokens": 4721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.34474858372159606}} {"text": "# Table of Contents\n* [Areal Interpolation of Population Counts Using National Land Cover Data (NLCD) in Python: vectorized raster](#Areal-Interpolation-of-Population-Counts-Using-National-Land-Cover-Data-%28NLCD%29-in-Python:-vectorized-raster)\n* [Step 1: read the corresponding image](#Step-1:-read-the-corresponding-image)\n* [Step 2: read a GeoDataFrame and append population from external source](#Step-2:-read-a-GeoDataFrame-and-append-population-from-external-source)\n* [Step 3: create weights from regression for each pixel type](#Step-3:-create-weights-from-regression-for-each-pixel-type)\n* [Step 4: create correspondence table for each pixel](#Step-4:-create-correspondence-table-for-each-pixel)\n* [Step 5: calculate population from a different tract subdivision](#Step-5:-calculate-population-from-a-different-tract-subdivision)\n\n\n# Areal Interpolation of Population Counts Using National Land Cover Data (NLCD) in Python: vectorized raster\n\nThis is a notebook that presents the functions built that uses the US Geological Survey's National Land Cover Data (NLCD) for population interpolation. This comprises a concise framework to use the NLCD data to estimate population into any spatial extent that the researcher might be interested. This step-by-step procedure can be used, for example, to more accurately harmonize population between two distinct periods of time that might have different spatial extents. For exemple, two different set of census tracts.\n\nThis was inpired by *Reibel, Michael, and Aditya Agrawal. \"Areal interpolation of population counts using pre-classified land cover data.\" Population Research and Policy Review 26.5-6 (2007): 619-633.*\n\nFirst let's import all the functions that we want:\n\n\n```python\nfrom tobler.vectorized_raster_interpolation import *\n```\n\n# Step 1: read the corresponding image\n\nThe first step to use these functionalities is to read a file from NLCD. We chose to use the data from Pennsylvania state like in example of the [GeoPySpark homepage](https://github.com/locationtech-labs/geopysparkk) and then download the file with these commands:\n\n```\ncurl -o /tmp/NLCD2011_LC_Pennsylvania.zip \"https://s3-us-west-2.amazonaws.com/prd-tnm/StagedProducts/NLCD/data/2011/landcover/states/NLCD2011_LC_Pennsylvania.zip?ORIG=513_SBDDG\"\n\nunzip -d /tmp /tmp/NLCD2011_LC_Pennsylvania.zip\n\n```\n\nThen in the same directory as this notebook do\n```\nln -s /tmp/NLCD2011_LC_Pennsylvania.tif .\n```\n\nNow, you need to specify the file path of the unzipped file that would look like something like this:\n\n\n```python\nraster_path = '~/NLCD2011_LC_Pennsylvania.tif'\n```\n\nNow, we import most of the needed packages to run the following steps. We highlight the rasterio package that is used to read and process the image of Pennsylvania.\n\n\n```python\n%matplotlib inline\nimport rasterio\nfrom rasterio.plot import show\n\nimport pandas as pd\nimport pickle\n\nimport geopandas as gpd\n\nimport statsmodels.formula.api as smf\nfrom statsmodels.genmod.families import Poisson\n\nimport numpy as np\n\nimport time\n```\n\n\n```python\npenn_raster = rasterio.open(raster_path)\nshow(penn_raster, cmap='terrain')\n```\n\nEach pixel represent one classification according to the NLCD. Therefore, we need to build a correspondence of the pixels code and what they represent accordingly to https://www.mrlc.gov/sites/default/files/metadata/landcover.html.\n\nAnother nice way to explore the NLCD is to use this Explorer Tool: https://www.mrlc.gov/viewer/\n\nThe description of the codes follows below:\n\n\n```python\nwith open('../files/land_cover_corresp.pkl', 'rb') as input:\n land_cover_corresp = pickle.load(input)\nland_cover_corresp\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeLong_DescriptionShort_Description
011Open Water - All areas of open water, generall...Open Water
112Perennial Ice/Snow - All areas characterized b...Perennial Ice/Snow
221Developed, Open Space - Includes areas with a ...Developed, Open Space
322Developed, Low Intensity -Includes areas with ...Developed, Low Intensity
423Developed, Medium Intensity - Includes areas w...Developed, Medium Intensity
524Developed, High Intensity - Includes highly de...Developed, High Intensity
631Barren Land (Rock/Sand/Clay) - Barren areas of...Barren Land (Rock/Sand/Clay)
741Deciduous Forest - Areas dominated by trees ge...Deciduous Forest
842Evergreen Forest - Areas dominated by trees ge...Evergreen Forest
943Mixed Forest - Areas dominated by trees genera...Mixed Forest
1051Dwarf Scrub - Alaska only areas dominated by s...Dwarf Scrub
1152Shrub/Scrub - Areas dominated by shrubs; less ...Shrub/Scrub
1271Grassland/Herbaceous - Areas dominated by gram...Grassland/Herbaceous
1372Sedge/Herbaceous - Alaska only areas dominated...Sedge/Herbaceous
1473Lichens - Alaska only areas dominated by fruti...Lichens
1574Moss - Alaska only areas dominated by mosses, ...Moss
1681Pasture/Hay - Areas of grasses, legumes, or gr...Pasture/Hay
1782Cultivated Crops - Areas used for the producti...Cultivated Crops
1890Woody Wetlands - Areas where forest or shrub l...Woody Wetlands
1995Emergent Herbaceous Wetlands - Areas where per...Emergent Herbaceous Wetlands
20255NANA
\n
\n\n\n\n# Step 2: read a GeoDataFrame and append population from external source\n\nSo far, we only read the image data from the NLCD, but not with any polygons from any spatial context of interest yet. This example uses all census data that the user must provide your own copy of the external database. A step-by-step procedure for downloading the data can be found here: https://github.com/spatialucr/geosnap/blob/master/examples/01_getting_started.ipynb. After the user download the LTDB_Std_All_fullcount.zip and extract the files, the filepath might be something like presented below.\n\n*obs.: this step could be from any shapefile, GeoJson, etc. that the researcher might have*\n\n\n```python\nfilepath = '~/data/LTDB_Std_2010_fullcount.csv'\n\ncensus_2010 = pd.read_csv(filepath, encoding = \"ISO-8859-1\", sep = \",\")\n\n# This file can be download here: https://drive.google.com/open?id=1gWF0OCn6xuR_WrEj7Ot2jY6KI2t6taIm\nwith open('C:\\\\Users\\\\renan\\\\Desktop\\\\segregation_working_notebooks\\\\data\\\\tracts_US.pkl', 'rb') as input:\n map_gpd = pickle.load(input)\n\ndf = census_2010.loc[(census_2010.state == \"PA\")]\n\nmap_gpd['INTGEOID10'] = pd.to_numeric(map_gpd[\"GEOID10\"])\nmerged_gdf = map_gpd.merge(df, left_on = 'INTGEOID10', right_on = 'tractid')\nmerged_gdf.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
STATEFP10COUNTYFP10TRACTCE10GEOID10NAME10COUNTY_IDcounty_id2COUNTYNS10NAME10_COUGEOID_MSA...a15hsp10a60hsp10ageasn10a15asn10a60asn10agentv10a15ntv10a60ntv10GlobD10GlobG10
0420010308004200103080030842001420011213656Adams23900...1321460145612wWhite
1420010304004200103040030442001420011213656Adams23900...1642423701112whSingle immig
2420010303004200103030030342001420011213656Adams23900...2041511411552whSingle immig
3420010305004200103050030542001420011213656Adams23900...15518812402whSingle immig
4420010307004200103070030742001420011213656Adams23900...167194267301wWhite
\n

5 rows × 61 columns

\n
\n\n\n\n\n```python\nmerged_gdf.plot(column = 'pop10', legend = True, figsize = (10, 5))\n```\n\n# Step 3: create weights from regression for each pixel type\n\nOnce you've got your GeoDataFrame with the desired variable, which is the total population in this case, already created and also the raster from NLCD data, you can estimate the weight of each are type according to the code and code description with the function `return_weights_from_regression`. In this function, you'll estimate the following model, by default:\n\n\\begin{equation}\n\\begin{split}\nPopulation_i & \\sim Poisson(\\mu_i)\\\\\nlog(\\mu_i) & = \\beta_1 \\times Type\\_21_i + \\beta_2 \\times Type\\_22_i + \\beta_3 \\times Type\\_23_i + \\beta_4 \\times Type\\_24_i\\\n\\end{split}\n\\end{equation}\n\n*obs.: please, note that this regression is without intercept.*\n\nFor a more detailed information and alternative options of this function you can type `help(return_weights_from_regression)`:\n\n\n```python\nhelp(return_weights_from_regression)\n```\n\n Help on function return_weights_from_regression in module tobler.vectorized_raster_interpolation:\n \n return_weights_from_regression(geodataframe, raster_path, pop_string, codes=[21, 22, 23, 24], likelihood='Poisson', n_pixels_option_values=256, force_crs_match=True, na_value=255, ReLU=True)\n Function that returns the weights of each land type according to NLCD types/codes\n \n Parameters\n ----------\n \n geodataframe : a geopandas geoDataFrame used to build regression\n \n raster_path : the path to the associated raster image.\n \n pop_string : the name of the variable on geodataframe that the regression shall be conducted\n \n codes : an integer list of codes values that should be considered as 'populated' from the National Land Cover Database (NLCD).\n The description of each code can be found here: https://www.mrlc.gov/sites/default/files/metadata/landcover.html\n The default is 21 (Developed, Open Space), 22 (Developed, Low Intensity), 23 (Developed, Medium Intensity) and 24 (Developed, High Intensity).\n \n likelihood : the likelihood assumed for the dependent variable (population). \n It can be 'Poisson' or 'Gaussian'. \n With the 'Poisson' a Generalized Linear Model with log as link function will be fitted and 'Gaussian' an ordinary least squares will be fitted. \n \n n_pixels_option_values : number of options of the pixel values of rasterior. Default is 256.\n \n force_crs_match : bool. Default is True.\n Wheter the Coordinate Reference System (CRS) of the polygon will be reprojected to the CRS of the raster file. \n It is recommended to let this argument as True.\n \n na_value : int. Default is 255.\n The number which is considered to be 'Not a Number' (NaN) in the raster pixel values.\n \n ReLU : bool. Default is True.\n Wheter the Rectified Linear Units (ReLU) transformation will be used to avoid negative weights for the land types.\n \n Notes\n -----\n 1) The formula uses a substring called 'Type_' before the code number due to the 'append_profile_in_gdf' function.\n 2) The pixel value, usually, ranges from 0 to 255. That is why the default of 'n_pixels_option_values' is 256.\n \n\n\n\n```python\nweights = return_weights_from_regression(merged_gdf, raster_path, 'pop10')\nweights\n```\n\n Appending profile...\n Append profile: Done.\n Starting to fit regression...\n\n\n\n\n\n array([0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0.00010345, 0.00098918, 0.00286406, 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. , 0. , 0. , 0. , 0. ,\n 0. ])\n\n\n\nThe resulting vector is a vector the coefficients of the regresison in the exact positions of the code of each land type. This is going to be needed for the future interpolation. \n\nSince several things happen under the hood of the `return_weights_from_regression` function, we choose to explain in more details this step in a separate example notebook called `regression_vectorized_raster_weights_explained_example.ipynb`.\n\n*One alternative way to calculate weights is to use the approach of the function `return_weights_from_xgboost`, instead of the regression approach.*\n\n# Step 4: create correspondence table for each pixel\n\nThis step might be one of the most expensive, computationally, in this process with the function `create_non_zero_population_by_pixels_locations`. Therefore, we inform the calculated total time. \n\nIn this function, you create a table that relates each pixel to its correspoding population. Each pixel has speciffically and uniquely one latitude and one longitude. This function internally, uses the weights given by the regression previously fitted and corrects with a correction term that varies with each tract accordingly to this equation:\n\n$$G_S=G_W\\left ( \\frac{T_G}{\\hat{T_G}} \\right )$$\n\nwhere $G_S$ is the scaled population estimate of grid cell $G$, $G_W$ is the raw weighted population estimate of grid cell $G$, $T_G$ is the observed population of the source tract of grid cell $G$, and $\\hat{T_G}$ is the fitted population of the source tract of grid cell $G$ derived by applying the weights to all grid cells and summing across all grid cells in source tract $T$. For more information you can type `help(create_non_zero_population_by_pixels_locations)`.\n\nobs. 1: Internally, all the necessary projections that might be needed are made inside the function.\n\nobs. 2: The results are only from the pixel that have some population on it.\n\n\n```python\nt0 = time.time()\ncorrespondence_table = create_non_zero_population_by_pixels_locations(merged_gdf, penn_raster, 'pop10', weights)\nt1 = time.time()\n```\n\n Polygon 3218 processed out of 3218\r\n\n\n```python\nprint('Total Time to build the correspondence table (in minutes): {}'.format((t1 - t0)/60))\n```\n\n Total Time to build the correspondence table (in minutes): 16.75805535316467\n\n\n\n```python\ncorrespondence_table.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
pop_valuelonslats
01.09115716002752041275
10.11411515998552041245
20.11411515998852041245
30.11411515999152041245
40.11411515999452041245
\n
\n\n\n\nAs you can see, this is a table that has each pixel latitude and longitude and the corresponding population calculated in the `pop_value` variable.\n\nAlso, one characteristic is that the total value of this correspondence table is the same of the original data:\n\n\n```python\ncorrespondence_table['pop_value'].sum() # Theoretically, the value is an integer, however this might not be the case due to numerical approximations\n```\n\n\n\n\n 12702378.999999985\n\n\n\n\n```python\nmerged_gdf['pop10'].sum()\n```\n\n\n\n\n 12702379\n\n\n\nHowever, this table has over 20 million lines, since it is all the non-zero pixels of the spatial extent:\n\n\n```python\nlen(correspondence_table)\n```\n\n\n\n\n 20029531\n\n\n\n# Step 5: calculate population from a different tract subdivision\n\nNow that we have a table that has the estimation of how many people leave in each pixel in this year, you can use this to estimate the population of basically **any clipping** that you may have in your data. Let's artificially clip the Pennsylvania State in a different set of tracts and then calculate the population for these tracts:\n\n\n```python\nfrom shapely.ops import cascaded_union\nboundary = gpd.GeoSeries(cascaded_union(merged_gdf.geometry)).buffer(0.001) # The 'buffer' method prevents some unusual points inside the state\npa_region_pre = gpd.GeoDataFrame(gpd.GeoSeries(boundary))\npa_region = pa_region_pre.rename(columns={0:'geometry'}).set_geometry('geometry')\npa_region.plot(edgecolor = 'black')\n```\n\nFirst, let's create a grid around the Pennsylvania area in order to overlay it to the actual region of this state later.\n\n\n```python\nfrom shapely.geometry import Polygon\n\nlow_left = -81\nlow_right = -74\nup_left = 38\nup_right = 43\n\nthickness = 60\n\n# This snippet was inspired in https://github.com/pysal/libpysal/blob/aa7882e7877b962f4269ea86a612dfc58152e5c6/libpysal/weights/user.py#L95\naux = list()\nfor i in np.linspace(low_left, low_right, num = thickness):\n for j in np.linspace(up_left, up_right, num = thickness):\n \n # Each width 'jump' must be at the same order of the grid constructed\n ll = i, j\n ul = i, j + np.diff(np.linspace(up_left, up_right, num = thickness))[0]\n ur = i + np.diff(np.linspace(low_left, low_right, num = thickness))[0], j + np.diff(np.linspace(up_left, up_right, num = thickness))[0]\n lr = i + np.diff(np.linspace(low_left, low_right, num = thickness))[0], j\n aux.append(Polygon([ll, ul, ur, lr, ll]))\n \npolys2 = gpd.GeoSeries(aux)\n\nenvgdf = gpd.GeoDataFrame(polys2)\nenvgdf_final = envgdf.rename(columns={0:'geometry'}).set_geometry('geometry')\nenvgdf_final.plot(edgecolor = 'black')\n```\n\nNow, we overlay the grid built with Pennsylvania and extract the intersection.\n\n\n```python\nres_union = gpd.overlay(pa_region, envgdf_final, how='intersection')\nres_union.plot(edgecolor = 'black')\n```\n\nNow, a very important step to take is to establish what is the Coordinate Reference System (CRS) of the GeoDataFrame we are working on. Therefore, we set that the resulting tracts of this overlay are in the same CRS of the original Pennsylvania GeoDataFrame:\n\nps.: this step is necessary in this case, since the resulting `res_union` does not have a CRS. \n\n\n```python\nres_union.crs = merged_gdf.crs\nres_union.crs\n```\n\n\n\n\n {'init': 'epsg:4326'}\n\n\n\nNow, we use the function `calculate_interpolated_population_from_correspondence_table` that uses as input the GeoDataFrame with the desired tract division, the raster file and the correspondence table built previously.\n\nThis step might be expensive computationally. Therefore, we calculate the time taken again.\n\n\n```python\nt0 = time.time()\ninterpolated_pa = calculate_interpolated_population_from_correspondence_table(res_union, penn_raster, correspondence_table)\nt1 = time.time()\n```\n\n Polygon 1349 processed out of 1349\r\n\n\n```python\nprint('Total Time to interpolate the population with new tracts (in minutes): {}'.format((t1 - t0)/60))\n```\n\n Total Time to interpolate the population with new tracts (in minutes): 74.72323754231135\n\n\n\n```python\ninterpolated_pa.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
geometryinterpolated_population
0POLYGON ((-75.19416491077428 40.71186440677966...67851.427415
1POLYGON ((-75.42372881355932 40.6271186440678,...68965.446573
2POLYGON ((-75.1864406779661 40.68088509831123,...297.593939
3(POLYGON ((-75.10228899895466 40.7966101694915...1547.847745
4POLYGON ((-75.42372881355932 40.71186440677966...22365.792509
\n
\n\n\n\nAs you can see, the result is also a GeoDataFrame with the variable called `interpolated_population`.\n\n\n```python\ninterpolated_pa.plot(column = 'interpolated_population', legend = True, figsize = (10, 5))\n```\n\nYou can see the highlighted area of Philadelphia and Pittsburgh and the legend ranging from higher values than the previous map of this state. Nevertheless, we can check that the resulting total population was the same as the original data.\n\n\n```python\ninterpolated_pa['interpolated_population'].sum()\n```\n\n\n\n\n 12702379.0\n\n\n", "meta": {"hexsha": "ca400c6dbbf6e3491fe441c296aac6bce1f491ae", "size": 323164, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/regression_vectorized_raster_example.ipynb", "max_stars_repo_name": "pattyf/tobler", "max_stars_repo_head_hexsha": "b3808eb3b532c6a4fd9baacdcc453c7021b2b1ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/regression_vectorized_raster_example.ipynb", "max_issues_repo_name": "pattyf/tobler", "max_issues_repo_head_hexsha": "b3808eb3b532c6a4fd9baacdcc453c7021b2b1ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/regression_vectorized_raster_example.ipynb", "max_forks_repo_name": "pattyf/tobler", "max_forks_repo_head_hexsha": "b3808eb3b532c6a4fd9baacdcc453c7021b2b1ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 225.2013937282, "max_line_length": 135620, "alphanum_fraction": 0.8882239358, "converted": true, "num_tokens": 8392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.3445189179103954}} {"text": "# Multiscale Migration Model\n\n### Scroll down to \"Editing Variable Values\" after running all cells \n\nThis notebook implements our model using `numpy`, `haversine`, and `pandas` (with `xlrd`). It has been tested to run on Python 3.6. To start, import the required libraries.\n\n\n\n```python\nimport os\nimport sys\nimport subprocess\nworking_directory = os.path.abspath('')\nsys.path.append(os.path.normpath(os.path.join(working_directory, \"..\", \"..\")))\n```\n\n\n```python\n# These libraries are used later to supply mathematical calculations.\nimport numpy as np\nimport pandas as pd\nfrom math import e\nfrom haversine import haversine\nimport ipywidgets as widgets\nfrom ipywidgets import *\n# Visualizaton\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport gos\nfrom gos.visualization import map_plot\n%matplotlib inline\n# Reduce some visual clutter by only printing ten rows at a time.\n# This can be adjusted to match personal preferences.\npd.set_option(\"display.max_rows\", 500)\n```\n\n\n```python\nplt.style.use('ggplot')\n```\n\nThe datasets used in the model are found in the `/data` subdirectory. Many are formatted as either CSV files or XLSX files.\n\n\n```python\nprint(subprocess.run(['ls', 'data'], capture_output=True, check=True).stdout.decode('utf-8'))\n```\n\n## Use this tool to change the skill level at which migration is studied \n\n\n\n```python\nskill = IntSlider(min=0, max=100, value=90)\ndisplay(skill)\n```\n\nThe following shortcut functions helps locate these data files easily.\n\n\n```python\ndef file_path(name):\n \"\"\"\n Shortcut function to get the relative path to the directory\n which contains the data.\n \"\"\"\n return \"./data/%s\" % name\n```\n\n\n\n## Cleaning the data.\n\nIn this step, we define some helper functions that will help all of our datasets talk to each other.\n\n\n\n\n```python\ncolumn_names = [\"Name\", \"Code\"]\n\ndef country_codes():\n \"\"\"\n Build country rows from their names, ISO codes, and Numeric\n Country Codes.\n \"\"\"\n cc = (\n pd.read_csv(\n file_path(\n \"Country_List_ISO_3166_Codes_Latitude_Longitude.csv\"),\n usecols=[0, 2, 3],\n index_col=1,\n keep_default_na=False))\n #other_codes = pd.read_csv(file_path(\"other.csv\"), index_col=1)\n \n #\n cc.columns = column_names\n #cc.index.rename(\"Name\")\n return cc #pd.concat([cc, other_codes])\n\ndef other_codes():\n other_codes = pd.read_csv(file_path(\"other.csv\"), index_col=1)\n other_codes.columns = column_names[0:1]\n return other_codes\n```\n\n\n```python\nworld = gos.World(index=set(country_codes().index) | set(other_codes().index))\n```\n\n\n```python\ngos.Neighborhood.update(country_codes().groupby(\"Alpha-3 code\")[\"Name\"].apply(list).to_dict())\ngos.Neighborhood.update(other_codes().groupby('ISO')[\"Name\"].apply(list).to_dict())\ngos.Neighborhood.update(country_codes().groupby(\"Alpha-3 code\")[\"Code\"].apply(list).to_dict())\n```\n\n\n \n# Importing Data\n\n### Freedom Index\n\nThe [Freedom Index](https://freedomhouse.org/report/freedom-world/freedom-world-2017) comes from Freedom House. \n\nA high freedom index score indicates a politically free country \n\n\n\n\n```python\ndef freedom_index():\n \"\"\"\n Read data from the Freedom Index.\n \"\"\"\n # TODO: Add xlrd to requirements.\n xl = pd.ExcelFile(file_path(\"Freedom_index.xlsx\"))\n xl = xl.parse(1)\n xl.set_index(\"Country\")\n return xl\n\nfi = freedom_index().set_index(\"Country\")\nfi.columns = [\"Freedom Index\"]\nfi.plot.hist(bins=10)\n#print(len(fi))\n```\n\n\n\n### A/B Values\n\nThese values are used in the return to skill function. These values are based on each country's income distribution.\n\n\n\n```python\ndef ab_values():\n \"\"\"\n Read generated A/B values for each country.\n \"\"\"\n return pd.read_excel(file_path(\"A&B values for RTS.xlsx\"))\n\nab = ab_values()\nab = ab.set_index(\"Country\")\n#ab.info()\n#print(ab)\nab.plot.hist(subplots=True, sharex=False)\n```\n\n\n \n### Passport Index\n\nThe [Passport Index](https://www.cato.org/human-freedom-index) comes from Arton Capital. \n\nA low passport index indicates a welcoming country. \n\n\n\n```python\ndef passport_index():\n \"\"\"\n Read data from the Passport Index.\n \"\"\"\n pi = pd.read_excel(file_path(\"PassportIndex.xlsx\"))\n pi = pi.set_index(\"Country\")\n pi.columns = [\"Passport Index\"]\n return pi\n\npi = passport_index()\npi.plot.hist()\n```\n\n\n\n## Unemployment\n\n\n\n\n```python\nunemployment_data = pd.read_csv(file_path(\"CIA_Unemployment.csv\"), index_col=0, usecols=[1, 2])\nunemployment_data[\"Unemployment\"] /= 100\nunemployment_data.plot.hist()\n```\n\n\n\n## Population\n\n\n\n\n```python\n# Population\npopulation = pd.read_csv(file_path(\"newPOP.csv\"))\npopulation = population.set_index(\"Country\")\npopulation\n```\n\n\n```python\nworld.update_neighborhoods(ab)\nworld.update_neighborhoods(pi)\nworld.update_neighborhoods(unemployment_data)\nworld.update_neighborhoods(population)\nworld.update_neighborhoods(fi)\n```\n\n\n\n## Shared Language\n\nAgents are assigned proficiency in languages spoken in their origin country. Moving to a country with entirely new languages presents a higher migration cost. \n\n\\begin{equation}\n L_{O\\leftrightarrow D}\\ = \n \\begin{cases}\n 0 & \\text{if origin and destination share a spoken language} \\\\\n 1 & \\text{otherwise} \\\\\n \\end{cases}\n\\end{equation}\n\n\n\n\n```python\nlang_csv = pd.read_csv(file_path(\"languages.csv\"), index_col=0)\nlang_sets = [set([str(y).strip() for y in x[1] if y != ' ']) for x in lang_csv.iterrows()]\noverlap = []\nfor s in lang_sets:\n o = []\n for i in range(len(lang_sets)):\n o.append(len(lang_sets[i].intersection(s)) >= 1)\n overlap.append(o)\nlang_data = pd.DataFrame(overlap, index=lang_csv.index, columns=lang_csv.index)\nprint(len(lang_data))\nworld.add_matrix(\"language\", 1-lang_data)\n```\n\n\n\n## UN Migration History\n\n\n\n\n```python\nun_pd = pd.read_excel(\n file_path(\n \"UN_MigrantStockByOriginAndDestination_2015.xlsx\"\n ),\n skiprows=15\n )\nun_pd = un_pd.set_index('Unnamed: 1')\nun_pd = un_pd.iloc[0:275,7:250]\n\n# TODO: Should we be using the UN numbers for this?\nun_pd = un_pd.sort_index().fillna(1)\nworld.add_matrix(\"un\", un_pd)\n```\n\n\n\n# Calculations\n\n\n\n\n\n## Distance\n\nThe great circle distance between the average latitude and longitude of each country is used to determine distance between each pair of countries. A greater distance between countries corresponds to a greater cost of migration.\n\n\n\n\n```python\ndistance_frame = pd.read_csv(\n file_path(\"Country_List_ISO_3166_Codes_Latitude_Longitude.csv\"),\n usecols=[2,4,5],\n index_col=0,\n keep_default_na=False)\nlocations = [(x[1][0], x[1][1]) for x in distance_frame.iterrows()]\nrows = []\nfor i in range(len(locations)):\n row = []\n for loc in locations:\n row.append(haversine(loc, locations[i]))\n rows.append(row)\ndistance = pd.DataFrame(rows, distance_frame.index, distance_frame.index)\nworld.add_matrix(\"distance\", distance / distance.max().max())\n```\n\n\n\n# Editing Variable Values \nRemove the \"#\" and change the values to best simulate your scenario \n\nTo reset values, run all cells above \n\n\n\n\n```python\npd.options.mode.chained_assignment = None # default='warn'\n\nworld.data[\"Freedom Index\"][\"AUS\"]=50\n#world.data[\"Passport Index\"][\"AUS\"]=80\n#world.data[\"Unemployment\"][\"AUS\"]=.058\n#world.data[\"Population\"][\"AUS\"]=8000000\n#world.matrices[\"un\"][\"AUS\"][\"USA\"]=77845\n```\n\n\n\n## Calculate \"RTS\".\nThis function measures income potential in a given country based on an agent's skill level (x). \n\nIt takes the form: \n\\begin{equation}\nAe^{Bx}\n\\end{equation}\nWhere A and B are constants unique to each country \n\n\n\n\n```python\nworld.update_neighborhoods(pd.Series(world.data[\"A\"] * e ** (world.data[\"B\"] * skill.value)), \"rts\")\n```\n\n\n\n## Country Beta Values\n\n\n\n\n```python\nworld.update_neighborhoods(pd.Series(world.data[\"A\"] * e ** (world.data[\"B\"] * 30)), \"beta\")\n```\n\n\n\n\n## Freedom Index difference \n\\begin{equation}\n\\frac{FI_D-FI_O}{100}\n\\end{equation}\n\nThis value weighs the origin and destination FI values against eachother. \n\n\n\n\n```python\nrows=[]\nfor i in range(len(world.data[\"Freedom Index\"])):\n row = []\n for freedom_index in world.data[\"Freedom Index\"]:\n diff=(freedom_index-(world.data[\"Freedom Index\"][i]))/100.0\n row.append(diff)\n rows.append(row)\nfi_diff = (pd.DataFrame(rows, world.data[\"Freedom Index\"].index, world.data[\"Freedom Index\"].index))\nprint(fi_diff)\n```\n\n\n\n\n## Political Barriers\n$$ PB = \\delta_1 \\frac{PIR_{D}}{100} + \\delta_2 (1-\\frac{(FI_D-FI_O)}{100}) $$\n\nPolitical barriers combines passport index rank (PIR) and freedom index scores (FI) for each country. The greater the value, the higher the cost of migration. \n\n\n\n\n\n```python\ndelta1=.5\ndelta2=.25\npolitical_barriers=delta1*world.data[\"Passport Index\"]/100.0 + delta2*(1 - fi_diff)\nprint(political_barriers)\n\n```\n\n\n```python\nworld.add_matrix(\"Political Barriers\", political_barriers)\n```\n\n\n\n\n## Migration History \nOut Migration: \n\\begin{equation} OM_{O\\rightarrow D}\\ = \\frac {\\text {migrants from origin in destination}} {\\text {population of origin}} \\end{equation}\n\nEthnic Enclave: \n\\begin{equation} EE_{O\\leftrightarrow D}\\ = \\frac {\\text{migrants from origin in destination}} {\\text {population of destination.}} \\end{equation}\n\nMigration History:\n\\begin{equation}\nMH_{O\\rightarrow D}\\ = \\gamma_1 (1-OM_{O\\rightarrow D})\\ + \\gamma_2 (1-EE_{O\\rightarrow D}) \n\\end{equation}\n\n\n\n\n```python\ngamma1=.5\ngamma2=.5\nOM=world.matrices['un'].sort_index(axis=1).sort_index(axis=0)/world.data['Population']\n#transpose UN matrix for this calculation so that we are dividing by population of destination \nEE=world.matrices['un'].T.sort_index(axis=1).sort_index(axis=0)/world.data['Population']\nEE=EE.T\nMH=gamma1*(OM)+gamma2*(EE)\n#print(MH)\nmax_MH = MH.max().nlargest(10).mean()\n#print(max_MH)\nMH = 1 - (MH/max_MH)\nMH[MH<0] = 0\nprint(MH)\n```\n\n\n```python\nworld.add_matrix(\"Migration History\", MH)\n```\n\n\n\n\n# Cost\n\n\n\n\n\n\n\nThe cost of migration between an origin and destination is the weighted average of the distance, migration history, shared language and political barriers between the two countries. \n\\begin{equation}\nC = { \\alpha_1 \\frac{D_{O\\leftrightarrow D}} {D_{Max}} + \\alpha_2 MH_{O\\rightarrow D} + \\alpha_3 L_{O\\leftrightarrow D} + \\alpha_4 PB}\n\\end{equation}\n\n\n\n\n```python\n# Cost\nalpha1=.35\nalpha2=.35\nalpha3=.15\nalpha4=.15\nc = (alpha1*world.matrices[\"distance\"] +\n alpha2*world.matrices[\"Migration History\"] +\n alpha3*world.matrices[\"language\"] +\n alpha4*world.matrices[\"Political Barriers\"])\nworld.add_matrix(\"cost\", c * world.data['beta'])\n```\n\n\n```python\nmap_plot(world.matrices[\"cost\"][\"SYR\"], title=\"Costs (SYR)\")\n```\n\n\n```python\nmap_plot(world.matrices[\"cost\"][\"FRA\"], title=\"Costs (FRA)\")\n```\n\n\n```python\nworld.update_neighborhoods((1 - world.data[\"Unemployment\"]) * world.data[\"rts\"], \"wages\")\n```\n\n\n```python\nmap_plot(world.data[\"wages\"], title=\"Wages\")\n```\n\n\n```python\n#beta = world.data.rts.mean()\n#beta = RTS_list.median()\n\nworld.add_matrix(\"migration\", (pd.DataFrame(\n np.array(\n [[x] * len(world.data) for x in world.data[\"wages\"].values]\n ) - np.array(\n [list(world.data[\"wages\"].values)] * len(world.data)\n ),\n world.data.index,\n world.data.index\n ) - world.matrices[\"cost\"]).clip(lower=0))\nworld.matrices[\"migration\"] = world.matrices[\"migration\"] / (world.matrices[\"migration\"].sum() + 1)\nworld.matrices[\"migration\"] = world.matrices[\"migration\"] / world.matrices[\"migration\"].sum(axis=1).max()\n\n# TODO: Why does this require being transposed?\nworld.matrices[\"migration\"] = (0.15 * world.matrices[\"migration\"].transpose() * world.data[\"Population\"]).transpose()\n\nworld.matrices[\"migration\"]\n```\n\n\n```python\nmap_plot(\n world.matrices[\"migration\"].sum(axis=1)+1,\n title=\"Immigration Estimations (x={})\".format(skill.value),\n normc=matplotlib.colors.LogNorm\n)\n```\n\n\n```python\nmap_plot(\n world.matrices[\"migration\"].sum(),\n title=\"Estimated Number of Emigrants (x={})\".format(skill.value),\n normc=matplotlib.colors.Normalize\n)\n```\n\n\n```python\nmap_plot(\n world.matrices[\"migration\"].sum(axis=1) - world.matrices[\"migration\"].sum(),\n title=\"Net Migration (x={})\".format(skill.value),\n normc=gos.visualization.MidPointNorm\n)\n```\n\n\n\n\n# Exporting Data\n\n\n\n\n\nDefining Vectors\n\n\n\n\n```python\nimmigration = world.matrices[\"migration\"].sum(axis=1)+1\nemigration = world.matrices[\"migration\"].sum()\nnet_migration = world.matrices[\"migration\"].sum(axis=1) - world.matrices[\"migration\"].sum()\n```\n\n\n\n\n- To export the following data, remove the \"#\" and run the cell. \n- The excel files will appear in the data folder under multiscale-migration. \n- Change the file names (in red) everytime you want to create a spreadsheet with new results. Otherwise new changes will override the original spreadsheets. \n\n\n\n\n```python\nimmigration.to_excel(\"data/immigration.xlsx\")\nemigration.to_excel(\"data/emigration.xlsx\")\nnet_migration.to_excel(\"data/net_migration.xlsx\")\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "33a53c6299bf16ab780102025f53bb57763c7b38", "size": 23419, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/multiscale-migration/GOS+Multiscale+Migration+Model.ipynb", "max_stars_repo_name": "crcresearch/GOS", "max_stars_repo_head_hexsha": "a359f54f9477c1785501bd07a05ccbb8d122a0c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2017-10-20T15:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-03T20:55:57.000Z", "max_issues_repo_path": "examples/multiscale-migration/GOS+Multiscale+Migration+Model.ipynb", "max_issues_repo_name": "crcresearch/GOS", "max_issues_repo_head_hexsha": "a359f54f9477c1785501bd07a05ccbb8d122a0c0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10, "max_issues_repo_issues_event_min_datetime": "2017-07-26T18:07:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-06T15:33:30.000Z", "max_forks_repo_path": "examples/multiscale-migration/GOS+Multiscale+Migration+Model.ipynb", "max_forks_repo_name": "crcresearch/GOS", "max_forks_repo_head_hexsha": "a359f54f9477c1785501bd07a05ccbb8d122a0c0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-12-29T02:51:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-29T02:51:16.000Z", "avg_line_length": 26.2544843049, "max_line_length": 236, "alphanum_fraction": 0.5329433366, "converted": true, "num_tokens": 3500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3444373776110126}} {"text": "# Optimization of a State-to-State Transfer in a Two-Level-System\n\n\n```\n# NBVAL_IGNORE_OUTPUT\n%load_ext watermark\nimport qutip\nimport numpy as np\nimport scipy\nimport matplotlib\nimport matplotlib.pylab as plt\nimport krotov\n%watermark -v --iversions\n```\n\n qutip 4.3.1\n numpy 1.15.4\n scipy 1.1.0\n matplotlib 3.0.2\n matplotlib.pylab 1.15.4\n krotov 0.0.1\n CPython 3.6.7\n IPython 7.2.0\n\n\n$\\newcommand{tr}[0]{\\operatorname{tr}}\n\\newcommand{diag}[0]{\\operatorname{diag}}\n\\newcommand{abs}[0]{\\operatorname{abs}}\n\\newcommand{pop}[0]{\\operatorname{pop}}\n\\newcommand{aux}[0]{\\text{aux}}\n\\newcommand{opt}[0]{\\text{opt}}\n\\newcommand{tgt}[0]{\\text{tgt}}\n\\newcommand{init}[0]{\\text{init}}\n\\newcommand{lab}[0]{\\text{lab}}\n\\newcommand{rwa}[0]{\\text{rwa}}\n\\newcommand{bra}[1]{\\langle#1\\vert}\n\\newcommand{ket}[1]{\\vert#1\\rangle}\n\\newcommand{Bra}[1]{\\left\\langle#1\\right\\vert}\n\\newcommand{Ket}[1]{\\left\\vert#1\\right\\rangle}\n\\newcommand{Braket}[2]{\\left\\langle #1\\vphantom{#2} \\mid\n#2\\vphantom{#1}\\right\\rangle}\n\\newcommand{op}[1]{\\hat{#1}}\n\\newcommand{Op}[1]{\\hat{#1}}\n\\newcommand{dd}[0]{\\,\\text{d}}\n\\newcommand{Liouville}[0]{\\mathcal{L}}\n\\newcommand{DynMap}[0]{\\mathcal{E}}\n\\newcommand{identity}[0]{\\mathbf{1}}\n\\newcommand{Norm}[1]{\\lVert#1\\rVert}\n\\newcommand{Abs}[1]{\\left\\vert#1\\right\\vert}\n\\newcommand{avg}[1]{\\langle#1\\rangle}\n\\newcommand{Avg}[1]{\\left\\langle#1\\right\\rangle}\n\\newcommand{AbsSq}[1]{\\left\\vert#1\\right\\vert^2}\n\\newcommand{Re}[0]{\\operatorname{Re}}\n\\newcommand{Im}[0]{\\operatorname{Im}}$\nThe purpose of this example is not to solve an especially interesting physical\nproblem but to give a rather simple example of how the package can be used in\norder to solve an optimization problem.\n\n## Define the Hamiltonian\n\nIn the\nfollowing the Hamiltonian, guess field and\nstates are defined.\n\nThe Hamiltonian\n$\\op{H}_{0} = - \\omega \\op{\\sigma}_{z}$\nrepresents a\nsimple qubit with energy\nlevel splitting $\\omega$ in the basis\n$\\{\\ket{0},\\ket{1}\\}$. The control\nfield\n$\\epsilon(t)$ is assumed to couple via\nthe\nHamiltonian $\\op{H}_{1}(t) =\n\\epsilon(t) \\op{\\sigma}_{x}$ to the qubit,\ni.e., the control\nfield effectively\ndrives\ntransitions between both qubit\nstates. For now, we initialize the control\nfield as constant.\n\n\n```\ndef ham_and_states(omega=1.0, ampl0=0.2):\n \"\"\"Two-level-system Hamiltonian\n \n Args:\n omega (float): energy separation of the qubit levels\n ampl0 (float): constant amplitude of the driving field\n \"\"\"\n H0 = - 0.5 * omega * qutip.operators.sigmaz()\n H1 = qutip.operators.sigmax()\n \n psi0 = qutip.Qobj(np.array([1,0]))\n psi1 = qutip.Qobj(np.array([0,1]))\n\n eps0 = lambda t, args: ampl0\n return ([H0, [H1, eps0]], psi0, psi1)\n\nH, psi0, psi1 = ham_and_states()\n```\n\nThe projectors $\\op{P}_0 = \\ket{0}\\bra{0}$ and $\\op{P}_1 = \\ket{1}\\bra{1}$ are\nintroduced since they allow for calculating the\npopulation in the respective\nstates later on.\n\n\n```\nproj0 = psi0 * psi0.dag()\nproj1 = psi1 * psi1.dag()\n```\n\n## Define the optimization target\n\nFirst we define the time grid of the\ndynamics, i.e., by taking the following\nvalues as an example, we define the\ninitial state to be at time $t=0$ and\nconsider a total propagation time of\n$T=5$. The entire time grid is divided into\n$n_{t}=500$ equidistant time steps.\n\n\n```\ntlist = np.linspace(0, 5, 500)\n```\n\nNext, we define the optimization targets, which is technically a list of\nobjectives, but here it has just one entry defining a simple state-to-state\ntransfer\nfrom initial state $\\ket{\\Psi_{\\init}} = \\ket{0}$ to the target state\n$\\ket{\\Psi_{\\tgt}} = \\ket{1}$, which we want to reach at final time $T$. Note\nthat we also have to pass the Hamiltonian $\\op{H}(t)$ that determines the\ndynamics of\nthe system to the optimization objective.\n\n\n```\nobjectives = [\n krotov.Objective(initial_state=psi0, target=psi1, H=H)\n]\n```\n\nIn addition, we have to define and assign a shape function $S(t)$ for the update\nin each control iteration to each\ncontrol field that will be updated. This shape\nusually takes care of\nexperimental limits such as the necessity of finite ramps\nat the beginning and\nend of the control field or other conceivable limitations\nfor field shapes: wherever $S(t)$ is zero, the optimization will not change the\nvalue of the control from the original guess.\n\n\n```\ndef S(t):\n \"\"\"Shape function for the field update\"\"\"\n return krotov.shapes.flattop(t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq')\n```\n\nAt this point, we also change the initial control field $\\epsilon_{0}(t)$ from a\nconstant to a shaped pulse that switches on smoothly from zero and again\nswitches off at the final time $T$. We re-use the shape function $S(t)$ that we\ndefined for the updates for this purpose (although generally, $S(t)$ for the\nupdates has nothing to with the shape of the control field).\n\n\n```\ndef shape_field(eps0):\n \"\"\"Applies the shape function S(t) to the guess field\"\"\"\n eps0_shaped = lambda t, args: eps0(t, args)*S(t)\n return eps0_shaped\n\nH[1][1] = shape_field(H[1][1])\n```\n\nHaving defined the shape function $S(t)$ and having shaped the guess field, we\nnow tell the optimization to also use $S(t)$ as the update-shape for\n$\\epsilon_0(t)$. In addition, we have to choose `lambda_a` for each control\nfield. It controls the update magnitude of the respective field in each\niteration.\n\n\n```\npulse_options = {\n H[1][1]: krotov.PulseOptions(lambda_a=5, shape=S)\n}\n```\n\nIt is convenient to introduce the function `print_fidelity`, which can be passed\nto the optimization procedure and will be called after each iteration and thus\nprovides additional feedback about the optimization progress.\n\n\n```\ndef print_fidelity(**args):\n F_re = np.average(np.array(args['tau_vals']).real)\n print(\" F = %f\" % F_re)\n return F_re\n```\n\n## Simulate dynamics of the guess field\n\nBefore heading towards the optimization\nprocedure, we first simulate the\ndynamics under the guess field\n$\\epsilon_{0}(t)$.\n\n\n```\ndef plot_pulse(pulse, tlist):\n fig, ax = plt.subplots()\n if callable(pulse):\n pulse = np.array([pulse(t, args=None) for t in tlist])\n ax.plot(tlist, pulse)\n ax.set_xlabel('time')\n ax.set_ylabel('pulse amplitude')\n plt.show(fig)\n```\n\nThe following plot shows the guess field $\\epsilon_{0}(t)$, which is, as chosen\nabove, just a constant field (with a smooth switch-on and switch-off)\n\n\n```\nplot_pulse(H[1][1], tlist)\n```\n\nThe next line solves the equation of motion for the defined objective, which\ncontains the initial state $\\ket{\\Psi_{\\init}}$ and the Hamiltonian $\\op{H}(t)$\ndefining its evolution.\n\n\n```\nguess_dynamics = objectives[0].mesolve(tlist, e_ops=[proj0, proj1])\n```\n\nThe plot of the population dynamics shows that the guess field does not transfer\nthe initial state $\\ket{\\Psi_{\\init}} = \\ket{0}$ to the desired target state\n$\\ket{\\Psi_{\\tgt}} = \\ket{1}$.\n\n\n```\ndef plot_population(result):\n fig, ax = plt.subplots()\n ax.plot(result.times, result.expect[0], label='0')\n ax.plot(result.times, result.expect[1], label='1')\n ax.legend()\n ax.set_xlabel('time')\n ax.set_ylabel('population')\n plt.show(fig)\n```\n\n\n```\nplot_population(guess_dynamics)\n```\n\n## Optimize\n\nIn the following we optimize the guess field $\\epsilon_{0}(t)$ such\nthat the intended state-to-state transfer $\\ket{\\Psi_{\\init}} \\rightarrow\n\\ket{\\Psi_{\\tgt}}$ is solved.\n\nThe cell below carries out the optimization. It\nrequires, besides the\npreviously\ndefined optimization `objectives`, information\nabout the\noptimization functional\n$F$ (via `chi_constructor`) and the\npropagation method that should be used. In\naddition, the number of total\niterations is required and, as an option, we pass\nan info-hook that after each\niteration combines a complete printout of the state\nof the optimization with the\n`print_fidelity` function defined above.\n\nHere, we\nchoose $F = F_{re}$ with\n\\begin{equation}\nF_{re}\n=\n\\Re\\Braket{\\Psi(T)}{\\Psi_{\\tgt}}\n\\end{equation}\n\nwith\n$\\ket{\\Psi(T)}$ the\nforward propagated state of $\\ket{\\Psi_{\\init}}$.\n\n\n```\noct_result = krotov.optimize_pulses(\n objectives,\n pulse_options=pulse_options,\n tlist=tlist,\n propagator=krotov.propagators.expm,\n chi_constructor=krotov.functionals.chis_re,\n info_hook=krotov.info_hooks.chain(\n krotov.info_hooks.print_debug_information, print_fidelity\n ),\n check_convergence=krotov.convergence.check_monotonic_fidelity,\n iter_stop=10,\n)\n```\n\n Iteration 0\n objectives:\n 1:|(2)⟩ - {[Herm[2,2], [Herm[2,2], u1(t)]]} - |(2)⟩\n adjoint objectives:\n 1:⟨(2)| - {[Herm[2,2], [Herm[2,2], u1(t)]]} - ⟨(2)|\n λₐ: 5.00e+00\n S(t) (ranges): [0.000000, 1.000155]\n duration: 0.6 secs (started at 2018-12-20 08:17:54)\n optimized pulses (ranges): [0.00, 0.20]\n backward states: None\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (2.12e-01:0.50π)\n F = 0.000000\n Iteration 1\n duration: 1.3 secs (started at 2018-12-20 08:17:55)\n optimized pulses (ranges): [0.00, 0.29]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (3.16e-01:0.23π)\n F = 0.235157\n Iteration 2\n duration: 1.3 secs (started at 2018-12-20 08:17:56)\n optimized pulses (ranges): [0.00, 0.37]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (4.91e-01:0.14π)\n F = 0.444066\n Iteration 3\n duration: 1.3 secs (started at 2018-12-20 08:17:57)\n optimized pulses (ranges): [-0.07, 0.44]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (6.44e-01:0.10π)\n F = 0.611354\n Iteration 4\n duration: 1.3 secs (started at 2018-12-20 08:17:59)\n optimized pulses (ranges): [-0.14, 0.50]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (7.60e-01:0.08π)\n F = 0.735071\n Iteration 5\n duration: 1.3 secs (started at 2018-12-20 08:18:00)\n optimized pulses (ranges): [-0.20, 0.55]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (8.41e-01:0.07π)\n F = 0.821734\n Iteration 6\n duration: 1.4 secs (started at 2018-12-20 08:18:01)\n optimized pulses (ranges): [-0.26, 0.58]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (8.96e-01:0.06π)\n F = 0.880461\n Iteration 7\n duration: 1.3 secs (started at 2018-12-20 08:18:03)\n optimized pulses (ranges): [-0.30, 0.61]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (9.31e-01:0.05π)\n F = 0.919555\n Iteration 8\n duration: 1.3 secs (started at 2018-12-20 08:18:04)\n optimized pulses (ranges): [-0.34, 0.63]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (9.54e-01:0.04π)\n F = 0.945388\n Iteration 9\n duration: 1.6 secs (started at 2018-12-20 08:18:05)\n optimized pulses (ranges): [-0.36, 0.65]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (9.69e-01:0.04π)\n F = 0.962447\n Iteration 10\n duration: 1.3 secs (started at 2018-12-20 08:18:07)\n optimized pulses (ranges): [-0.39, 0.66]\n backward states: [1 * ndarray(500)]\n forward states: [1 * ndarray(500)]\n fw_states_T norm: 1.000000\n τ: (9.78e-01:0.03π)\n F = 0.973756\n\n\n\n```\noct_result\n```\n\n\n\n\n Krotov Optimization Result\n --------------------------\n - Started at 2018-12-20 08:17:54\n - Number of objectives: 1\n - Number of iterations: 10\n - Reason for termination: Reached 10 iterations\n - Ended at 2018-12-20 08:18:08\n\n\n\n## Simulate dynamics of the optimized field\n\nHaving obtained the optimized\ncontrol field, we can now\nplot it and calculate the\npopulation dynamics under\nthis field.\n\n\n```\nplot_pulse(oct_result.optimized_controls[0], tlist)\n```\n\nIn contrast to the dynamics under the guess field, the optimized field indeed\ndrives the initial state $\\ket{\\Psi_{\\init}} = \\ket{0}$ to the desired target\nstate $\\ket{\\Psi_{\\tgt}} = \\ket{1}$.\n\n\n```\nopt_dynamics = oct_result.optimized_objectives[0].mesolve(\n tlist, e_ops=[proj0, proj1])\n```\n\n\n```\nplot_population(opt_dynamics)\n```\n", "meta": {"hexsha": "7bcb037d73c300abbce6e3e5ab400f767f77690b", "size": 81359, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/01_example_simple_state_to_state.ipynb", "max_stars_repo_name": "TejasAvinashShetty/krotov", "max_stars_repo_head_hexsha": "e2dd0fad2f07f41004d7beef53e8ebc75b0d6d9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/notebooks/01_example_simple_state_to_state.ipynb", "max_issues_repo_name": "TejasAvinashShetty/krotov", "max_issues_repo_head_hexsha": "e2dd0fad2f07f41004d7beef53e8ebc75b0d6d9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/notebooks/01_example_simple_state_to_state.ipynb", "max_forks_repo_name": "TejasAvinashShetty/krotov", "max_forks_repo_head_hexsha": "e2dd0fad2f07f41004d7beef53e8ebc75b0d6d9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 102.3383647799, "max_line_length": 17672, "alphanum_fraction": 0.8483019703, "converted": true, "num_tokens": 4000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.34443737761101256}} {"text": "\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n \n Enter your authorization code:\n ··········\n Mounted at /content/drive\n\n\n# Neuromatch Academy: Week 2, Day 5, Tutorial 3\n# Learning to Act: Q-Learning\n\n__Content creators:__ Marcelo Mattar and Eric DeWitt with help from Byron Galbraith\n\n__Content reviewers:__ Matt Krause and Michael Waskom\n\n---\n\n# Tutorial Objectives\n \nIn this tutorial you will learn how to act in the more realistic setting of sequential decisions, formalized by Markov Decision Processes (MDPs). In a sequential decision problem, the actions executed in one state not only may lead to immediate rewards (as in a bandit problem), but may also affect the states experienced next (unlike a bandit problem). Each individual action may therefore affect affect all future rewards. Thus, making decisions in this setting requires considering each action in terms of their expected **cumulative** future reward.\n\nWe will consider here the example of spatial navigation, where actions (movements) in one state (location) affect the states experienced next, and an agent might need to execute a whole sequence of actions before a reward is obtained.\n\nBy the end of this tutorial, you will learn\n* what grid worlds are and how they help in evaluating simple reinforcement learning agents\n* the basics of the Q-learning algorithm for estimating action values\n* how the concept of exploration and exploitation, reviewed in the bandit case, also applies to the sequential decision setting\n\n---\n# Setup\n\n\n```python\n# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import convolve as conv\n```\n\n\n```python\n#@title Figure settings\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle\")\n```\n\n\n```python\n#@title Helper functions\ndef epsilon_greedy(q, epsilon):\n \"\"\"Epsilon-greedy policy: selects the maximum value action with probabilty\n (1-epsilon) and selects randomly with epsilon probability.\n \n Args:\n q (ndarray): an array of action values\n epsilon (float): probability of selecting an action randomly \n \n Returns:\n int: the chosen action\n \"\"\"\n if np.random.random() > epsilon:\n action = np.argmax(q)\n else:\n action = np.random.choice(len(q)) \n\n return action\n\n\nclass CliffWorld:\n \"\"\"\n World: Cliff world.\n 40 states (4-by-10 grid world).\n The mapping from state to the grids are as follows:\n 30 31 32 ... 39\n 20 21 22 ... 29\n 10 11 12 ... 19\n 0 1 2 ... 9\n 0 is the starting state (S) and 9 is the goal state (G).\n Actions 0, 1, 2, 3 correspond to right, up, left, down.\n Moving anywhere from state 9 (goal state) will end the session.\n Taking action down at state 11-18 will go back to state 0 and incur a\n reward of -100.\n Landing in any states other than the goal state will incur a reward of -1.\n Going towards the border when already at the border will stay in the same\n place.\n \"\"\"\n def __init__(self):\n self.name = \"cliff_world\"\n self.n_states = 40\n self.n_actions = 4\n self.dim_x = 10\n self.dim_y = 4\n self.init_state = 0\n\n def get_outcome(self, state, action):\n if state == 9: # goal state\n reward = 0\n next_state = None\n return next_state, reward\n reward = -1 # default reward value\n if action == 0: # move right\n next_state = state + 1\n if state % 10 == 9: # right border\n next_state = state\n elif state == 0: # start state (next state is cliff)\n next_state = None\n reward = -100\n elif action == 1: # move up\n next_state = state + 10\n if state >= 30: # top border\n next_state = state\n elif action == 2: # move left\n next_state = state - 1\n if state % 10 == 0: # left border\n next_state = state\n elif action == 3: # move down\n next_state = state - 10\n if state >= 11 and state <= 18: # next is cliff\n next_state = None\n reward = -100\n elif state <= 9: # bottom border\n next_state = state\n else:\n print(\"Action must be between 0 and 3.\")\n next_state = None\n reward = None\n return int(next_state) if next_state is not None else None, reward\n\n def get_all_outcomes(self):\n outcomes = {}\n for state in range(self.n_states):\n for action in range(self.n_actions):\n next_state, reward = self.get_outcome(state, action)\n outcomes[state, action] = [(1, next_state, reward)]\n return outcomes\n \n\ndef learn_environment(env, learning_rule, params, max_steps, n_episodes): \n # Start with a uniform value function\n value = np.ones((env.n_states, env.n_actions))\n\n # Run learning\n reward_sums = np.zeros(n_episodes)\n\n # Loop over episodes\n for episode in range(n_episodes):\n state = env.init_state # initialize state \n reward_sum = 0\n\n for t in range(max_steps):\n # choose next action\n action = epsilon_greedy(value[state], params['epsilon'])\n \n # observe outcome of action on environment\n next_state, reward = env.get_outcome(state, action)\n\n # update value function\n value = learning_rule(state, action, reward, next_state, value, params)\n \n # sum rewards obtained\n reward_sum += reward\n \n if next_state is None:\n break # episode ends\n state = next_state \n \n reward_sums[episode] = reward_sum\n \n return value, reward_sums\n\n\ndef plot_state_action_values(env, value, ax=None):\n \"\"\"\n Generate plot showing value of each action at each state.\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n\n for a in range(env.n_actions): \n ax.plot(range(env.n_states), value[:, a], marker='o', linestyle='--')\n ax.set(xlabel='States', ylabel='Values')\n ax.legend(['R','U','L','D'], loc='lower right')\n \n\ndef plot_quiver_max_action(env, value, ax=None):\n \"\"\"\n Generate plot showing action of maximum value or maximum probability at\n each state (not for n-armed bandit or cheese_world).\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n\n X = np.tile(np.arange(env.dim_x), [env.dim_y,1]) + 0.5\n Y = np.tile(np.arange(env.dim_y)[::-1][:,np.newaxis], [1,env.dim_x]) + 0.5\n which_max = np.reshape(value.argmax(axis=1), (env.dim_y,env.dim_x))\n which_max = which_max[::-1,:]\n U = np.zeros(X.shape)\n V = np.zeros(X.shape)\n U[which_max == 0] = 1\n V[which_max == 1] = 1\n U[which_max == 2] = -1\n V[which_max == 3] = -1\n \n ax.quiver(X, Y, U, V)\n ax.set(\n title='Maximum value/probability actions',\n xlim=[-0.5, env.dim_x+0.5],\n ylim=[-0.5, env.dim_y+0.5], \n )\n ax.set_xticks(np.linspace(0.5, env.dim_x-0.5, num=env.dim_x))\n ax.set_xticklabels([\"%d\" % x for x in np.arange(env.dim_x)])\n ax.set_xticks(np.arange(env.dim_x+1), minor=True)\n ax.set_yticks(np.linspace(0.5, env.dim_y-0.5, num=env.dim_y)) \n ax.set_yticklabels([\"%d\" % y for y in np.arange(0, env.dim_y*env.dim_x, \n env.dim_x)]) \n ax.set_yticks(np.arange(env.dim_y+1), minor=True)\n ax.grid(which='minor',linestyle='-')\n\n\ndef plot_heatmap_max_val(env, value, ax=None):\n \"\"\"\n Generate heatmap showing maximum value at each state\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n\n if value.ndim == 1:\n value_max = np.reshape(value, (env.dim_y,env.dim_x))\n else:\n value_max = np.reshape(value.max(axis=1), (env.dim_y,env.dim_x)) \n value_max = value_max[::-1,:]\n\n im = ax.imshow(value_max, aspect='auto', interpolation='none', cmap='afmhot')\n ax.set(title='Maximum value per state')\n ax.set_xticks(np.linspace(0, env.dim_x-1, num=env.dim_x))\n ax.set_xticklabels([\"%d\" % x for x in np.arange(env.dim_x)])\n ax.set_yticks(np.linspace(0, env.dim_y-1, num=env.dim_y))\n if env.name != 'windy_cliff_grid':\n ax.set_yticklabels(\n [\"%d\" % y for y in np.arange(\n 0, env.dim_y*env.dim_x, env.dim_x)][::-1])\n return im\n\n\ndef plot_rewards(n_episodes, rewards, average_range=10, ax=None):\n \"\"\"\n Generate plot showing total reward accumulated in each episode.\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots()\n\n smoothed_rewards = (conv(rewards, np.ones(average_range), mode='same')\n / average_range)\n\n ax.plot(range(0, n_episodes, average_range),\n smoothed_rewards[0:n_episodes:average_range],\n marker='o', linestyle='--')\n ax.set(xlabel='Episodes', ylabel='Total reward')\n \n\ndef plot_performance(env, value, reward_sums):\n fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(16, 12))\n plot_state_action_values(env, value, ax=axes[0,0])\n plot_quiver_max_action(env, value, ax=axes[0,1])\n plot_rewards(n_episodes, reward_sums, ax=axes[1,0])\n im = plot_heatmap_max_val(env, value, ax=axes[1,1])\n fig.colorbar(im)\n```\n\n---\n# Section 1: Markov Decision Processes\n\n\n```python\n#@title Video 1: MDPs and Q-learning\n# Insert the ID of the corresponding youtube video\nfrom IPython.display import YouTubeVideo\nvideo = YouTubeVideo(id=\"8yvwMrUQJOU\", width=854, height=480, fs=1)\nprint(\"Video available at https://youtu.be/\" + video.id)\nvideo\n```\n\n Video available at https://youtu.be/8yvwMrUQJOU\n\n\n\n\n\n\n\n\n\n\n\n## Section 1.1: Grid Worlds\n\nAs pointed out, bandits only have a single state and immediate rewards for our actions. Many problems we are interested in have multiple states and delayed rewards, i.e. we won't know if the choices we made will pay off over time, or which actions we took contributed to the outcomes we observed.\n\nIn order to explore these ideas, we turn the a common problem setting: the grid world. Grid worlds are simple environments where each state corresponds to a tile on a 2D grid, and the only actions the agent can take are to move up, down, left, or right across the grid tiles. The agent's job is almost always to find a way to a goal tile in the most direct way possible while overcoming some maze or other obstacles, either static or dynamic.\n\nFor our discussion we will be looking at the classic Cliff World, or Cliff Walker, environment. This is a 4x10 grid with a starting position in the lower-left and the goal position in the lower-right. Every tile between these two is the \"cliff\", and should the agent enter the cliff, they will receive a -100 reward and be sent back to the starting position. Every tile other than the cliff produces a -1 reward when entered. The goal tile ends the episode after taking any action from it.\n\n\n\nGiven these conditions, the maximum achievable reward is -11 (1 up, 9 right, 1 down). Using negative rewards is a common technique to encourage the agent to move and seek out the goal state as fast as possible.\n\n---\n# Section 2: Q-Learning\n\nNow that we have our environment, how can we solve it? \n\nOne of the most famous algorithms for estimating action values (aka Q-values) is the Temporal Differences (TD) **control** algorithm known as *Q-learning* (Watkins, 1989). \n\n\\begin{align}\nQ(s_t,a_t) \\leftarrow Q(s_t,a_t) + \\alpha \\big(r_t + \\gamma\\max_\\limits{a} Q(s_{t+1},a_{t+1}) - Q(s_t,a_t)\\big)\n\\end{align}\n\nwhere $Q(s,a)$ is the value function for action $a$ at state $s$, $\\alpha$ is the learning rate, $r$ is the reward, and $\\gamma$ is the temporal discount rate.\n\nThe expression $r_t + \\gamma\\max_\\limits{a} Q(s_{t+1},a_{t+1})$ is referred to as the TD target while the full expression \n\\begin{align}\nr_t + \\gamma\\max_\\limits{a} Q(s_{t+1},a_{t+1}) - Q(s_t,a_t),\n\\end{align}\ni.e. the difference between the TD target and the current Q-value, is referred to as the TD error, or reward prediction error.\n\nBecause of the max operator used to select the optimal Q-value in the TD target, Q-learning directly estimates the optimal action value, i.e. the cumulative future reward that would be obtained if the agent behaved optimally, regardless of the policy currently followed by the agent. For this reason, Q-learning is referred to as an **off-policy** method.\n\n## Exercise 1: Implement the Q-learning algorithm\n\nIn this exercise you will implement the Q-learning update rule described above. It takes in as arguments the previous state $s_t$, the action $a_t$ taken, the reward received $r_t$, the current state $s_{t+1}$, the Q-value table, and a dictionary of parameters that contain the learning rate $\\alpha$ and discount factor $\\gamma$. The method returns the updated Q-value table. For the parameter dictionary, $\\alpha$: `params['alpha']` and $\\gamma$: `params['gamma']`. \n\n\n\n```python\ndef q_learning(state, action, reward, next_state, value, params):\n \"\"\"Q-learning: updates the value function and returns it.\n \n Args:\n state (int): the current state identifier\n action (int): the action taken\n reward (float): the reward received\n next_state (int): the transitioned to state identifier\n value (ndarray): current value function of shape (n_states, n_actions)\n params (dict): a dictionary containing the default parameters\n \n Returns:\n ndarray: the updated value function of shape (n_states, n_actions)\n \"\"\"\n # Q-value of current state-action pair\n q = value[state, action]\n \n ##########################################################\n ## TODO for students: implement the Q-learning update rule\n # Fill out function and remove\n #raise NotImplementedError(\"Student excercise: implement the Q-learning update rule\")\n ##########################################################\n\n # write an expression for finding the maximum Q-value at the current state\n if next_state is None:\n max_next_q = 0\n else:\n max_next_q = np.max(value[next_state])\n\n # write the expression to compute the TD error\n td_error = reward + params['gamma']*max_next_q - q \n # write the expression that updates the Q-value for the state-action pair \n value[state, action] = q +params['alpha']*td_error\n \n return value\n```\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D5_ReinforcementLearning/solutions/W2D5_Tutorial3_Solution_910598ca.py)\n\n\n\nNow that we have our Q-learning algorithm, let's see how it handles learning to solve the Cliff World environment. \n\nYou will recall from the previous tutorial that a major part of reinforcement learning algorithms are their ability to balance exploitation and exploration. For our Q-learning agent, we again turn to the epsilon-greedy strategy. At each step, the agent will decide with probability $1 - \\epsilon$ to use the best action for the state it is currently in by looking at the value function, otherwise just make a random choice.\n\nThe process by which our the agent will interact with and learn about the environment is handled for you in the helper function `learn_environment`. This implements the entire learning episode lifecycle of stepping through the state observation, action selection (epsilon-greedy) and execution, reward, and state transition. Feel free to review that code later to see how it all fits together, but for now let's test out our agent.\n\n\n```python\n# set for reproducibility, comment out / change seed value for different results\nnp.random.seed(1)\n\n# parameters needed by our policy and learning rule\nparams = {\n 'epsilon': 0.1, # epsilon-greedy policy\n 'alpha': 0.1, # learning rate \n 'gamma': 1.0, # discount factor\n}\n\n# episodes/trials\nn_episodes = 500\nmax_steps = 1000\n\n# environment initialization\nenv = CliffWorld()\n\n# solve Cliff World using Q-learning\nresults = learn_environment(env, q_learning, params, max_steps, n_episodes)\nvalue_qlearning, reward_sums_qlearning = results\n\n# Plot results\nplot_performance(env, value_qlearning, reward_sums_qlearning)\n```\n\nIf all went well, we should see four plots that show different aspects on our agent's learning and progress.\n\n* The top left is a representation of the Q-table itself, showing the values for different actions in different states. Notably, going right from the starting state or down when above the cliff is clearly very bad.\n* The top right figure shows the greedy policy based on the Q-table, i.e. what action would the agent take if it only took its best guess in that state.\n* The bottom right is the same as the top, only instead of showing the action, it's showing a representation of the maximum Q-value at a particular state.\n* The bottom left is the actual proof of learning, as we see the total reward steadily increasing after each episode until asymptoting at the maximum possible reward of -11.\n\nFeel free to try changing the parameters or random seed and see how the agent's behavior changes.\n\n---\n# Summary\n\nIn this tutorial you implemented a reinforcement learning agent based on Q-learning to solve the Cliff World environment. Q-learning combined the epsilon-greedy approach to exploration-expoitation with a table-based value function to learn the expected future rewards for each state.\n\n---\n# Bonus\n\n## SARSA\n\nAn alternative to Q-learning, the SARSA algorithm also estimates action values. However, rather than estimating the optimal (off-policy) values, SARSA estimates the **on-policy** action value, i.e. the cumulative future reward that would be obtained if the agent behaved according to its current beliefs.\n\n\\begin{align}\nQ(s_t,a_t) \\leftarrow Q(s_t,a_t) + \\alpha \\big(r_t + \\gamma Q(s_{t+1},a_{t+1}) - Q(s_t,a_t)\\big)\n\\end{align}\n\nwhere, once again, $Q(s,a)$ is the value function for action $a$ at state $s$, $\\alpha$ is the learning rate, $r$ is the reward, and $\\gamma$ is the temporal discount rate.\n\nIn fact, you will notices that the *only* difference between Q-learning and SARSA is the TD target calculation uses the policy to select the next action (in our case epsilon-greedy) rather than using the action that maximizes the Q-value.\n\n### Exercise 2: Implement the SARSA algorithm\n\nIn this exercise you will implement the SARSA update rule described above. Just like Q-learning, it takes in as arguments the previous state $s_t$, the action $a_t$ taken, the reward received $r_t$, the current state $s_{t+1}$, the Q-value table, and a dictionary of parameters that contain the learning rate $\\alpha$ and discount factor $\\gamma$. The method returns the updated Q-value table. You may use the `epsilon_greedy` function to acquire the next action. For the parameter dictionary, $\\alpha$: `params['alpha']`, $\\gamma$: `params['gamma']`, and $\\epsilon$: `params['epsilon']`. \n\n\n\n```python\ndef sarsa(state, action, reward, next_state, value, params):\n \"\"\"SARSA: updates the value function and returns it.\n \n Args:\n state (int): the current state identifier\n action (int): the action taken\n reward (float): the reward received\n next_state (int): the transitioned to state identifier\n value (ndarray): current value function of shape (n_states, n_actions)\n params (dict): a dictionary containing the default parameters\n \n Returns:\n ndarray: the updated value function of shape (n_states, n_actions)\n \"\"\"\n # value of previous state-action pair\n q = value[state, action]\n \n ##########################################################\n ## TODO for students: implement the SARSA update rule\n # Fill out function and remove\n raise NotImplementedError(\"Student excercise: implement the SARSA update rule\")\n ##########################################################\n\n # select the expected value at current state based on our policy by sampling\n # from it\n if next_state is None:\n policy_next_q = 0\n else:\n # write an expression for selecting an action using epsilon-greedy\n policy_action = ...\n # write an expression for obtaining the value of the policy action at the \n # current state\n policy_next_q = ...\n \n # write the expression to compute the TD error\n td_error = ... \n # write the expression that updates the Q-value for the state-action pair \n value[state, action] = ...\n \n return value\n```\n\n\n```python\ndef sarsa(state, action, reward, next_state, value, params):\n \"\"\"SARSA: updates the value function and returns it.\n \n Args:\n state (int): the current state identifier\n action (int): the action taken\n reward (float): the reward received\n next_state (int): the transitioned to state identifier\n value (ndarray): current value function of shape (n_states, n_actions)\n params (dict): a dictionary containing the default parameters\n \n Returns:\n ndarray: the updated value function of shape (n_states, n_actions)\n \"\"\"\n # value of previous state-action pair\n q = value[state, action]\n \n # select the expected value at current state based on our policy by sampling\n # from it\n if next_state is None:\n policy_next_q = 0\n else:\n # write an expression for selecting an action using epsilon-greedy\n policy_action = epsilon_greedy(value[next_state], params['epsilon'])\n # write an expression for obtaining the value of the policy action at the \n # current state\n policy_next_q = value[next_state, policy_action]\n \n # write the expression to compute the TD error\n td_error = reward + params['gamma'] * policy_next_q - q \n # write the expression that updates the Q-value for the state-action pair \n value[state, action] = q + params['alpha'] * td_error\n \n return value\n```\n\nNow that we have an implementation for SARSA, let's see how it tackles Cliff World. We will again use the same setup we tried with Q-learning.\n\n\n```python\n# set for reproducibility, comment out / change seed value for different results\nnp.random.seed(1)\n\n# parameters needed by our policy and learning rule\nparams = {\n 'epsilon': 0.1, # epsilon-greedy policy\n 'alpha': 0.1, # learning rate \n 'gamma': 1.0, # discount factor\n}\n\n# episodes/trials\nn_episodes = 500\nmax_steps = 1000\n\n# environment initialization\nenv = CliffWorld()\n\n# learn Cliff World using Sarsa\nresults = learn_environment(env, sarsa, params, max_steps, n_episodes)\nvalue_sarsa, reward_sums_sarsa = results\n\n# Plot results\nplot_performance(env, value_sarsa, reward_sums_sarsa)\n```\n\nWe should see that SARSA also solves the task with similar looking outcomes to Q-learning. One notable difference is that SARSA seems to be skittsh around the cliff edge and often goes further away before coming back down to the goal.\n\nAgain, feel free to try changing the parameters or random seed and see how the agent's behavior changes.\n\n## On-Policy vs Off-Policy\n \nWe have now seen an example of both on- and off-policy learning algorithms. Let's compare both Q-learning and SARSA reward results again, side-by-side, to see how they stack up.\n\n\n```python\n# parameters needed by our policy and learning rule\nparams = {\n 'epsilon': 0.1, # epsilon-greedy policy\n 'alpha': 0.1, # learning rate \n 'gamma': 1.0, # discount factor\n}\n\n# episodes/trials\nn_episodes = 500\nmax_steps = 1000\n\n# environment initialization\nenv = CliffWorld()\n\n# learn Cliff World using Sarsa\nnp.random.seed(1)\nresults = learn_environment(env, q_learning, params, max_steps, n_episodes)\nvalue_qlearning, reward_sums_qlearning = results\nnp.random.seed(1)\nresults = learn_environment(env, sarsa, params, max_steps, n_episodes)\nvalue_sarsa, reward_sums_sarsa = results\n```\n\n\n```python\nfig, ax = plt.subplots()\nax.plot(reward_sums_qlearning, label='Q-learning')\nax.plot(reward_sums_sarsa, label='SARSA')\nax.set(xlabel='Episodes', ylabel='Total reward')\nplt.legend(loc='lower right');\n```\n\nOn this simple Cliff World task, Q-learning and SARSA are almost indistinguisable from a performance standpoint, but we can see that Q-learning has a slight-edge within the 500 episode time horizon. Let's look at the illustrated \"greedy policy\" plots again.\n\n\n```python\nfig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(16, 6))\nplot_quiver_max_action(env, value_qlearning, ax=ax1)\nax1.set(title='Q-learning maximum value/probability actions')\nplot_quiver_max_action(env, value_sarsa, ax=ax2)\nax2.set(title='SARSA maximum value/probability actions');\n```\n\nWhat should immediately jump out is that Q-learning learned to go up, then immediately go to the right, skirting the cliff edge, until it hits the wall and goes down to the goal. The policy further away from the cliff is less certain.\n\nSARSA, on the other hand, appears to avoid the cliff edge, going up one more tile before starting over to the goal side. This also clearly solves the challenge of getting to the goal, but does so at an additional -2 cost over the truly optimal route.\n\nWhy do you think these behaviors emerged the way they did?\n", "meta": {"hexsha": "8700302aefcacd2f160ff665338bf592b558a58d", "size": 826204, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W2D5_ReinforcementLearning/student/W2D5_Tutorial3.ipynb", "max_stars_repo_name": "hnoamany/course-content", "max_stars_repo_head_hexsha": "d89047537e57854c62cb9536a9c768b235fe4bf8", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/W2D5_ReinforcementLearning/student/W2D5_Tutorial3.ipynb", "max_issues_repo_name": "hnoamany/course-content", "max_issues_repo_head_hexsha": "d89047537e57854c62cb9536a9c768b235fe4bf8", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/W2D5_ReinforcementLearning/student/W2D5_Tutorial3.ipynb", "max_forks_repo_name": "hnoamany/course-content", "max_forks_repo_head_hexsha": "d89047537e57854c62cb9536a9c768b235fe4bf8", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 826204.0, "max_line_length": 826204, "alphanum_fraction": 0.9551248844, "converted": true, "num_tokens": 6358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34443737761101256}} {"text": "```python\nfrom IPython.display import Image \nImage('../../../python_for_probability_statistics_and_machine_learning.jpg')\n```\n\n\n\n\n \n\n \n\n\n\n# Support Vector Machines\n\nSupport Vector Machines (SVM) originated from the statistical learning theory\ndeveloped by Vapnik-Chervonenkis. As such, it represents a deep application of\nstatistical theory that incorporates the VC dimension concepts we\ndiscussed in the first section. Let's start by looking at some pictures.\nConsider the two-dimensional classification problem shown in\n[Figure](#fig:svm_001). [Figure](#fig:svm_001) shows two classes (gray and\nwhite\ncircles) that can be separated by any of the lines shown. Specifically, any\nsuch separating line can be written as the locus of points ($\\mathbf{x}$) in\nthe two-dimensional plane that satisfy the following,\n\n\n\n
\n\n

In the two-dimensional plane, the two classes (gray and white circles) are\neasily separated by any one of the lines shown.

\n\n\n\n\n$$\n\\beta_0 + \\boldsymbol{\\beta}^T \\mathbf{x} = 0\n$$\n\n To classify an arbitrary $\\mathbf{x}$ using this line, we just\ncompute the sign of $\\beta_0+\\boldsymbol{\\beta}^T \\mathbf{x}$ and assign one\nclass to the positive sign and the other class to the negative sign. To\nuniquely specify such a separating line (or, hyperplane in a higher-dimensional\nspace) we need additional criteria.\n\n\n[Figure](#fig:svm_002) shows the data with two bordering parallel lines that\nform a margin around the central separating line. The *maximal margin\nalgorithm* finds the widest margin and the unique separating line. As a\nconsequence, the algorithm uncovers the elements in the data that touch the\nmargins. These are the *support* elements. The other elements\naway from the border are not relevent to the solution. This reduces\nmodel variance because the solution is insensitive to the removal of\nelements other than these supporting elements (usually a small minority).\n\n\n\n
\n\n

The maximal margin algorithm finds the separating line that maximizes the\nmargin shown. The elements that touch the margins are the support elements. The\ndotted elements are not relevent to the solution.

\n\n\n\n\n\nTo see how this works for linearly separable classes, consider a\ntraining set consisting of $\\lbrace (\\mathbf{x},y) \\rbrace$ where\n$y\\in \\lbrace -1,1 \\rbrace$. For any point $\\mathbf{x}_i$, we\ncompute the functional margin as $\\hat{ \\gamma_i }=y_i (\\beta_0 +\n\\boldsymbol{\\beta}^T \\mathbf{x}_i)$. Thus, $\\hat{\\gamma}_i >0$ when\n$\\mathbf{x}_i$ is correctly classified. The geometrical margin is\n$\\gamma = \\hat{\\gamma}/\\lVert\\boldsymbol{\\beta}\\rVert$. When\n$\\mathbf{x}_i$ is correctly classified, the geometrical margin is\nequal to the perpendicular distance from $\\mathbf{x}_i$ to the line.\nLet's look see how the maximal margin algorithm works.\n\nLet $M$ be the width of the margin. The maximal margin algorithm is can be\nformulated as a quadratic programming problem. We want to simultaneously\nmaximize the margin $M$ while ensuring that all of the data points are\ncorrectly classified.\n\n$$\n\\begin{aligned}\n& \\underset{\\beta_0,\\boldsymbol{\\beta},\\lVert\\boldsymbol{\\beta}\\rVert=1}{\\text{m\naximize}}\n& & M \\\\\\\n& \\text{subject to:}\n& & y_i(\\beta_0+\\boldsymbol{\\beta}^T \\mathbf{x}_i) \\geq M, \\; i = 1, \\ldots, N.\n\\end{aligned}\n$$\n\n The first line says we want to generate a maximum value for $M$ by\nadjusting $\\beta_0$ and $\\boldsymbol{\\beta}$ while keeping\n$\\lVert\\boldsymbol{\\beta}\\rVert=1$. The functional margins for each $i^{th}$\ndata element are the constraints to the problem and must be satisfied for every\nproposed solution. In words, the constraints enforce that the elements have to\nbe correctly classified and outside of the margin around the separating line.\nWith some reformulation, it turns out that\n$M=1/\\lVert\\boldsymbol{\\beta}\\rVert$ and this can be put into the following\nstandard format,\n\n$$\n\\begin{aligned}\n& \\underset{\\beta_0,\\boldsymbol{\\beta}}{\\text{minimize}}\n& & \\lVert\\boldsymbol{\\beta}\\rVert \\\\\\\n& \\text{subject to:}\n& & y_i(\\beta_0+\\boldsymbol{\\beta}^T \\mathbf{x}_i) \\geq 1, \\; i = 1, \\ldots, N.\n\\end{aligned}\n$$\n\n This is a convex optimization problem and can be solved using\npowerful\nmethods in that area.\n\nThe situation becomes more complex when the two classes are not separable and\nwe have to allow some unavoidable mixing between the two classes in the\nsolution. This means that the contraints have to modified as in the following,\n\n$$\ny_i(\\beta_0+\\boldsymbol{\\beta}^T \\mathbf{x}_i) \\geq M(1-\\xi_i)\n$$\n\n where the $\\xi_i$ are the slack variables and represent the\nproportional amount tha the prediction is on the wrong side of the margin. Thus,\nelements are misclassified when $\\xi_i>1$. With these additional variables,\nwe have a more general formulation of the convex optimization problem,\n\n$$\n\\begin{aligned}\n& \\underset{\\beta_0,\\boldsymbol{\\beta}}{\\text{minimize}}\n& & \\lVert\\boldsymbol{\\beta}\\rVert \\\\\\\n& \\text{subject to:}\n& & y_i(\\beta_0+\\boldsymbol{\\beta}^T \\mathbf{x}_i) \\geq 1-\\xi_i, \\\\\\\n& & & \\xi_i \\geq 0, \\sum \\xi_i \\leq \\texttt{constant}, \\; i = 1, \\ldots, N.\n\\end{aligned}\n$$\n\n which can be rewritten in the following equivalent form,\n\n\n
\n\n$$\n\\begin{equation}\n\\begin{aligned}\n& \\underset{\\beta_0,\\boldsymbol{\\beta}}{\\text{minimize}}\n& & \\frac{1}{2}\\lVert\\boldsymbol{\\beta}\\rVert + C \\sum \\xi_i \\\\\\\n& \\text{subject to:}\n& & y_i(\\beta_0+\\boldsymbol{\\beta}^T \\mathbf{x}_i) \\geq 1-\\xi_i, \\xi_i \\geq 0 \\;\ni = 1, \\ldots, N.\n\\end{aligned}\n\\end{equation}\n\\label{eq:svm} \\tag{1}\n$$\n\n Because the $\\xi_i$ terms are all positive, the objective\nis to maximize the margin (i.e., minimize $\\lVert\\boldsymbol{\\beta}\\rVert$)\nwhile minimizing the proportional drift of the predictions to the wrong side\nof the margin (i.e., $C \\sum \\xi_i$). Thus, large values of $C$ shunt\nalgorithmic focus towards the correctly classified points near the\ndecision boundary and small values focus on further data. The value $C$ is\na hyperparameter for the SVM.\n\nThe good news is that all of these complicated pieces are handled neatly inside\nof Scikit-learn. The following sets up the linear *kernel* for the SVM (more on\nkernels soon),\n\n\n```python\nfrom sklearn.datasets import make_blobs\nfrom sklearn.svm import SVC\nsv = SVC(kernel='linear')\n```\n\nWe can create some synthetic data using `make_blobs` and then\nfit it to the SVM,\n\n\n```python\nX,y=make_blobs(n_samples=200, centers=2, n_features=2,\n random_state=0,cluster_std=.5)\nsv.fit(X,y)\n```\n\n\n\n\n SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n decision_function_shape='ovr', degree=3, gamma='auto', kernel='linear',\n max_iter=-1, probability=False, random_state=None, shrinking=True,\n tol=0.001, verbose=False)\n\n\n\nAfter fitting, the SVM now has the estimated support vectors and the\ncoefficients of the $\\boldsymbol{\\beta}$ in the `sv.support_vectors_` and\n`sv.coef_` attributes, respectively. [Figure](#fig:svm_003) shows the two\nsample classes (white and gray circles) and the line separating them that was\nfound by the maximal margin algorithm. The two parallel dotted lines show the\nmargin. The large circles enclose the support vectors, which are the data\nelements that are relevent to the solution. Notice that only these elements\ncan touch the edges of the margins.\n\n\n```python\n%matplotlib inline\n\nfrom matplotlib.pylab import subplots\nimport numpy as np\nxi = np.linspace(X[:,0].min(),X[:,0].max(),100)\n\nfig,ax=subplots()\n_=ax.scatter(X[:,0],X[:,1],c=y,s=50,cmap='gray',marker='o',alpha=.3)\n_=ax.plot(sv.support_vectors_[:,0],sv.support_vectors_[:,1],'ko',markersize=20,alpha=.2)\n_=ax.plot(xi,-sv.coef_[0,0]/sv.coef_[0,1]*xi- sv.intercept_/sv.coef_[0,1],'k',lw=3.)\nmargin = np.linalg.norm(sv.coef_)\n_=ax.plot(xi,-sv.coef_[0,0]/sv.coef_[0,1]*xi-(sv.intercept_+margin/2.)/sv.coef_[0,1],'--k',lw=3.)\n_=ax.plot(xi,-sv.coef_[0,0]/sv.coef_[0,1]*xi-(sv.intercept_-margin/2.)/sv.coef_[0,1],'--k',lw=3.)\n```\n\n\n\n
\n\n

The two class shown (white and gray circles) are linearly separable. The\nmaximal margin solution is shown by the dark black line in the middle. The\ndotted lines show the extent of the margin. The large circles indicate the\nsupport vectors for the maximal margin solution.

\n\n\n\n\n\n```python\n\ndef draw_margins(sv,X,y,ax=None):\n sv.fit(X,y)\n xi = np.linspace(X[:,0].min(),X[:,0].max(),100)\n if ax is None: fig,ax=subplots()\n _=ax.scatter(X[:,0],X[:,1],c=y,s=50,cmap='gray',marker='o',alpha=.3)\n _=ax.plot(sv.support_vectors_[:,0],sv.support_vectors_[:,1],'ko',markersize=20,alpha=.2)\n _=ax.plot(xi,-sv.coef_[0,0]/sv.coef_[0,1]*xi- sv.intercept_/sv.coef_[0,1],'k',lw=3.)\n margin = np.linalg.norm(sv.coef_)\n _=ax.plot(xi,-sv.coef_[0,0]/sv.coef_[0,1]*xi- (sv.intercept_+margin/2.)/sv.coef_[0,1],'--k',lw=3.)\n _=ax.plot(xi,-sv.coef_[0,0]/sv.coef_[0,1]*xi- (sv.intercept_-margin/2.)/sv.coef_[0,1],'--k',lw=3.)\n```\n\n\n```python\n\nX, y = make_blobs(n_samples=50, centers=2, n_features=2,\n cluster_std=1,random_state=0)\n\nfig,axs = subplots(2,2,sharex=True,sharey=True)\n#fig.set_size_inches((12,6))\nsv = SVC(kernel='linear',C=.0100)\ndraw_margins(sv,X,y,ax=axs[0,0])\n_=axs[0,0].set_title('C=0.01')\nsv = SVC(kernel='linear',C=1)\ndraw_margins(sv,X,y,ax=axs[0,1])\n_=axs[0,1].set_title('C=1')\nsv = SVC(kernel='linear',C=100)\ndraw_margins(sv,X,y,ax=axs[1,0])\n_=axs[1,0].set_title('C=100')\nsv = SVC(kernel='linear',C=10000)\ndraw_margins(sv,X,y,ax=axs[1,1])\n_=axs[1,1].set_title('C=10000')\n```\n\n[Figure](#fig:svm_004) shows what happens when the value of $C$ changes.\nIncreasing this value emphasizes the $\\xi$ part of the objective function in\nEquation [eq:svm](#eq:svm). As shown in the top left panel, a small value for\n$C$ means that\nthe algorithm is willing to accept many support vectors at the expense of\nmaximizing the margin. That is, the proportional amount that predictions are on\nthe wrong side of the margin is more acceptable with smaller $C$. As the value\nof $C$ increases, there are fewer support vectors because the optimization\nprocess prefers to eliminate support vectors that are far away from the margins\nand accept fewer of these that encroach into the margin. Note that as the value\nof $C$ progresses through this figure, the separating line tilts slightly.\n\n\n\n
\n\n

The maximal margin algorithm finds the separating line that maximizes the\nmargin shown. The elements that touch the margins are the support elements. The\ndotted elements are not relevent to the solution.

\n\n\n\n\n\n## Kernel Tricks\n\nSupport Vector Machines provide a powerful method to deal with linear\nseparations, but they can also apply to non-linear boundaries by\nexploiting the so-called *kernel trick*. The convex optimization\nformulation of the SVM includes a *dual* formulation that leads to a\nsolution that requires only the inner-products of the features. The\nkernel trick is to substitute inner-products by nonlinear kernel\nfunctions. This can be thought of as mapping the original features\nonto a possibly infinite dimensional space of new features. That is,\nif the data are not linearly separable in two-dimensional space (for\nexample) maybe they are separable in three-dimensional space (or\nhigher)?\n\nTo make this concrete, suppose the original input space is\n$\\mathbb{R}^n$ and we want to use a non-linear mapping\n$\\psi:\\mathbf{x} \\mapsto \\mathcal{F}$ where $\\mathcal{F}$ is an\ninner-product space of higher dimension. The kernel trick is to\ncalculate the inner-product in $\\mathcal{F}$ using a kernel\nfunction, $K(\\mathbf{x}_i,\\mathbf{x}_j) = \\langle\n\\psi(\\mathbf{x}_i),\\psi(\\mathbf{x}_j)\\rangle$. The long way to\ncompute this is to first compute $\\psi(\\mathbf{x})$ and then do the\ninner-product. The kernel-trick way to do it is to use the kernel\nfunction and avoid computing $\\psi$. In other words, the kernel\nfunction returns what the inner-product in $\\mathcal{F}$ would have\nreturned if $\\psi$ had been applied. For example, to achieve an\n$n^{th}$ polynomial mapping of the input space, we can use\n$\\kappa(\\mathbf{x}_i,\\mathbf{x}_j)=(\\mathbf{x}_i^T\\mathbf{x}_j+\\theta)^n$.\nFor example, suppose the input space is $\\mathbb{R}^2$ and\n$\\mathcal{F}=\\mathbb{R}^4$ and we have the following mapping,\n\n$$\n\\psi(\\mathbf{x}) : (x_0,x_1) \\mapsto (x_0^2,x_1^2,x_0 x_1, x_1 x_0)\n$$\n\n The inner product in $\\mathcal{F}$ is then,\n\n$$\n\\langle \\psi(\\mathbf{x}),\\psi(\\mathbf{y}) \\rangle = \\langle\n\\mathbf{x},\\mathbf{y} \\rangle^2\n$$\n\n In other words, the kernel is the square of the inner\nproduct in input space. The advantage of using the kernel instead of\nsimply enlarging the feature space is computational because you only\nneed to compute the kernel on all distinct pairs of the input space.\nThe following example should help make this concrete. First we create\nsome Sympy variables,\n\n\n```python\nimport sympy as S\nx0,x1=S.symbols('x:2',real=True)\ny0,y1=S.symbols('y:2',real=True)\n```\n\nNext, we create the $\\psi$ function that maps into $\\mathbb{R}^4$\nand the corresponding kernel function,\n\n\n```python\npsi = lambda x,y: (x**2,y**2,x*y,x*y)\nkern = lambda x,y: S.Matrix(x).dot(y)**2\n```\n\nNotice that the inner product in $\\mathbb{R}^4$ is\nequal to the kernel function, which only uses wthe $\\mathbb{R}^2$\nvariables.\n\n\n```python\nprint(S.Matrix(psi(x0,x1)).dot(psi(y0,y1)))\nprint(S.expand(kern((x0,x1),(y0,y1)))) # same as above\n```\n\n x0**2*y0**2 + 2*x0*x1*y0*y1 + x1**2*y1**2\n x0**2*y0**2 + 2*x0*x1*y0*y1 + x1**2*y1**2\n\n\n**Polynomial Regression Using Kernels.** Recall our favorite\nlinear regression problem from the regularization chapter,\n\n$$\n\\min_{\\boldsymbol{\\beta}} \\Vert y - \\mathbf{X}\\boldsymbol{\\beta}\\Vert^2\n$$\n\n where $\\mathbf{X}$ is a $n\\times m$ matrix with $m>n$. As\nwe discussed, there are multiple solutions to this problem. The\nleast-squares solution is the following:\n\n$$\n\\boldsymbol{\\beta}_{LS}=\\mathbf{X}^T(\\mathbf{X}\\mathbf{X}^T)^{\\text{-1}}\\mathbf{\ny}\n$$\n\n Given a new feature vector $\\mathbf{x}$, the corresponding estimator\nfor $\\mathbf{y}$ is the following,\n\n$$\n\\hat{\\mathbf{y}} = \\mathbf{x}^T\\boldsymbol{\\beta}_{LS}=\\mathbf{x}^T\\mathbf{X}^T(\n\\mathbf{X}\\mathbf{X}^T)^{\\text{-1}}\\mathbf{y}\n$$\n\n Using the kernel trick, the solution can be written more generally as\nthe following,\n\n$$\n\\hat{\\mathbf{y}}=\\mathbf{k}(\\mathbf{x})^T\\mathbf{K}^{\\text{-1}}\\mathbf{y}\n$$\n\n where the $n\\times n$ kernel matrix $\\mathbf{K}$ replaces\n$\\mathbf{X}\\mathbf{X}^T$ and where $\\mathbf{k}(\\mathbf{x})$ is a $n$-vector of\ncomponents $\\mathbf{k}(\\mathbf{x})=[\\kappa(\\mathbf{x}_i,\\mathbf{x})]$ and where\n$\\mathbf{K}_{i,j}=\\kappa(\\mathbf{x}_i,\\mathbf{x}_j)$ for the kernel function\n$\\kappa$. With this more general setup, we can substitute\n$\\kappa(\\mathbf{x}_i,\\mathbf{x}_j)=(\\mathbf{x}_i^T\\mathbf{x}_j+\\theta)^n$ for\n$n^{th}$-order polynomial regression [[bauckhagenumpy]](#bauckhagenumpy). Note\nthat ridge\nregression can also be incorporated by inverting $(\\mathbf{K}+\\alpha\n\\mathbf{I})$, which can help stabilize poorly conditioned $\\mathbf{K}$ matrices\nwith a tunable $\\alpha$ hyper-parameter [[bauckhagenumpy]](#bauckhagenumpy).\n\nFor some kernels, the enlarged $\\mathcal{F}$ space is infinite-dimensional.\nMercer's conditions provide technical restrictions on the kernel functions.\nPowerful, well-studied kernels have been implemented in Scikit-learn. The\nadvantage of kernel functions may evaporate for when $n\\rightarrow m$ in which\ncase using the $\\psi$ functions instead can be more practicable.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n```python\nfrom matplotlib.pylab import cm\nxi = np.linspace(X[:,0].min(),X[:,0].max(),100)\nyi = np.linspace(X[:,1].min(),X[:,1].max(),100)\n\nfig,ax=subplots()\n_=ax.scatter(X[:,0],X[:,1],c=y,s=50,cmap='gray',marker='o',alpha=.3)\nXi,Yi = np.meshgrid(xi,yi)\nZi=sv.predict(np.c_[Xi.ravel(),Yi.ravel()]).reshape(Xi.shape)\n\n_=ax.contourf(Xi,Yi,Zi,cmap=cm.Paired,alpha=0.2);\n```\n", "meta": {"hexsha": "8bf326becb141dc929f1ec4ead3eac5c14561ade", "size": 236626, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "chapters/machine_learning/notebooks/svm.ipynb", "max_stars_repo_name": "nsydn/Python-for-Probability-Statistics-and-Machine-Learning", "max_stars_repo_head_hexsha": "d3e0f8ea475525a694a975dbfd2bf80bc2967cc6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 570, "max_stars_repo_stars_event_min_datetime": "2016-05-05T19:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:09:19.000Z", "max_issues_repo_path": "chapters/machine_learning/notebooks/svm.ipynb", "max_issues_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_issues_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2016-05-12T22:18:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-06T14:37:06.000Z", "max_forks_repo_path": "chapters/machine_learning/notebooks/svm.ipynb", "max_forks_repo_name": "crlsmcl/https-github.com-unpingco-Python-for-Probability-Statistics-and-Machine-Learning", "max_forks_repo_head_hexsha": "6fd69459a28c0b76b37fad79b7e8e430d09a86a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 276, "max_forks_repo_forks_event_min_datetime": "2016-05-27T01:42:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:20:27.000Z", "avg_line_length": 341.9450867052, "max_line_length": 114721, "alphanum_fraction": 0.9165856668, "converted": true, "num_tokens": 5402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.3443218126173266}} {"text": "```python\n# This cell is mandatory in all Dymos documentation notebooks.\nmissing_packages = []\ntry:\n import openmdao.api as om\nexcept ImportError:\n if 'google.colab' in str(get_ipython()):\n !python -m pip install openmdao[notebooks]\n else:\n missing_packages.append('openmdao')\ntry:\n import dymos as dm\nexcept ImportError:\n if 'google.colab' in str(get_ipython()):\n !python -m pip install dymos\n else:\n missing_packages.append('dymos')\ntry:\n import pyoptsparse\nexcept ImportError:\n if 'google.colab' in str(get_ipython()):\n !pip install -q condacolab\n import condacolab\n condacolab.install_miniconda()\n !conda install -c conda-forge pyoptsparse\n else:\n missing_packages.append('pyoptsparse')\nif missing_packages:\n raise EnvironmentError('This notebook requires the following packages '\n 'please install them and restart this notebook\\'s runtime: {\",\".join(missing_packages)}')\n```\n\n(examples:bryson_denham)=\n# The Bryson-Denham Problem\n\nThe Bryson-Denham problem is a variation of the double integrator problem {cite}`bryson1975applied`. It can be stated as:\n\nMinimize the control effort required to reverse the direction of motion of a frictionless sliding block such that the reversal happens with some limited amount of displacement.\n\n## State and control variables\n\nThis system has two state variables, the position ($x$) and velocity ($v$) of the sliding block. \n\nThis system has a single control variable ($u$), the acceleration of the block.\n\nThe dynamics of the system are governed by\n\n\\begin{align}\n \\dot{x} &= v \\\\\n \\dot{v} &= u\n\\end{align}\n\n\n\n## Problem Definition\n\nWe seek to minimize the time required to exit the well in the positive direction.\n\n\\begin{align}\n \\mathrm{Minimize} \\, J &= 0.5 \\int_0^1 u^2 dt\n\\end{align}\n\nSubject to the initial conditions\n\n\\begin{align}\n x_0 &= 0.0 \\\\\n v_0 &= 1.0\n\\end{align}\n\nand the terminal constraints\n\n\\begin{align}\n x_f &= 0.0 \\\\\n v_f &= -1.0\n\\end{align}\n\nIn addition, $x$ is consrained to remain below a displacement of 1/9.\n\n\\begin{align}\n x &\\le 1/9\n\\end{align}\n\n## Dealing with integral costs in Dymos\n\nIn classic optimal control, the objective is often broken into the terminal component (the Mayer term) and the integral component (the Lagrange term).\nDymos does not distinguish between the two.\nIn this case, since the objective $J$ is an integrated quantity, we add a term to the ODE\n\n\\begin{align}\n\\dot{J} &= 0.5 u^2\n\\end{align}\n\n## Defining the ODE\n\nThe following code implements the equations of motion for the mountain car problem.\nSince the rate of $x$ is given by another state ($v$), and the rate of $v$ is given by a control ($u$), there is no need to compute their rates in the ODE.\nDymos can pull their values from those other states and controls.\nThe ODE, therefore, only needs to compute the rate of change of $J$.\n\nA few things to note:\n\n1. By providing the tag `dymos.state_rate_source:{name}`, we're letting Dymos know what states need to be integrated, there's no need to specify a rate source when using this ODE in our Phase.\n2. Pairing the above tag with `dymos.state_units:{units}` means we don't have to specify units when setting properties for the state in our run script.\n\n\n```python\nimport numpy as np\nimport openmdao.api as om\n\n\nclass BrysonDenhamODE(om.ExplicitComponent):\n \n def initialize(self):\n self.options.declare('num_nodes', types=int)\n \n def setup(self):\n nn = self.options['num_nodes']\n \n self.add_input('x', shape=(nn,), units='m')\n self.add_input('v', shape=(nn,), units='m/s')\n self.add_input('u', shape=(nn,), units='m/s**2')\n \n self.add_output('J_dot', shape=(nn,), units='m**2/s**4',\n tags=['dymos.state_rate_source:J',\n 'dymos.state_units:m**2/s**3'])\n \n ar = np.arange(nn, dtype=int)\n \n self.declare_partials(of='J_dot', wrt='u', rows=ar, cols=ar)\n\n def compute(self, inputs, outputs):\n u = inputs['u']\n outputs['J_dot'] = 0.5 * u**2\n\n def compute_partials(self, inputs, partials):\n partials['J_dot', 'u'] = inputs['u']\n \n```\n\n## Solving the Bryson-Denham problem with Dymos\n\nThe following script solves the minimum-time mountain car problem with Dymos.\nThis problem is pretty trivial and can be solved using the SLSQP optimizer in scipy.\n\nTo begin, import the packages we require:\n\n\n```python\nimport dymos as dm\nimport matplotlib.pyplot as plt\n```\n\nWe then instantiate an OpenMDAO problem and set the optimizer and its options.\n\nThe call to `declare_coloring` tells the optimizer to attempt to find a sparsity pattern that minimizes the work required to compute the derivatives across the model.\n\nSLSQP does not internally use this sparsity information to reduce memory and improve performance as some other optimizers do, but the performance due to the increased efficiency in computing derivatives still makes it worthwhile.\n\n\n```python\n#\n# Initialize the Problem and the optimization driver\n#\np = om.Problem()\n \np.driver = om.ScipyOptimizeDriver()\np.driver.declare_coloring()\n```\n\nNext, we add a Dymos Trajectory group to the problem's model and add a phase to it.\n\nIn this case we're using the Radau pseudospectral transcription to solve the problem.\n\n\n```python\n#\n# Create a trajectory and add a phase to it\n#\ntraj = p.model.add_subsystem('traj', dm.Trajectory())\ntx = transcription=dm.Radau(num_segments=24)\nphase = traj.add_phase('phase0', dm.Phase(ode_class=BrysonDenhamODE, transcription=tx))\n```\n\nAt this point, we set the options on the main variables used in a Dymos phase. \n\nIn addition to `time`, we have three states (`x`, `v`, and `J`) and a single control (`u`). \n\nHere we use bounds on the states themselves to constrain the initial and final value of `x` and1 `v`, and the initial value of `J`.\nFrom an optimization perspective, this means that we are removing the first and last values in the state histories of $x$ and $v$ from the vector of design variables.\nTheir initial and final values will remain unchanged throughout the optimization process.\n\nOn the other hand, we could specify `fix_initial=False, fix_final=False` for these values, and Dymos would be free to change them.\nWe would then need to put a boundary constraint in place to enforce their final values.\nFeel free to experiment with different ways of enforcing the boundary constraints on this problem and see how it affects performance.\n\nThe scaler values (`ref`) are all set to 1 here.\n\nBounds on time duration are guesses, and the bounds on the states and controls come from the implementation in the references.\n\nAlso, we don't need to specify targets for any of the variables here because their names _are_ the targets in the top-level of the model.\nThe rate source and units for the states are obtained from the tags in the ODE component we previously defined.\n\n\n```python\n#\n# Set the variables\n#\nphase.set_time_options(fix_initial=True, fix_duration=True)\n\nphase.add_state('x', fix_initial=True, fix_final=True, rate_source='v')\nphase.add_state('v', fix_initial=True, fix_final=True, rate_source='u')\nphase.add_state('J', fix_initial=True, fix_final=False) # Rate source obtained from tags on the ODE outputs\nphase.add_control('u', continuity=True, rate_continuity=False)\n```\n\n\n```python\n#\n# Minimize time at the end of the phase\n#\nphase.add_objective('J', loc='final', ref=1)\nphase.add_path_constraint('x', upper=1/9)\n\n#\n# Setup the Problem\n#\np.setup()\n```\n\nWe then set the initial guesses for the variables in the problem and solve it.\n\nWe're using the phase `interp` method to provide initial guesses for the states and controls.\nIn this case, by giving it two values, it is linearly interpolating from the first value to the second value, and then returning the interpolated value at the input nodes for the given variable.\n\nFinally, we use the `dymos.run_problem` method to execute the problem.\nThis interface allows us to do some things that the standard OpenMDAO `problem.run_driver` interface does not.\nIt will automatically record the final solution achieved by the optimizer in case named `'final'` in a file called `dymos_solution.db`.\nBy specifying `simulate=True`, it will automatically follow the solution with an explicit integration using `scipy.solve_ivp`.\nThe results of the simulation are stored in a case named `final` in the file `dymos_simulation.db`.\nThis explicit simulation demonstrates how the system evolved with the given controls, and serves as a check that we're using a dense enough grid (enough segments and segments of sufficient order) to accurately represent the solution.\n\nIf those two solution didn't agree reasonably well, we could rerun the problem with a more dense grid.\nInstead, we're asking Dymos to automatically change the grid if necessary by specifying `refine_method='ph'`.\nThis will attempt to repeatedly solve the problem and change the number of segments and segment orders until the solution is in reasonable agreement.\n\n\n```python\n#\n# Set the initial values\n#\np['traj.phase0.t_initial'] = 0.0\np['traj.phase0.t_duration'] = 1.0\n\np.set_val('traj.phase0.states:x', phase.interp('x', ys=[0, 0]))\np.set_val('traj.phase0.states:v', phase.interp('v', ys=[1, -1]))\np.set_val('traj.phase0.states:J', phase.interp('J', ys=[0, 1]))\np.set_val('traj.phase0.controls:u', np.sin(phase.interp('u', ys=[0, 0])))\n\n#\n# Solve for the optimal trajectory\n#\ndm.run_problem(p, run_driver=True, simulate=True)\n\n```\n\n## Plotting the solution\n\nThe recommended practice is to obtain values from the recorded cases.\nWhile the problem object can also be queried for values, building plotting scripts that use the case recorder files as the data source means that the problem doesn't need to be solved just to change a plot.\nHere we load values of various variables from the solution and simulation for use in the animation to follow.\n\n\n```python\nsol = om.CaseReader('dymos_solution.db').get_case('final')\nsim = om.CaseReader('dymos_simulation.db').get_case('final')\n\nt = sol.get_val('traj.phase0.timeseries.time')\nx = sol.get_val('traj.phase0.timeseries.states:x')\nv = sol.get_val('traj.phase0.timeseries.states:v')\nJ = sol.get_val('traj.phase0.timeseries.states:J')\nu = sol.get_val('traj.phase0.timeseries.controls:u')\nh = np.sin(3 * x) / 3\n\nt_sim = sim.get_val('traj.phase0.timeseries.time')\nx_sim = sim.get_val('traj.phase0.timeseries.states:x')\nv_sim = sim.get_val('traj.phase0.timeseries.states:v')\nJ_sim = sim.get_val('traj.phase0.timeseries.states:J')\nu_sim = sim.get_val('traj.phase0.timeseries.controls:u')\nh_sim = np.sin(3 * x_sim) / 3\n\nfig = plt.figure(constrained_layout=True, figsize=(12, 4))\ngs = fig.add_gridspec(2, 2)\n\nx_ax = fig.add_subplot(gs[0, 0])\nv_ax = fig.add_subplot(gs[1, 0])\nJ_ax = fig.add_subplot(gs[0, 1])\nu_ax = fig.add_subplot(gs[1, 1])\n\nx_ax.set_ylabel('x ($m$)')\nv_ax.set_ylabel('v ($m/s$)')\nJ_ax.set_ylabel('J ($m^2$/s^3$)')\nu_ax.set_ylabel('u ($m/s^2$)')\nv_ax.set_xlabel('t (s)')\nu_ax.set_xlabel('t (s)')\n\nx_sol_handle, = x_ax.plot(t, x, 'o', ms=1)\nv_ax.plot(t, v, 'o', ms=1)\nJ_ax.plot(t, J, 'o', ms=1)\nu_ax.plot(t, u, 'o', ms=1)\n\nx_sim_handle, = x_ax.plot(t_sim, x_sim, '-', ms=1)\nv_ax.plot(t_sim, v_sim, '-', ms=1)\nJ_ax.plot(t_sim, J_sim, '-', ms=1)\nu_ax.plot(t_sim, u_sim, '-', ms=1)\n\nfor ax in [x_ax, v_ax, J_ax, u_ax]:\n ax.grid(True, alpha=0.2)\n \nplt.figlegend([x_sol_handle, x_sim_handle], ['solution', 'simulation'], ncol=2, loc='lower center');\n\n\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\nassert_near_equal(J[-1, 0], 4.0, tolerance=1.0E-3)\n```\n\n## Animating the Solution\n\nThe collapsed code cell below contains the code used to produce an animation of the mountain car solution using Matplotlib.\n\nThe green area represents the hilly terrain the car is traversing. The black circle is the center of the car, and the orange arrow is the applied control.\n\nThe applied control _generally_ has the same sign as the velocity and is 'bang-bang', that is, it wants to be at its maximum possible magnitude. Interestingly, the sign of the control flips shortly before the sign of the velocity changes.\n\n\n```python\nimport matplotlib as mpl\nfrom matplotlib import animation\n\nBLOCK_SIZE = 0.02\nX_EXTENTS = (-0.025, 0.175)\n\nfig = plt.figure(constrained_layout=True, figsize=(12, 6))\ngs = fig.add_gridspec(3, 2)\n\nanim_ax = fig.add_subplot(gs[:, 0])\nanim_ax.set_aspect('equal')\n\nx_ax = fig.add_subplot(gs[0, 1:])\nv_ax = fig.add_subplot(gs[1, 1:])\nu_ax = fig.add_subplot(gs[2, 1:])\n\nx_ax.set_ylabel('x')\nv_ax.set_ylabel('v')\nu_ax.set_ylabel('u')\nu_ax.set_xlabel('t')\n\n# set up the subplots as needed\nanim_ax.set_xlim(X_EXTENTS);\ny_extents = [-np.diff(X_EXTENTS) / 2, np.diff(X_EXTENTS) / 2]\nanim_ax.set_ylim(y_extents);\nanim_ax.set_xlabel('x');\nanim_ax.set_yticks([])\ntime_text = anim_ax.text(0.05, 0.9, 't = 0.000 s', fontsize=16, transform=anim_ax.transAxes)\n\nx_sol_line, = x_ax.plot(t, x, 'o', ms=1, label='solution', color='k')\nv_ax.plot(t, v, 'o', ms=1, color='k')\nu_ax.plot(t, u, 'o', ms=1, color='k')\n\nx_sim_line, = x_ax.plot([], [], '-', linewidth=3, label='simulation', color='tab:blue')\nv_sim_line, = v_ax.plot([], [], '-', linewidth=3, color='tab:red')\nu_sim_line, = u_ax.plot([], [], '-', linewidth=3, color='tab:orange')\n\nplt.figlegend(ncol=2, handles=[x_sol_line, x_sim_line], loc='upper center',\n bbox_to_anchor=(0.78,0.98))\n\nx_ax.grid(alpha=0.2)\ntxt_x = x_ax.text(0.8, 0.1, f'x = {x_sim[0, 0]:6.3f}', horizontalalignment='left',\n verticalalignment='center', transform=x_ax.transAxes)\n\nv_ax.grid(alpha=0.2)\ntxt_v = v_ax.text(0.8, 0.1, f'v = {v_sim[0, 0]:6.3f}', horizontalalignment='left',\n verticalalignment='center', transform=v_ax.transAxes)\n\nu_ax.grid(alpha=0.2)\ntxt_u = u_ax.text(0.8, 0.1, f'u = {u_sim[0, 0]:6.3f}', horizontalalignment='left',\n verticalalignment='center', transform=u_ax.transAxes)\n\nx_terrain = np.linspace(-0.025, 0.175, 2);\nh_terrain = 0 * x_terrain\nterrain_line, = anim_ax.plot(x_terrain, h_terrain, '-', color='tab:gray', lw=2);\nterrain = anim_ax.fill_between(x_terrain, h_terrain, h_terrain-1, color='tab:green');\nwall = mpl.patches.Rectangle(xy=(1/9 + BLOCK_SIZE, 0), width=BLOCK_SIZE, height=3*BLOCK_SIZE, color='tab:gray')\nanim_ax.add_patch(wall)\nblock = mpl.patches.Rectangle(xy=(0, 0), width=BLOCK_SIZE, height=BLOCK_SIZE, alpha=0.5)\nanim_ax.add_patch(block)\nv_vec = anim_ax.quiver(x_sim[0,0] + BLOCK_SIZE / 2, BLOCK_SIZE * 0.25, v_sim[0,0], [0], scale=10, angles='xy', color='tab:red')\nu_vec = anim_ax.quiver(x_sim[0,0] + BLOCK_SIZE / 2, BLOCK_SIZE * 0.75, u_sim[0,0], [0], scale=50, angles='xy', color='tab:orange')\n\n# See https://brushingupscience.com/2019/08/01/elaborate-matplotlib-animations/ for quiver animation\n\nANIM_DURATION = 3\nPRE_PAUSE_DURATION = 1\nPOST_PAUSE_DURATION = 0.5\nANIM_FPS = 20\n\nnum_points = t_sim.size\nnum_frames = int(ANIM_DURATION * ANIM_FPS)\npre_pause_frames = int(PRE_PAUSE_DURATION * ANIM_FPS)\npost_pause_frames = int(POST_PAUSE_DURATION * ANIM_FPS)\n\nidx_from_frame_num = np.linspace(0, num_points-1, num_frames, dtype=int)\n\ndef drawframe(n):\n\n if n < pre_pause_frames:\n idx = 0\n elif n - pre_pause_frames >= idx_from_frame_num.size:\n idx = num_points - 1\n else:\n idx = idx_from_frame_num[n - pre_pause_frames]\n\n x = x_sim[idx]\n v = v_sim[idx]\n u = u_sim[idx]\n t = t_sim[idx]\n h = 0\n block.set_xy((x[0], h))\n \n v_vec.set_offsets((x[0] + BLOCK_SIZE/2, BLOCK_SIZE * 0.25))\n v_vec.set_UVC(v, 0)\n\n u_vec.set_offsets((x[0] + BLOCK_SIZE/2, BLOCK_SIZE * 0.75))\n u_vec.set_UVC(u, 0)\n\n x_sim_line.set_data(t_sim[:idx], x_sim[:idx])\n v_sim_line.set_data(t_sim[:idx], v_sim[:idx])\n u_sim_line.set_data(t_sim[:idx], u_sim[:idx])\n\n txt_x.set_text(f'x = {x[0]:6.3f}')\n txt_v.set_text(f'v = {v[0]:6.3f}')\n txt_u.set_text(f'u = {u[0]:6.3f}')\n \n time_text.set_text(f't = {t[0]:6.3f}')\n \n return block, u_vec, v_vec, x_sim_line, v_sim_line, u_sim_line, time_text\n\n# # blit=True re-draws only the parts that have changed.\n# # repeat_delay has no effect when using to_jshtml, so pad drawframe to show the final frame for PAUSE_FRAMES extra frames.\nanim = animation.FuncAnimation(fig, drawframe, frames=pre_pause_frames + num_frames + post_pause_frames, interval=1000/ANIM_FPS, blit=True);\nplt.close() # Don't let jupyter display the un-animated plot\n\nfrom IPython.display import HTML\nwith open('anim.html', 'w') as f:\n f.write(anim.to_jshtml())\nHTML('anim.html')\n```\n\n## References\n\n```{bibliography}\n:filter: docname in docnames\n```\n", "meta": {"hexsha": "4cb424ad03dcc95cb0ebdba37f08bc61a0d87f7e", "size": 25003, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/dymos_book/examples/bryson_denham/bryson_denham.ipynb", "max_stars_repo_name": "yonghoonlee/dymos", "max_stars_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/dymos_book/examples/bryson_denham/bryson_denham.ipynb", "max_issues_repo_name": "yonghoonlee/dymos", "max_issues_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9, "max_issues_repo_issues_event_min_datetime": "2021-05-24T15:14:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T21:12:55.000Z", "max_forks_repo_path": "docs/dymos_book/examples/bryson_denham/bryson_denham.ipynb", "max_forks_repo_name": "yonghoonlee/dymos", "max_forks_repo_head_hexsha": "602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1165730337, "max_line_length": 245, "alphanum_fraction": 0.5810102788, "converted": true, "num_tokens": 4611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.34411649504631336}} {"text": "\n\n\n# Tutorial-IllinoisGRMHD: harm_u2p_util.c\n\n## Authors: Leo Werneck & Zach Etienne\n\n**This module is currently under development**\n\n## In this tutorial module we explain the utility functions needed by the conservative-to-primitive algorithm used by `HARM`. This module will likely be absorbed by another one once we finish documenting the code.\n\n### Required and recommended citations:\n\n* **(Required)** Etienne, Z. B., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L. IllinoisGRMHD: an open-source, user-friendly GRMHD code for dynamical spacetimes. Class. Quantum Grav. 32 (2015) 175009. ([arxiv:1501.07276](http://arxiv.org/abs/1501.07276)).\n* **(Required)** Noble, S. C., Gammie, C. F., McKinney, J. C., Del Zanna, L. Primitive Variable Solvers for Conservative General Relativistic Magnetohydrodynamics. Astrophysical Journal, 641, 626 (2006) ([astro-ph/0512420](https://arxiv.org/abs/astro-ph/0512420)).\n* **(Recommended)** Del Zanna, L., Bucciantini N., Londrillo, P. An efficient shock-capturing central-type scheme for multidimensional relativistic flows - II. Magnetohydrodynamics. A&A 400 (2) 397-413 (2003). DOI: 10.1051/0004-6361:20021641 ([astro-ph/0210618](https://arxiv.org/abs/astro-ph/0210618)).\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis module is organized as follows\n\n0. [Step 0](#src_dir): **Source directory creation**\n1. [Step 1](#introduction): **Introduction**\n1. [Step 2](#harm_utoprim_2d__c__eos_indep): **EOS independent routines**\n 1. [Step 2.a](#raise_g): *The `raise_g()` function*\n 1. [Step 2.b](#lower_g): *The `lower_g()` function*\n 1. [Step 2.c](#ncov_calc): *The `ncov_calc()` function*\n1. [Step 3](#harm_utoprim_2d__c__eos_dep): **EOS dependent routines**\n 1. [Step 3.a](#pressure_rho0_u): *The `pressure_rho0_u()` function*\n 1. [Step 3.b](#pressure_rho0_w): *The `pressure_rho0_w()` function*\n1. [Step n-1](#code_validation): **Code validation**\n1. [Step n](#latex_pdf_output): **Output this notebook to $\\LaTeX$-formatted PDF file**\n\n\n\n# Step 0: Source directory creation \\[Back to [top](#toc)\\]\n$$\\label{src_dir}$$\n\nWe will now use the [cmdline_helper.py NRPy+ module](Tutorial-Tutorial-cmdline_helper.ipynb) to create the source directory within the `IllinoisGRMHD` NRPy+ directory, if it does not exist yet.\n\n\n```python\n# Step 0: Creation of the IllinoisGRMHD source directory\n# Step 0a: Add NRPy's directory to the path\n# https://stackoverflow.com/questions/16780014/import-file-from-parent-directory\nimport os,sys\nnrpy_dir_path = os.path.join(\"..\",\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Step 0b: Load up cmdline_helper and create the directory\nimport cmdline_helper as cmd\nIGM_src_dir_path = os.path.join(\"..\",\"src\")\ncmd.mkdir(IGM_src_dir_path)\n\n# Step 0c: Create the output file path \noutfile_path__harm_u2p_util__c = os.path.join(IGM_src_dir_path,\"harm_u2p_util.c\")\n```\n\n\n\n# Step 1: Introduction \\[Back to [top](#toc)\\]\n$$\\label{introduction}$$\n\n\n\n# Step 2: EOS independent routines` \\[Back to [top](#toc)\\]\n$$\\label{harm_utoprim_2d__c__eos_indep}$$\n\n\n```python\n%%writefile $outfile_path__harm_u2p_util__c\n#ifndef __HARM_U2P_UTIL__C__\n#define __HARM_U2P_UTIL__C__\n/*\n -------------------------------------------------------------------------------\n Copyright 2005 Scott C. Noble, Charles F. Gammie, \n Jonathan C. McKinney, and Luca Del Zanna\n\n\n This file is part of PVS-GRMHD.\n\n PVS-GRMHD is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n PVS-GRMHD is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with PVS-GRMHD; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n -------------------------------------------------------------------------------\n*/\n\n// Function prototypes for this file:\nstatic void raise_g(CCTK_REAL vcov[NDIM], CCTK_REAL gcon[NDIM][NDIM], CCTK_REAL vcon[NDIM]);\nstatic void lower_g(CCTK_REAL vcon[NDIM], CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL vcov[NDIM]);\nstatic void ncov_calc(CCTK_REAL gcon[NDIM][NDIM],CCTK_REAL ncov[NDIM]);\nstatic CCTK_REAL pressure_rho0_u(eos_struct eos, CCTK_REAL rho0, CCTK_REAL u);\nstatic CCTK_REAL pressure_rho0_w(eos_struct eos, CCTK_REAL rho0, CCTK_REAL w);\n\n// Inlined function used by this file\nstatic inline void compute_P_cold__eps_cold(eos_struct eos,CCTK_REAL rho_in, CCTK_REAL &P_cold,CCTK_REAL &eps_cold);\n```\n\n Writing ../src/harm_u2p_util.c\n\n\n\n\n## Step 2.a: The `raise_g()` function \\[Back to [top](#toc)\\]\n$$\\label{raise_g}$$\n\nThis is a simple function, used to *raise* the indices of a *covariant vector* using an inverse metric, $g^{\\mu\\nu}$. Usually the vector is 4-dimensional and $g^{\\mu\\nu}$ is the inverse physical ADM 4-metric, but the function can be used with arbitrary vectors and metrics. In other words, given a vector $v_{\\mu}$ and an inverse metric $g^{\\mu\\nu}$ the function outputs\n\n$$\n\\boxed{v^{\\mu} = g^{\\mu\\nu}v_{\\nu}}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__harm_u2p_util__c\n\n\n/********************************************************************** \n raise_g():\n \n -- calculates the contravariant form of a covariant tensor, \n using the inverse of the metric;\n***********************************************************************/\nstatic void raise_g(CCTK_REAL vcov[NDIM], CCTK_REAL gcon[NDIM][NDIM], CCTK_REAL vcon[NDIM])\n{\n int i,j;\n\n for(i=0;i\n\n## Step 2.b: The `lower_g()` function \\[Back to [top](#toc)\\]\n$$\\label{lower_g}$$\n\nThis is a simple function, used to *lower* the indices of a *contravariant vector* using a metric, $g_{\\mu\\nu}$. Usually the vector is 4-dimensional and $g_{\\mu\\nu}$ is the physical ADM 4-metric, but the function can be used with arbitrary vectors and metrics. In other words, given a vector $v^{\\mu}$ and a metric $g_{\\mu\\nu}$ the function outputs\n\n$$\n\\boxed{v_{\\mu} = g_{\\mu\\nu}v^{\\nu}}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__harm_u2p_util__c\n\n\n/********************************************************************** \n lower_g():\n \n -- calculates the ocvariant form of a contravariant tensor \n using the metric;\n***********************************************************************/\nstatic void lower_g(CCTK_REAL vcon[NDIM], CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL vcov[NDIM])\n{\n int i,j;\n\n for(i=0;i\n\n## Step 2.c: The `ncov_calc()` function \\[Back to [top](#toc)\\]\n$$\\label{ncov_calc}$$\n\nThis simple function sets the covariant normal vector $n_{\\mu} = \\left(-\\alpha,0,0,0\\right)$.\n\n\n```python\n%%writefile -a $outfile_path__harm_u2p_util__c\n\n\n/********************************************************************** \n ncov_calc(): \n\n -- calculates the covariant form of the normal vector to our \n spacelike hypersurfaces ala the ADM formalism.\n\n -- requires the inverse metric;\n***********************************************************************/\nstatic void ncov_calc(CCTK_REAL gcon[NDIM][NDIM],CCTK_REAL ncov[NDIM]) \n{\n CCTK_REAL lapse ;\n int i;\n\n lapse = sqrt(-1./gcon[0][0]) ;\n\n ncov[0] = -lapse ;\n for( i = 1; i < NDIM; i++) { \n ncov[i] = 0. ;\n }\n\n return ;\n}\n```\n\n Appending to ../src/harm_u2p_util.c\n\n\n\n\n# Step 3: EOS dependent routines\n$$\\label{harm_utoprim_2d__c__eos_dep}$$\n\n\n\n## Step 3.a: The `pressure_rho0_u()` function \\[Back to [top](#toc)\\]\n$$\\label{pressure_rho0_u}$$\n\nThe $\\Gamma$-law EOS implemented in `HARM` is\n\n$$\np_{\\Gamma}\\left(\\rho_{b},u\\right) = \\left(\\Gamma-1\\right)u\\ ,\n$$\n\nwhere\n\n$$\nu = \\rho_{b}\\epsilon\\ .\n$$\n\nThus, the pre-PPEOS Patch version of this function was\n\n```c\n/**************************************************\n The following functions assume a Gamma-law EOS:\n***************************************************/\n\n/* \n pressure as a function of rho0 and u \n this is used by primtoU and Utoprim_?D\n*/\nstatic CCTK_REAL pressure_rho0_u(CCTK_REAL rho0, CCTK_REAL u)\n{\n return((GAMMA - 1.)*u) ;\n}\n```\n\nIn the case of a hybrid EOS, however, we have $p_{\\rm hybrid}=p_{\\rm hybrid}\\left(\\rho_{b},\\epsilon\\right)$. To obtain $p_{\\rm hybrid}\\left(\\rho_{b},u\\right)$ we use:\n\n$$\np_{\\rm hybrid} = P_{\\rm cold}\\left(\\rho_{b}\\right) + \\left(\\Gamma_{\\rm th}-1\\right)\\rho_{b}\\left[\\epsilon - \\epsilon_{\\rm cold}\\left(\\rho_{b}\\right)\\right]\n\\implies\n\\boxed{\np_{\\rm hybrid}\\left(\\rho_{b},u\\right) = P_{\\rm cold}\\left(\\rho_{b}\\right) + \\left(\\Gamma_{\\rm th}-1\\right)\\left[u - \\rho_{b}\\epsilon_{\\rm cold}\\left(\\rho_{b}\\right)\\right]\\ ,\n}\n$$\n\nwhere\n\n$$\n\\left\\{\n\\begin{align}\nP_{\\rm cold}\\left(\\rho_{b}\\right) = K_{\\rm poly}\\rho_{b}^{\\Gamma_{\\rm poly}}\\ ,\\\\\n\\epsilon_{\\rm cold}\\left(\\rho_{b}\\right) = C + \\frac{P_{\\rm cold}}{\\rho_{b}\\left(\\Gamma_{\\rm poly}-1\\right)}\\ ,\n\\end{align}\n\\right.\n$$\n\nwhere $C$ is a precomputed integration constant which guarantees the continuity of $\\epsilon_{\\rm cold}\\left(\\rho_{b}\\right)$ and the subscript \"poly\" indicates the local polytropic EOS quantity.\n\n\n```python\n%%writefile -a $outfile_path__harm_u2p_util__c\n\n/**************************************************\n The following functions assume a Gamma-law EOS:\n***************************************************/\n\n/* \npressure as a function of rho0 and u \nthis is used by primtoU and Utoprim_?D\n*/\nstatic CCTK_REAL pressure_rho0_u(eos_struct eos, CCTK_REAL rho0, CCTK_REAL u)\n{\n \n // Set up Gamma_th:\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n DECLARE_CCTK_PARAMETERS;\n#endif\n\n // Compute P_cold, eps_cold\n CCTK_REAL P_cold, eps_cold;\n compute_P_cold__eps_cold(eos,rho0, P_cold,eps_cold);\n\n /* Compute the pressure as a function of rho_b (rho0) and\n * u = rho_b * eps, using our hybrid EOS:\n * .-------------------------------------------------------------.\n * | p(rho_b,u) = P_cold + (Gamma_th - 1)*(u - rho_b * eps_cold) |\n * .-------------------------------------------------------------.\n */\n return( P_cold + (Gamma_th - 1.0)*(u - rho0*eps_cold) );\n\n}\n```\n\n Appending to ../src/harm_u2p_util.c\n\n\n\n\n## Step 3.2: The `pressure_rho0_w()` function \\[Back to [top](#toc)\\]\n$$\\label{pressure_rho0_w}$$\n\nThe $\\Gamma$-law EOS implemented in `HARM` is\n\n$$\np_{\\Gamma} = \\left(\\Gamma-1\\right)u\\ .\n$$\n\nWe want now to obtain $p_{\\Gamma}\\left(\\rho_{b},w\\right)$, where\n\n$$\nw = u + \\rho_{b} + p\\ .\n$$\n\nThen\n\n$$\np_{\\Gamma} = \\left(\\Gamma-1\\right)\\left(w - \\rho_{b} - p_{\\Gamma}\\right)\n\\implies\n\\boxed{\np_{\\Gamma}\\left(\\rho_{b},w\\right) = \\frac{\\left(\\Gamma-1\\right)}{\\Gamma}\\left(w-\\rho_{b}\\right)\n}\\ .\n$$\n\nThus, the pre-PPEOS Patch version of this function was\n\n```c\n/* \n pressure as a function of rho0 and w = rho0 + u + p \n this is used by primtoU and Utoprim_1D\n*/\nstatic CCTK_REAL pressure_rho0_w(CCTK_REAL rho0, CCTK_REAL w)\n{\n return((GAMMA-1.)*(w - rho0)/GAMMA) ;\n}\n```\n\nFor our hybrid EOS, we have\n\n$$\n\\begin{align}\np_{\\rm hybrid} &= P_{\\rm cold} + \\left(\\Gamma_{\\rm th}-1\\right)\\rho_{b}\\left[\\epsilon - \\epsilon_{\\rm cold}\\right]\\\\\n&= P_{\\rm cold} + \\left(\\Gamma_{\\rm th}-1\\right)\\left[u - \\rho_{b}\\epsilon_{\\rm cold}\\right]\\\\\n&= P_{\\rm cold} + \\left(\\Gamma_{\\rm th}-1\\right)\\left[w-\\rho_{b}-p_{\\rm hybrid} - \\rho_{b}\\epsilon_{\\rm cold}\\right]\\\\\n&= P_{\\rm cold} + \\left(\\Gamma_{\\rm th}-1\\right)\\left[w - \\rho_{b}\\left(1+\\epsilon_{\\rm cold}\\right)\\right]- \\left(\\Gamma_{\\rm th}-1\\right)p_{\\rm hybrid}\\\\\n\\implies\n&\\boxed{\np_{\\rm hybrid}\\left(\\rho_{b},w\\right) = \\frac{P_{\\rm cold}}{\\Gamma_{\\rm th}} + \\frac{\\left(\\Gamma_{\\rm th}-1\\right)}{\\Gamma_{\\rm th}}\\left[w - \\rho_{b}\\left(1+\\epsilon_{\\rm cold}\\right)\\right]\n}\n\\end{align}\n$$\n\n\n```python\n%%writefile -a $outfile_path__harm_u2p_util__c\n\n\n/* \n pressure as a function of rho0 and w = rho0 + u + p \n this is used by primtoU and Utoprim_1D\n*/\nstatic CCTK_REAL pressure_rho0_w(eos_struct eos, CCTK_REAL rho0, CCTK_REAL w)\n{\n \n // Set up Gamma_th:\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n DECLARE_CCTK_PARAMETERS;\n#endif\n \n // Compute P_cold, eps_cold\n CCTK_REAL P_cold, eps_cold;\n compute_P_cold__eps_cold(eos,rho0, P_cold,eps_cold);\n\n /* Compute the pressure as a function of rho_b (rho0) and\n * w = u + rho_b + p, using our hybrid EOS:\n * ----------------------------------------------------------------------------\n * | p(rho_b,w) = ( P_cold + (Gamma_th-1)*( w - rho_b*(1+eps_cold) ) )/Gamma_th |\n * ----------------------------------------------------------------------------\n */\n return( (P_cold + (Gamma_th-1.0)*( w - rho0*(1.0+eps_cold) ) )/Gamma_th );\n}\n#endif\n```\n\n Appending to ../src/harm_u2p_util.c\n\n\n\n\n# Step 4: Code validation \\[Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# Verify if the code generated by this tutorial module\n# matches the original IllinoisGRMHD source code\n\n# First download the original IllinoisGRMHD source code\nimport urllib\nfrom os import path\n\noriginal_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/harm_u2p_util.c\"\noriginal_IGM_file_name = \"harm_u2p_util-original.c\"\noriginal_IGM_file_path = os.path.join(IGM_src_dir_path,original_IGM_file_name)\n\n# Then download the original IllinoisGRMHD source code\n# We try it here in a couple of ways in an attempt to keep\n# the code more portable\ntry:\n original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n # Write down the file the original IllinoisGRMHD source code\n with open(original_IGM_file_path,\"w\") as file:\n file.write(original_IGM_file_code)\nexcept:\n try:\n original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n # Write down the file the original IllinoisGRMHD source code\n with open(original_IGM_file_path,\"w\") as file:\n file.write(original_IGM_file_code)\n except:\n # If all else fails, hope wget does the job\n !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# Perform validation\nValidation__harm_u2p_util__c = !diff $original_IGM_file_path $outfile_path__harm_u2p_util__c\n\nif Validation__harm_u2p_util__c == []:\n # If the validation passes, we do not need to store the original IGM source code file\n !rm $original_IGM_file_path\n print(\"Validation test for harm_u2p_util.c: PASSED!\")\nelse:\n # If the validation fails, we keep the original IGM source code file\n print(\"Validation test for harm_u2p_util.c: FAILED!\")\n # We also print out the difference between the code generated\n # in this tutorial module and the original IGM source code\n print(\"Diff:\")\n for diff_line in Validation__harm_u2p_util__c:\n print(diff_line)\n```\n\n Validation test for harm_u2p_util.c: FAILED!\n Diff:\n 1c1,2\n < \n ---\n > #ifndef __HARM_U2P_UTIL__C__\n > #define __HARM_U2P_UTIL__C__\n 28,154c29,33\n < void primtoU_g( CCTK_REAL prim[], CCTK_REAL gcov[][NDIM], CCTK_REAL gcon[][NDIM], CCTK_REAL gdet, CCTK_REAL U[] );\n < static void ucon_calc_g(CCTK_REAL prim[],CCTK_REAL gcov[][NDIM],CCTK_REAL gcon[][NDIM],CCTK_REAL ucon[]);\n < static void raise_g(CCTK_REAL vcov[], CCTK_REAL gcon[][NDIM], CCTK_REAL vcon[]);\n < static void lower_g(CCTK_REAL vcon[], CCTK_REAL gcov[][NDIM], CCTK_REAL vcov[]);\n < static void ncov_calc(CCTK_REAL gcon[][NDIM],CCTK_REAL ncov[]) ;\n < static void bcon_calc_g(CCTK_REAL prim[],CCTK_REAL ucon[],CCTK_REAL ucov[],CCTK_REAL ncov[],CCTK_REAL bcon[]); \n < static CCTK_REAL pressure_rho0_u(CCTK_REAL rho0, CCTK_REAL u);\n < static CCTK_REAL pressure_rho0_w(CCTK_REAL rho0, CCTK_REAL w);\n < int gamma_calc_g(CCTK_REAL *pr, CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL *gamma);\n < \n < /********************************************************************** \n < primtoU_g(): \n < \n < -- calculates the conserved variables from the primitive variables \n < and the metric;\n < -- assumes that the conserved and primitive variables are defined ala HARM:\n < \n < / rho u^t \\\n < U = | T^t_\\mu + rho u^t | sqrt(-det(g_{\\mu\\nu}))\n < \\ B^i /\n < \n < / rho \\\n < P = | uu |\n < | \\tilde{u}^i |\n < \\ B^i /\n < \n < **************************************************************************/\n < \n < \n < void primtoU_g(\n < CCTK_REAL prim[NPR], /* primitive variables */\n < CCTK_REAL gcov[NDIM][NDIM], /* covariant (index dn) form of metric */\n < CCTK_REAL gcon[NDIM][NDIM], /* contravariant (index up) form of metric */\n < CCTK_REAL gdet, /* sqrt of -1 times det(g_{\\mu \\nu}) */\n < CCTK_REAL U[NPR] /* matrix of derivatives */\n < ) {\n < int i ;\n < CCTK_REAL rho0 ;\n < static CCTK_REAL ucon[NDIM],ucov[NDIM],bcon[NDIM],bcov[NDIM],ncov[NDIM] ;\n < CCTK_REAL gamma,n_dot_b,bsq,u,p,w, alpha ;\n < \n < \n < /* Calculate auxiliary quantities: */\n < alpha = 1.0/sqrt(-gcon[0][0]);\n < \n < ucon_calc_g(prim,gcov,gcon,ucon) ;\n < lower_g(ucon,gcov,ucov) ;\n < ncov_calc(gcon,ncov) ;\n < \n < gamma = -ncov[0]*ucon[0] ;\n < \n < bcon_calc_g(prim,ucon,ucov,ncov,bcon) ;\n < lower_g(bcon,gcov,bcov) ;\n < \n < n_dot_b = 0. ;\n < for(i=0;i<4;i++) n_dot_b += ncov[i]*bcon[i] ;\n < bsq = 0. ;\n < for(i=0;i<4;i++) bsq += bcov[i]*bcon[i] ;\n < \n < rho0 = prim[RHO] ;\n < u = prim[UU] ;\n < p = pressure_rho0_u(rho0,u) ;\n < w = rho0 + u + p ;\n < \n < // Now set the conserved variables themselves, using HARM's definition:\n < U[RHO] = ucon[0]*rho0 ;\n < \n < for( i = 0; i < 4; i++) {\n < U[QCOV0+i] = gamma*(w + bsq)*ucov[i] \n < - (p + bsq/2.)*ncov[i] \n < + n_dot_b*bcov[i] ;\n < \n < U[QCOV0+i] /= alpha;\n < }\n < \n < U[QCOV0] = U[QCOV0] + U[RHO];\n < U[BCON1] = prim[BCON1] ;\n < U[BCON2] = prim[BCON2] ;\n < U[BCON3] = prim[BCON3] ;\n < \n < for(i = 0; i < NPR; i++ ) {\n < U[i] *= gdet;\n < }\n < \n < return ;\n < }\n < \n < /********************************************************************** \n < ucon_calc_g(): \n < \n < -- calculates the contravariant (up) components of the four-velocity\n < given the primitive variables, of which the velocity is \n < \\tilde{u}^i = \\gamma v^j where v^j is the velocity of the \n < flow w.r.t a normal observer to the coordinates;\n < \n < -- also requires the metric and inverse metric;\n < \n < -- assumes:\n < \n < / rho \\\n < P = | uu |\n < | \\tilde{u}^i |\n < \\ B^i /\n < \n < ******************************************************************/\n < static void ucon_calc_g(CCTK_REAL prim[NPR],CCTK_REAL gcov[NDIM][NDIM],CCTK_REAL gcon[NDIM][NDIM],\n < CCTK_REAL ucon[NDIM])\n < {\n < CCTK_REAL u_tilde_con[4] ;\n < CCTK_REAL u_tilde_sq ;\n < CCTK_REAL gamma,lapse ;\n < int i,j;\n < \n < u_tilde_con[0] = 0. ;\n < u_tilde_con[1] = prim[UTCON1] ;\n < u_tilde_con[2] = prim[UTCON2] ;\n < u_tilde_con[3] = prim[UTCON3] ;\n < \n < u_tilde_sq = 0. ;\n < for(i=0;i static void raise_g(CCTK_REAL vcov[NDIM], CCTK_REAL gcon[NDIM][NDIM], CCTK_REAL vcon[NDIM]);\n > static void lower_g(CCTK_REAL vcon[NDIM], CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL vcov[NDIM]);\n > static void ncov_calc(CCTK_REAL gcon[NDIM][NDIM],CCTK_REAL ncov[NDIM]);\n > static CCTK_REAL pressure_rho0_u(eos_struct eos, CCTK_REAL rho0, CCTK_REAL u);\n > static CCTK_REAL pressure_rho0_w(eos_struct eos, CCTK_REAL rho0, CCTK_REAL w);\n 156c35,36\n < for(i=0;i // Inlined function used by this file\n > static inline void compute_P_cold__eps_cold(eos_struct eos,CCTK_REAL rho_in, CCTK_REAL &P_cold,CCTK_REAL &eps_cold);\n 158,159d37\n < return ;\n < }\n 166c44\n < ******************************************************************/\n ---\n > ***********************************************************************/\n 179a58\n > \n 185c64\n < ******************************************************************/\n ---\n > ***********************************************************************/\n 198a78\n > \n 206c86\n < ******************************************************************/\n ---\n > ***********************************************************************/\n 222,292d101\n < /********************************************************************** \n < bcon_calc_g(): \n < \n < -- using the primitive variables, contra-/co-variant 4-vel., \n < and covariant normal vector, calculate the contravariant \n < form of the magnetic 4-vector b^\\mu (the small \"b\" in HARM);\n < -- assumes:\n < \n < / rho \\\n < P = | uu |\n < | \\tilde{u}^i |\n < \\ B^i /\n < ******************************************************************/\n < static void bcon_calc_g(CCTK_REAL prim[NPR],CCTK_REAL ucon[NDIM],CCTK_REAL ucov[NDIM],\n < CCTK_REAL ncov[NDIM],CCTK_REAL bcon[NDIM]) \n < {\n < static CCTK_REAL Bcon[NDIM] ;\n < CCTK_REAL u_dot_B ;\n < CCTK_REAL gamma ;\n < int i ;\n < \n < // Bcon = \\mathcal{B}^\\mu of the paper:\n < Bcon[0] = 0. ;\n < for(i=1;i1E-10){ // then assume not just machine precision\n < return (1);\n < }\n < else utsq=1E-10; // set floor\n < }\n < \n < *gamma = sqrt(1. + utsq) ;\n < \n < return(0) ;\n < }\n < \n < \n 298,299c107,108\n < pressure as a function of rho0 and u \n < this is used by primtoU and Utoprim_?D\n ---\n > pressure as a function of rho0 and u \n > this is used by primtoU and Utoprim_?D\n 301c110\n < static CCTK_REAL pressure_rho0_u(CCTK_REAL rho0, CCTK_REAL u)\n ---\n > static CCTK_REAL pressure_rho0_u(eos_struct eos, CCTK_REAL rho0, CCTK_REAL u)\n 302a112,114\n > \n > // Set up Gamma_th:\n > #ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n 304c116,129\n < return((gamma_th /* <- Should be local polytropic Gamma factor */ - 1.)*u) ;\n ---\n > #endif\n > \n > // Compute P_cold, eps_cold\n > CCTK_REAL P_cold, eps_cold;\n > compute_P_cold__eps_cold(eos,rho0, P_cold,eps_cold);\n > \n > /* Compute the pressure as a function of rho_b (rho0) and\n > * u = rho_b * eps, using our hybrid EOS:\n > * .-------------------------------------------------------------.\n > * | p(rho_b,u) = P_cold + (Gamma_th - 1)*(u - rho_b * eps_cold) |\n > * .-------------------------------------------------------------.\n > */\n > return( P_cold + (Gamma_th - 1.0)*(u - rho0*eps_cold) );\n > \n 308d132\n < \n 313c137\n < static CCTK_REAL pressure_rho0_w(CCTK_REAL rho0, CCTK_REAL w)\n ---\n > static CCTK_REAL pressure_rho0_w(eos_struct eos, CCTK_REAL rho0, CCTK_REAL w)\n 314a139,141\n > \n > // Set up Gamma_th:\n > #ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n 316c143,155\n < return((gamma_th /* <- Should be local polytropic Gamma factor */ -1.)*(w - rho0)/gamma_th /* <- Should be local polytropic Gamma factor */ ) ;\n ---\n > #endif\n > \n > // Compute P_cold, eps_cold\n > CCTK_REAL P_cold, eps_cold;\n > compute_P_cold__eps_cold(eos,rho0, P_cold,eps_cold);\n > \n > /* Compute the pressure as a function of rho_b (rho0) and\n > * w = u + rho_b + p, using our hybrid EOS:\n > * ----------------------------------------------------------------------------\n > * | p(rho_b,w) = ( P_cold + (Gamma_th-1)*( w - rho_b*(1+eps_cold) ) )/Gamma_th |\n > * ----------------------------------------------------------------------------\n > */\n > return( (P_cold + (Gamma_th-1.0)*( w - rho0*(1.0+eps_cold) ) )/Gamma_th );\n 318,319c157\n < \n < \n ---\n > #endif\n\n\n\n\n# Step 5: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-IllinoisGRMHD__harm_u2p_util.pdf](Tutorial-IllinoisGRMHD__harm_u2p_util.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means).\n\n\n```python\nlatex_nrpy_style_path = os.path.join(nrpy_dir_path,\"latex_nrpy_style.tplx\")\n#!jupyter nbconvert --to latex --template $latex_nrpy_style_path --log-level='WARN' Tutorial-IllinoisGRMHD__harm_u2p_util.ipynb\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__harm_u2p_util.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__harm_u2p_util.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__harm_u2p_util.tex\n!rm -f Tut*.out Tut*.aux Tut*.log\n```\n", "meta": {"hexsha": "b9e1b9cc11d7012c12ca75ae9cc3702c5d7c9a7d", "size": 37490, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_u2p_util.ipynb", "max_stars_repo_name": "Steve-Hawk/nrpytutorial", "max_stars_repo_head_hexsha": "42d7450dba8bf43aa9c2d8f38f85f18803de69b7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-12-23T05:31:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-23T05:31:25.000Z", "max_issues_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_u2p_util.ipynb", "max_issues_repo_name": "Steve-Hawk/nrpytutorial", "max_issues_repo_head_hexsha": "42d7450dba8bf43aa9c2d8f38f85f18803de69b7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_u2p_util.ipynb", "max_forks_repo_name": "Steve-Hawk/nrpytutorial", "max_forks_repo_head_hexsha": "42d7450dba8bf43aa9c2d8f38f85f18803de69b7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-02T12:51:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T12:51:56.000Z", "avg_line_length": 38.8497409326, "max_line_length": 386, "alphanum_fraction": 0.483168845, "converted": true, "num_tokens": 8759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34411647820698654}} {"text": "

\n \n\n

\n\n## Machine Learning based uncertainty models\n\n## Subsurface Property Prediction with Neural Networks\n\n### Eduardo Maldonado Cruz, Graduate Research Assistant, The University of Texas at Austin\n\n#### [Twitter](https://twitter.com/emaldonadocruz) | [GitHub](https://github.com/emaldonadocruz) | [LinkedIn](https://www.linkedin.com/in/eduardo-maldonado-8386a898/)\n\n### Michael Pyrcz, Associate Professor, The University of Texas at Austin \n\n#### [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1)\n\n## Executive summary\n\nDeep learning models focus on **prediction accuracy and minimizing prediction error**. Yet, for spatial models, **accurate predictions along with accurate and precise uncertainty models are critical.** \n\nDue to limited data veracity, data sparsity, and feature heterogeneity in the spatial setting, uncertainty is significant; therefore, **predicting a single estimate must be replaced with a prediction of the uncertainty distribution**.\n\n**We propose a novel and easy to use objective function to summarize uncertainty model performance**.\nThe proposed function tunes deep learning models for optimum uncertainty accuracy and precision.\n\n## Objective\n\nTune deep learning models for maximum **goodness**, **accuracy** and **precision**.\n\n## Introduction\n\nDeep learning models focus on prediction accuracy and minimizing prediction error. Yet, for spatial models, accurate predictions along with accurate and precise uncertainty models are critical. Prediction of the entire uncertainty model is accomplished robustly with Bayesian Neural Networks but with high computational cost(MacKay, 1991; Hinton and Van Camp 1993). Leading to the development of stochastic regularization techniques, one of the most popular is dropout (Hinton et al., 2012; Srivastava et al., 2014, Gal, 2016, Gal and Ghahramani., 2016, Kendall and Gal, 2017, Osband et al., 2016) that can be interpreted as a Bayesian approximation with greater computationally efficiency. \n\nDropout is a technique that addresses overfitting in neural networks and provides an approach to improve prediction accuracy by ensemble learning. Dropout refers to randomly removing or reducing (also known as regularizing) network weights, removing or weakening the connections between the nodes in the neural network to introduce prediction model stochasticity during model training (Dahl, 2013; Srivastava, 2014; Hara, 2016). \n\nEnsemble predictions benefit from reduced model variance and improved prediction model generalization. The proposed method uses the machine learning dropout hyperparameter to calculate accurate and precise uncertainty models of response features. This objective function is based on the goodness metric proposed by Deutsch (1996).\n\nThe goodness of the uncertainty model (Maldonado and Pyrcz, 2021)\n\n\\begin{equation}\n\\mathrm{f}\\left(x\\right)=\\frac{1}{2}\\left[\\frac{1}{n}\\sum_{i=1}^{n}\\left|y\\left(\\mathbf{u}_{\\mathrm{i}}\\right)-\\hat{y}\\left(\\mathbf{u}_{\\mathrm{i}}\\right)\\right|\\right]+\\frac{1}{2}\\left[\\int_{0}^{1}\\left[3a\\left(p\\right)-2\\right]\\left[\\overline{\\xi\\left(p\\right)}-p\\right]dp\\right]\n\\label{eq:Goodness} \\tag{1}\n\\end{equation}\n\nwhere the first term is the typical mean absolute error (MAE) in testing between $𝑦_𝑖 (𝐮_𝐢 )$ training response feature values and $𝑦_𝑖 (𝐮_𝐢 )$ estimates over n withheld testing data, and the second term is a measure of goodness.\n\nWhere $\\xi(𝐮_𝑖;𝑝)$ is the indicator function at each point $𝐮_𝑖, 𝑖=1,…,𝑛,$ evaluated over a range of symmetric 𝑝-probability intervals:\n\n\\begin{equation}\n\\xi\\left(\\mathbf{u}_{\\mathrm{i}};p\\right)=\\begin{cases}\n1, & F_{y}\\left(\\mathbf{u}_{\\mathrm{i}};y\\left(\\mathbf{u}_{\\mathrm{i}}\\right)\\right)\\in\\left(p_{low},p_{upp}\\right]\\\\\n0, & \\mathrm{Otherwise}\n\\end{cases}\n\\label{eq:IndicatorFunc} \\tag{2}\n\\end{equation}\n\nNext, we use $\\ref{eq:Goodness}$ as the objective function to tune a very simple uncertainty model.\n\n\n## Library importing\n\nFirst we must import some libraries to train a deep learning model.\n\n\n\n```python\n# Set verbosity\nimport logging\nlogging.getLogger(\"tensorflow\").setLevel(logging.ERROR)\n\n# Libraries for data analysis and array manipulation\nimport pandas as pd\nimport numpy as np\n\n# Libraries for plotting\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\n\n# Import tensorflow\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom keras.layers.core import Lambda\nfrom tensorflow.keras import backend as K\n\n#Librabry with useful analysis statistics\nfrom scipy import stats\nfrom scipy import integrate\nimport random\n\n\n# Preprocessing and train-test split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n# library for hyperparameter search\nimport optuna\n\n#To import, save and load jobs\nimport joblib\n```\n\n\n```python\ntf.random.set_seed(0)\nnp.random.RandomState(38)\nnp.random.seed(38)\n```\n\n\n```python\n!pip install UTuning\n```\n\n Requirement already satisfied: UTuning in c:\\users\\em42363\\anaconda3\\envs\\new\\lib\\site-packages (0.1.3)\n\n\n\n```python\n#import sys\n#sys.path.insert(0, r'C:\\Users\\em42363\\OneDrive\\PhD\\UTuning')\n\nfrom UTuning import scorer, plots\n```\n\n\n```python\n## Plots\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\nimport matplotlib.tri as tri\nfrom scipy.ndimage import gaussian_filter\n\n#import matplotlib\n#matplotlib.rcParams['text.usetex'] = True\n\n\ndef error_line(Prediction, Truth, Sigma, Frac=1):\n '''Simple function to draw an error line plot. It takes three arrays of the same length \n\n Parameters\n ----------\n\n Prediction : float array\n The predicted value array (Prediction)\n Truth : float array\n The truth value array (Truth) \n Sigma : float array\n The standard deviation array (Sigma)\n Frac : float \n Frac is the fraction of points to display randomly\n\n Returns\n -------\n Scatter plot\n '''\n yline = [min(Prediction.min(), Truth.min()),\n max(Prediction.max(), Truth.max())]\n xline = [min(Prediction.min(), Truth.min()),\n max(Prediction.max(), Truth.max())]\n\n fig, ax = plt.subplots(figsize=(10, 6))\n # To display randomly less points [Remove , Keep] in fraction\n mask = np.random.choice([False, True], len(Prediction), p=[(1-Frac), (Frac)])\n ax.errorbar(Prediction[mask], Truth[mask], xerr=Sigma[mask],\n fmt='k.',\n ecolor='k')\n ax.plot(xline, yline, '-k')\n ax.set_xlabel('Predicted value, $\\hat{y}$')\n ax.set_ylabel('True value, $y$ ')\n plt.show()\n\ndef error_accuracy_plot(percentile,IF_array,Prediction_array,Truth,Sigma):\n '''Simple function to draw an error line plot and its corresponding accuracy plot. \n\n Parameters\n ----------\n\n Prediction : float array\n The predicted value array (Prediction)\n Truth : float array\n The truth value array (Truth) \n Sigma : float array\n The standard deviation array (Sigma)\n Frac : float \n Frac is the fraction of points to display randomly\n\n Returns\n -------\n Scatter plot\n '''\n avgIndFunc = np.mean(IF_array, axis=0)\n \n L = 10\n mean = np.empty((L, len(percentile)))\n\n for p_interv in range(len(percentile)):\n for l in np.arange(0, L):\n samples = random.choices(IF_array[:, p_interv],\n k=IF_array.shape[0])\n mean[l, p_interv] = np.mean(samples)\n \n fig,(ax1,ax2)=plt.subplots(1,2,figsize=(12,4))\n \n if len(Prediction_array.shape)>1:\n xline = [0,max(np.mean(Prediction_array,axis=1).max(),Truth.max())+max(np.mean(Prediction_array,axis=1).max(),Truth.max())*0.1]#\n yline = [0,xline[1]]#\n \n ax1.errorbar(np.mean(Prediction_array,axis=1), Truth, xerr=Sigma, \n fmt='k.',\n ecolor='k')\n else:\n xline = [0,max(Prediction_array.max(),Truth.max())+max(Prediction_array.max(),Truth.max())*0.1]#\n yline = [0,xline[1]]#\n \n ax1.errorbar(Prediction_array, Truth, xerr=Sigma, \n fmt='k.',\n ecolor='k')\n ax1.plot(xline, yline, '-k')\n ax1.set_xlabel('Predicted value, $\\hat{y}$')\n ax1.set_ylabel('True value, $y$ ')\n\n ax2.plot(percentile, avgIndFunc,'-ok',markersize=5)\n ax2.plot(percentile,np.round(avgIndFunc+np.std(mean, axis=0), 3),'--k')\n ax2.plot(percentile,np.round(avgIndFunc-np.std(mean, axis=0), 3),'--k')\n ax2.plot([0, 1],[0, 1],'-k')\n ax2.set_ylabel(r\"$\\overline{\\xi (p)}$\")\n ax2.set_xlabel('Probability interval $p$')\n ax2.set_ylim(0,1)\n ax2.set_xlim(0,1)\n\n ax2.plot(percentile, avgIndFunc,'-ok',markersize=5)\n \n\ndef surface(x, y, z, levels, labels):\n \n fig, (ax1) = plt.subplots(nrows=1,figsize=(12,6))\n \n npoints=x.shape[0]\n smooth=1\n \n # Create grid values first.\n xi = np.linspace(x.min(), x.max(), npoints)\n yi = np.linspace(y.min(), y.max(), npoints)\n \n # Linearly interpolate the data (x, y) on a grid defined by (xi, yi).\n triang = tri.Triangulation(x, y)\n interpolator = tri.LinearTriInterpolator(triang, z)\n Xi, Yi = np.meshgrid(xi, yi)\n zi = interpolator(Xi, Yi)\n \n zi = gaussian_filter(zi, smooth)\n \n levels = levels\n \n ax1.contour(xi, yi, zi, levels=levels, linewidths=0.1, colors='k')\n \n cntr1 = ax1.contourf(xi, yi, zi, levels=levels, cmap=\"inferno\",alpha=0.95)\n \n cbar = plt.colorbar(cntr1, ax=ax1)\n cbar.set_label(labels['z'], rotation=270,labelpad=30)\n \n ax1.set(xlim=(x.min(), x.max()),ylim=(y.min(), y.max()))\n\n ax1.scatter(x,y,s=7,color='white')\n ax1.set_xlabel(labels['x'])\n ax1.set_ylabel(labels['y'])\n \n \n plt.show()\n\n```\n\n\n```python\n## Scorer\nimport numpy as np\nimport scipy.stats as stats\nimport scipy.integrate as integrate\n\nclass scorer:\n '''\n Scorer class, a class to represent the accuracy, precision and goodness\n score from an uncertainty model.\n \n Attributes\n ----------\n Accuracy : float\n Precision : float\n Goodness : float\n Overall uncertainty : float\n Indicator Function : float array\n '''\n def __init__(self, Prediction, Truth, Sigma):\n \n n_quantiles = 11\n self.perc = np.linspace(0.0, 1.01, n_quantiles)\n # self.A_array=np.zeros(Prediction.shape[0])\n # self.P_array=np.zeros(Prediction.shape[0])\n # self.G_array=np.zeros(Prediction.shape[0])\n #self.U_array=np.zeros(Prediction.shape[0])\n\n self.IF_array=np.zeros((Prediction.shape[0],n_quantiles))\n \n if len(Prediction.shape)>1:\n for i in range(Prediction.shape[0]):\n IF = APG_calc(Truth[i], Prediction[i,:], Sigma[i],n_quantiles)\n #self.U_array[i]=U\n # self.A_array[i]=A\n # self.P_array[i]=P\n # self.G_array[i]=G\n self.IF_array[i,:] = IF\n else:\n Pred_array = np.zeros((Sigma.shape[0],100))\n for i in range(Prediction.shape[0]):\n Pred_array[i,:] = np.random.normal(loc=Prediction[i],scale=Sigma[i],size=100)\n IF = APG_calc(Truth[i], Pred_array[i,:], Sigma[i],n_quantiles)\n #self.U_array[i]=U\n # self.A_array[i]=A\n # self.P_array[i]=P\n # self.G_array[i]=G\n self.IF_array[i,:] = IF\n \n self.avgIndFunc = np.mean(self.IF_array, axis=0)\n \n self.a = np.zeros(len(self.avgIndFunc))\n for i in range(len(self.avgIndFunc)):\n if self.avgIndFunc[i] > self.perc[i] or self.avgIndFunc[i] == self.perc[i]:\n self.a[i] = 1\n else:\n self.a[i] = 0\n \n def Accuracy(self):\n Accuracy = integrate.simps(self.a, self.perc)\n return Accuracy\n #return print('Accuracy = {0:2.2f}'.format(np.mean(self.A_array)))\n \n def Precision(self):\n Prec = self.a*(self.avgIndFunc-self.perc)\n Precision = 1-2*integrate.simps(Prec, self.perc)\n return Precision\n #return print('Precision = {0:2.2f}'.format(np.mean(self.P_array)))\n \n def Goodness(self):\n Sum = (3*self.a-2)*(self.avgIndFunc-self.perc)\n Goodness = 1-integrate.simps(Sum, self.perc)\n return Goodness\n #return print('Goodness = {0:2.2f}'.format(np.mean(self.G_array)))\n\n def Overall_uncertainty(self,Sigma):\n return Sigma.mean()\n #return print('Overall uncertainty = {0:2.2f}'.format(np.mean(self.G_array)))\n \n def IndicatorFunction(self):\n return self.IF_array\n\ndef APG_calc(Truth, Pred, Sigma,n_quantiles):\n\n mask = np.random.choice([False, True],\n len(Pred),\n p=[0, 1]) # To display randomly less points [Remove , Keep] in fraction\n\n Pred=Pred[mask]\n \n perc = np.linspace(0.0, 1.01, n_quantiles)\n\n F = np.zeros(Pred.shape[0])\n Indicator_func = np.zeros((Pred.shape[0], perc.shape[0]))\n\n # range of symmetric p-probability intervals\n plow = (1 - perc) / 2\n pupp = (1 + perc) / 2\n \n for i in range(len(Pred)):\n F[i] = stats.norm.cdf(Truth,\n loc=Pred[i],\n scale=Sigma)\n for proba_low, proba_upp in zip(plow, pupp):\n for k in range(len(plow)):\n if plow[k] < F[i] <= pupp[k]:\n Indicator_func[i, k] = 1\n else:\n Indicator_func[i, k] = 0\n\n avgIndFunc = np.mean(Indicator_func, axis=0)\n\n return avgIndFunc\n\n```\n\n\n```python\nphysical_devices = tf.config.list_physical_devices('GPU') \nif len(physical_devices)>0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n```\n\n## Functions\n\nFirst lets define some useful functions that will be later used for plotting and case evaluation\n\n\n```python\n# Custom functions\ndef get_dataframe(mc_predictions, y_s, X_s):\n '''\n This function takes the sampled distribution along with the testing data and obtains\n the mean, variance and standard deviation, from this function we get the dataframe\n to construct the accuracy plot.\n '''\n \n Mean = np.zeros((mc_predictions.shape[1]))\n Var = np.zeros((mc_predictions.shape[1]))\n STD = np.zeros((mc_predictions.shape[1]))\n \n for i in range(mc_predictions.shape[1]):\n Mean[i] = np.average(mc_predictions[:, i])\n Var[i] = np.var(mc_predictions[:, i])\n STD[i] = np.std(mc_predictions[:, i])\n\n mask = np.random.choice([False, True], len(Mean), p=[0.5, 0.5])\n \n df = pd.DataFrame()\n \n df['Pred'] = Mean[mask]\n df['Truth'] = y_s[mask]\n df['Var'] = Var[mask]\n df['Sigma'] = np.sqrt(Var[mask])\n \n return df\n\ndef get_GAP(MeanVal, Sigma, Truth, n_quantiles):\n '''\n This function takes the dataframe and calculates the indicator function and the average\n we then use this information to estimate the accuracy, goodness and precision of the model.\n '''\n perc = np.linspace(0.0, 1.00, n_quantiles)\n F = np.zeros(MeanVal.shape[0])\n Indicator_func = np.zeros((MeanVal.shape[0], perc.shape[0]))\n\n # range of symmetric p-probability intervals\n plow = (1 - perc) / 2\n pupp = (1 + perc) / 2\n \n for i in range(len(MeanVal)):\n F[i] = stats.norm.cdf(Truth[i],\n loc=MeanVal[i],\n scale=Sigma[i])\n for proba_low, proba_upp in zip(plow, pupp):\n for k in range(len(plow)):\n if plow[k] < F[i] <= pupp[k]:\n Indicator_func[i, k] = 1\n else:\n Indicator_func[i, k] = 0\n\n avgIndFunc = np.mean(Indicator_func, axis=0)\n \n a = np.zeros(len(avgIndFunc))\n for i in range(len(avgIndFunc)):\n if avgIndFunc[i] > perc[i] or avgIndFunc[i] == perc[i]:\n a[i] = 1\n else:\n a[i] = 0\n print(f'Overall uncertainty = {Sigma.mean():.6f}')\n U = Sigma.mean()\n \n ##% Goodness, Precision and Accuracy\n \n\n Accuracy = integrate.simps(a, perc)\n\n Prec = a*(avgIndFunc-perc)\n Precision = 1-2*integrate.simps(Prec, perc)\n\n Sum = (3*a-2)*(avgIndFunc-perc)\n Goodness = 1-integrate.simps(Sum, perc)\n\n return Goodness, Precision, Accuracy, U, Indicator_func,perc\n\ndef error_line(Mean,Truth,STD,r):\n '''\n Simple function to draw an error line plot. It takes the mean predicted value,\n the truth value and the standard deviation.\n '''\n \n xline = [0,1]#\n yline = [0,1]#\n plt.figure(figsize=(10, 6))\n mask = np.random.choice([False, True], len(Mean), p=[0.5, 0.5])\n plt.errorbar(Mean[mask], Truth[mask], xerr=STD[mask], \n fmt='k.', ecolor='k',label=\"Pearson's r = {0:2.2f}\".format(r))\n plt.legend()\n plt.plot(xline, yline, '-k')\n \n plt.xlabel('Predicted value, $\\hat{y}$ [bl]')\n plt.ylabel('True value, $y$ [bl]')\n\n plt.show()\n \ndef accuracy_plot(Indicator_func,perc):\n '''\n This function takes the indicator function and percentiles to draw the accuracy plot.\n '''\n \n L = 100 \n mean = np.empty((L, len(perc)))\n std = np.empty_like(mean)\n avgIndFunc = np.mean(Indicator_func, axis=0)\n for p_interv in range(len(perc)):\n for l in np.arange(0, L):\n samples = random.choices(Indicator_func[:, p_interv],\n k=Indicator_func.shape[0])\n mean[l, p_interv] = np.mean(samples)\n\n plt.figure(figsize=(10, 6))\n plt.plot(perc, avgIndFunc,'-ok',markersize=5)\n plt.plot(perc,np.round(avgIndFunc+np.std(mean, axis=0), 3),'--k')\n plt.plot(perc,np.round(avgIndFunc-np.std(mean, axis=0), 3),'--k')\n plt.plot([0, 1],[0, 1],'-k')\n plt.ylabel(r\"$\\overline{\\xi (p)}$\")\n plt.xlabel('Probability interval $p$')\n plt.ylim(0,1)\n plt.xlim(0,1)\n plt.show()\n\ndef histogram(mc_predictions):\n '''\n From the Monte Carlo predictions we draw a random point and construct the\n histogram of predictions from the model\n '''\n \n Avg = []\n rand=np.random.randint(0,mc_predictions.shape[1])\n for i in range(mc_predictions.shape[0]):\n Avg.append(np.average(mc_predictions[i,rand]))\n\n Std = np.std(Avg)\n\n # Histograms\n n_bins = 20\n fig, axs = plt.subplots(1, 1, figsize=(10, 6))\n N, bins, patches = axs.hist(Avg,\n bins=n_bins,\n label='$\\sigma$ = %2.5f' % Std)\n #axs.set_title('Root Mean squared error in barrels for each cell');\n fracs = N / N.max()\n norm = colors.Normalize(fracs.min(), fracs.max())\n for thisfrac, thispatch in zip(fracs, patches):\n color = plt.cm.binary(norm(thisfrac))\n thispatch.set_facecolor(color)\n plt.legend()\n plt.ylabel('Number of cases')\n plt.xlabel('Normalized production value')\n \ndef histogram_fixed(Prediction,rand):\n '''\n From the Monte Carlo predictions we draw a random point and construct the\n histogram of predictions from the model\n '''\n \n Pred_array = np.zeros(100)\n Pred_array = np.random.normal(loc=np.mean(Prediction[:,rand]),scale=np.std(Prediction[:,rand]),size=500)\n\n # Histograms\n n_bins = 15\n fig, axs = plt.subplots(1, 1, figsize=(10, 6))\n N, bins, patches = axs.hist(Pred_array,\n bins='auto',\n color = 'black',\n label='$\\sigma$ = %2.5f' % np.std(Prediction[:,rand]),\n rwidth = 0.85,\n alpha =0.85)\n plt.legend()\n plt.ylabel('Number of cases')\n plt.xlabel('Normalized production value')\n \ndef plot_loss(history):\n '''\n Simple function to plot the loss for the training and testing data\n '''\n plt.figure(figsize=(12,6))\n plt.plot(history.history['loss'], label='Training loss')\n plt.plot(history.history['val_loss'], label='Testing loss')\n plt.xlabel('Epoch')\n plt.ylabel('Loss ')\n plt.legend()\n plt.grid(True) \n\ndef objective(trial):\n '''\n We use this function to define the search space for the hyperparameter search.\n This function creates, train and evaluates the model.\n '''\n\n dropout = trial.suggest_discrete_uniform('Dropout', 0.05, 0.95, 0.01)\n lr = float(trial.suggest_discrete_uniform('learn_rate', 0.001, .03, 0.001))\n \n model = create_model(dropout)\n \n opt = keras.optimizers.Adam(learning_rate=lr)\n\n model.compile(loss='mae',\n optimizer=opt,\n metrics='mse')\n\n model.fit(\n X_train,\n y_train,\n shuffle=True,\n batch_size=16,\n epochs=100,\n verbose=False,\n )\n score = model.evaluate(X_test, y_test, verbose=0)\n\n mc_predictions = evaluate_cases(model, X_test, 8, y_test,100)\n #df = get_dataframe(mc_predictions, y_test, X_test)\n #df.to_csv('ModelPredictions.csv')\n \n Sigma = np.std(mc_predictions , axis = 0)\n Pred_array = mc_predictions\n Pred = np.mean(mc_predictions , axis = 0) \n A, P, G = model_eval(y_test,mc_predictions,Sigma,np.mean(mc_predictions,axis=0))\n \n Score = 0.5*score[0]+0.5*(1-G)\n\n return Score\n\ndef APG_calc(Truth, Pred, Sigma,n_quantiles):\n\n mask = np.random.choice([False, True],\n len(Pred),\n p=[0.0, 1]) # To display randomly less points [Remove , Keep] in fraction\n\n Pred=Pred[mask]\n perc = np.linspace(0.0, 1.00, n_quantiles)\n\n F = np.zeros(Pred.shape[0])\n Indicator_func = np.zeros((Pred.shape[0], perc.shape[0]))\n\n # range of symmetric p-probability intervals\n plow = (1 - perc) / 2\n pupp = (1 + perc) / 2\n \n for i in range(len(Pred)):\n F[i] = stats.norm.cdf(Truth,\n loc=Pred[i],\n scale=Sigma)\n for proba_low, proba_upp in zip(plow, pupp):\n for k in range(len(plow)):\n if plow[k] < F[i] <= pupp[k]:\n Indicator_func[i, k] = 1\n else:\n Indicator_func[i, k] = 0\n\n avgIndFunc = np.mean(Indicator_func, axis=0)\n \n return avgIndFunc\n\ndef model_eval(y_test,Pred_array,Sigma,Pred):\n \n n_quantiles=11\n perc = np.linspace(0.0, 1.00, n_quantiles)\n \n Truth = y_test\n\n IF_array=np.zeros((Pred_array.shape[0],n_quantiles))\n\n for i in range(Pred_array.shape[0]):\n IF=APG_calc(Truth[i], Pred_array[:,i], Sigma[i],n_quantiles)\n IF_array[i,:] = IF\n \n avgIndFunc = np.mean(IF_array, axis=0)\n\n a = np.zeros(len(avgIndFunc))\n for i in range(len(avgIndFunc)):\n if avgIndFunc[i] > perc[i] or avgIndFunc[i] == perc[i]:\n a[i] = 1\n else:\n a[i] = 0\n\n Accuracy = integrate.simps(a, perc)\n\n Prec = a*(avgIndFunc-perc)\n \n Precision = 1-2*integrate.simps(Prec, perc)\n\n Sum = (3*a-2)*(avgIndFunc-perc)\n\n Goodness = 1-integrate.simps(Sum, perc)\n \n print('Accuracy = {0:1.2f}'.format(Accuracy))\n print('Precision = {0:1.2f}'.format(Precision))\n print('Goodness = {0:1.2f}'.format(Goodness))\n\n L = 100\n mean = np.empty((L, len(perc)))\n\n for p_interv in range(len(perc)):\n for l in np.arange(0, L):\n samples = random.choices(IF_array[:, p_interv],\n k=IF_array.shape[0])\n mean[l, p_interv] = np.mean(samples)\n\n mask = np.random.choice([False, True],\n len(Pred),\n p=[0.95, 0.05]) # To display randomly less points [Remove , Keep] in fraction\n\n fig,(ax1,ax2)=plt.subplots(1,2,figsize=(12,4))\n xline = [0,max(Pred.max(),Truth.max())+max(Pred.max(),Truth.max())*0.1]#\n yline = [0,xline[1]]#\n ax1.errorbar(Pred[mask], Truth[mask], xerr=Sigma[mask], \n fmt='k.',\n ecolor='k')\n ax1.plot(xline, yline, '-k')\n ax1.set_xlabel('Predicted value, $\\hat{y}$')\n ax1.set_ylabel('True value, $y$ ')\n ax2.plot(perc, avgIndFunc,'-ok',markersize=5)\n ax2.plot(perc,np.round(avgIndFunc+np.std(mean, axis=0), 3),'--k')\n ax2.plot(perc,np.round(avgIndFunc-np.std(mean, axis=0), 3),'--k')\n ax2.plot([0, 1],[0, 1],'-k')\n ax2.set_ylabel(r\"$\\overline{\\xi (p)}$\")\n ax2.set_xlabel('Probability interval $p$')\n ax2.set_ylim(0,1)\n ax2.set_xlim(0,1)\n ax2.plot(perc, avgIndFunc,'-ok',markersize=5)\n plt.show()\n \n return Accuracy,Precision,Goodness\n\ndef evaluate_cases(model, X_s, batch_size,y_s,n_samples):\n '''\n This function takes the model, the testing data, a batch size and an integer representing\n the number of samples that the model will produce.\n '''\n #Take n_samples to draw a distribution\n mc_predictions = np.zeros((n_samples, y_s.shape[0]))\n for i in range(n_samples):\n y_p = model.predict(X_s, verbose=1, batch_size=batch_size)\n mc_predictions[i] = (y_p[:,0])\n \n return mc_predictions\n\n\n```\n\n## Dataset exploration\n\nFor this notebook example we have a problem that consists on predicting **Production** from **Porosity**, **Permeability**, **Brittleness** and **TOC**. We have selected this problem because we are primarily interested in capturing the uncertainty related to predictions of Production based on existing data. \n\nThis problem can be expanded to any prediction problem.\n\nFirst lets import the dataset:\n\n\n```python\ndf=pd.read_csv('https://raw.githubusercontent.com/GeostatsGuy/GeoDataSets/master/unconv_MV.csv')\n```\n\nSome information about our dataset, we have 5 columns including Porosity, Permeability, Acoustic impedance, Density and Facies.\n\n\n```python\ndf.describe().transpose()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countmeanstdmin25%50%75%max
WellIndex1000.0500.500000288.8194361.000000250.75000500.50000750.2500001000.00000
Por1000.014.9504603.0296345.40000012.8575014.9850017.08000024.65000
LogPerm1000.01.3988800.4059660.1200001.130001.390001.6800002.58000
AI1000.02.9826100.5776290.9600002.577503.010003.3600004.70000
Brittle1000.049.71948015.077006-10.50000039.7225049.6800059.17000093.47000
TOC1000.01.0038100.504978-0.2600000.640000.995001.3600002.71000
VR1000.01.9911700.3081940.9000001.810002.000002.1725002.90000
Production1000.02247.2958091464.2563122.7135351191.369561976.487823023.59421412568.64413
\n
\n\n\n\nNow we separate or data between predictor features and response features.\nWe use Porosity, Permeability, Brittleness and Total Oil Content values to predict production\n\n\n```python\ny = df['Production'].values\nx = df[['Por', 'LogPerm', 'Brittle', 'TOC']].values\n```\n\n## Data normalization and split train-test\n\nTo speed up things, we can choose to randomly remove points of the dataset using the following code:\n\n```python\nmask = np.random.choice([False, True], len(x), p=[0.5, .5]) #Remove, Keep\n```\n\n\n```python\nmask = np.random.choice([False, True], len(x), p=[0, 1]) #Remove, Keep\nx=x[mask,:]\ny=y[mask]\n```\n\nThen we perform a min max normalization over the reponse features\n\n\n```python\nymin=y.min()\nymax=y.max()\ny = (y-ymin)/(ymax-ymin)\n```\n\nAnd apply standarization over the predictor features\n\n\n```python\nscaler = StandardScaler()\nx = scaler.fit_transform(x)\n```\n\nNext, we split our data in training-testing.\n\n\n```python\nX_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33,random_state=20)\n```\n\n## Neural network model, deterministic\n\nNext we define the neural network model under the class create_model. This is a classic deterministic model. We generate the exact same outcomes under a given set of initial conditions.\n\n\n\n```python\nclass create_model(keras.Model):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.input_layer = keras.layers.Flatten(input_shape=[x.shape[1]])\n self.hidden1 = keras.layers.Dense(24, activation='relu')\n self.hidden2 = keras.layers.Dense(24, activation='relu')\n self.hidden3 = keras.layers.Dense(24, activation='relu')\n self.output_layer = keras.layers.Dense(1)\n\n def call(self, input, training=True):\n input_layer = self.input_layer(input)\n hidden1 = self.hidden1(input_layer)\n hidden2 = self.hidden2(hidden1)\n output_layer = self.output_layer(hidden2)\n return output_layer\n```\n\nThe following information is used to save or load the model weights.\n\n\n```python\npath = \"\"\nname = \"Production_predict\"\nweights_path = path + name + '.h5'\n```\n\n### Training\n\nBefore training we must instantiate the model, lets use Mean Absolute Error as loss function to guide our model for better results.\n\n\n```python\nmodel = create_model()\n\nopt = keras.optimizers.Adam(learning_rate=0.01)\n\nmodel.compile(loss='mae',\n optimizer=opt,\n metrics='mse')\n```\n\nAnd fit our model\n\n\n```python\nhistory=model.fit(\n X_train,\n y_train,\n shuffle=True,\n batch_size=16,\n epochs=300,\n verbose=True,\n validation_data=(X_test,y_test)\n)\n```\n\n Epoch 1/300\n 42/42 [==============================] - 0s 4ms/step - loss: 0.0814 - mse: 0.0144 - val_loss: 0.0416 - val_mse: 0.0034\n Epoch 2/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0321 - mse: 0.0020 - val_loss: 0.0348 - val_mse: 0.0023\n Epoch 3/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0275 - mse: 0.0015 - val_loss: 0.0276 - val_mse: 0.0017\n Epoch 4/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0192 - mse: 7.2834e-04 - val_loss: 0.0239 - val_mse: 0.0015\n Epoch 5/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0217 - mse: 9.6677e-04 - val_loss: 0.0188 - val_mse: 0.0011\n Epoch 6/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0197 - mse: 8.8205e-04 - val_loss: 0.0237 - val_mse: 0.0013\n Epoch 7/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0216 - mse: 9.7121e-04 - val_loss: 0.0174 - val_mse: 0.0010\n Epoch 8/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0169 - mse: 7.0821e-04 - val_loss: 0.0208 - val_mse: 0.0011\n Epoch 9/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0136 - mse: 4.2520e-04 - val_loss: 0.0151 - val_mse: 7.7642e-04\n Epoch 10/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0130 - mse: 3.7688e-04 - val_loss: 0.0139 - val_mse: 7.4347e-04\n Epoch 11/300\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0154 - mse: 5.1280e-04 - val_loss: 0.0196 - val_mse: 0.0010\n Epoch 12/300\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0147 - mse: 4.3246e-04 - val_loss: 0.0134 - val_mse: 6.1520e-04\n Epoch 13/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0146 - mse: 5.4891e-04 - val_loss: 0.0167 - val_mse: 9.1230e-04\n Epoch 14/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0148 - mse: 5.1257e-04 - val_loss: 0.0157 - val_mse: 8.3598e-04\n Epoch 15/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0109 - mse: 2.9622e-04 - val_loss: 0.0126 - val_mse: 6.3203e-04\n Epoch 16/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0154 - mse: 5.1265e-04 - val_loss: 0.0114 - val_mse: 5.4699e-04\n Epoch 17/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0100 - mse: 2.4569e-04 - val_loss: 0.0106 - val_mse: 5.0593e-04\n Epoch 18/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0113 - mse: 2.6259e-04 - val_loss: 0.0188 - val_mse: 6.8315e-04\n Epoch 19/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0105 - mse: 2.4215e-04 - val_loss: 0.0111 - val_mse: 4.5334e-04\n Epoch 20/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0100 - mse: 2.1796e-04 - val_loss: 0.0102 - val_mse: 4.5106e-04\n Epoch 21/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0100 - mse: 2.3250e-04 - val_loss: 0.0143 - val_mse: 6.4058e-04\n Epoch 22/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0111 - mse: 2.4717e-04 - val_loss: 0.0105 - val_mse: 4.8525e-04\n Epoch 23/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0116 - mse: 2.7866e-04 - val_loss: 0.0140 - val_mse: 6.2280e-04\n Epoch 24/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0104 - mse: 2.2747e-04 - val_loss: 0.0106 - val_mse: 4.1180e-04\n Epoch 25/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.9595e-04 - val_loss: 0.0081 - val_mse: 3.2163e-04\n Epoch 26/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0111 - mse: 2.3746e-04 - val_loss: 0.0088 - val_mse: 3.7616e-04\n Epoch 27/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0077 - mse: 1.2487e-04 - val_loss: 0.0099 - val_mse: 4.1804e-04\n Epoch 28/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0110 - mse: 2.7573e-04 - val_loss: 0.0101 - val_mse: 3.9446e-04\n Epoch 29/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.3862e-04 - val_loss: 0.0106 - val_mse: 3.4492e-04\n Epoch 30/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.2542e-04 - val_loss: 0.0089 - val_mse: 4.0501e-04\n Epoch 31/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.9394e-04 - val_loss: 0.0118 - val_mse: 3.9765e-04\n Epoch 32/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0096 - mse: 1.8953e-04 - val_loss: 0.0115 - val_mse: 4.5696e-04\n Epoch 33/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0107 - mse: 2.4836e-04 - val_loss: 0.0122 - val_mse: 4.6006e-04\n Epoch 34/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.6931e-04 - val_loss: 0.0073 - val_mse: 2.2432e-04\n Epoch 35/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.1949e-04 - val_loss: 0.0079 - val_mse: 2.1966e-04\n Epoch 36/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0074 - mse: 1.4117e-04 - val_loss: 0.0142 - val_mse: 5.1516e-04\n Epoch 37/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0087 - mse: 1.7177e-04 - val_loss: 0.0085 - val_mse: 2.3251e-04\n Epoch 38/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0090 - mse: 1.6235e-04 - val_loss: 0.0110 - val_mse: 3.9395e-04\n Epoch 39/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0110 - mse: 2.2397e-04 - val_loss: 0.0186 - val_mse: 6.4351e-04\n Epoch 40/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0110 - mse: 2.3720e-04 - val_loss: 0.0180 - val_mse: 6.3284e-04\n Epoch 41/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0107 - mse: 2.6746e-04 - val_loss: 0.0099 - val_mse: 2.7985e-04\n Epoch 42/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.6761e-04 - val_loss: 0.0085 - val_mse: 2.5701e-04\n Epoch 43/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0080 - mse: 1.3475e-04 - val_loss: 0.0072 - val_mse: 1.3918e-04\n Epoch 44/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.3504e-04 - val_loss: 0.0078 - val_mse: 1.8957e-04\n Epoch 45/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0074 - mse: 1.2305e-04 - val_loss: 0.0089 - val_mse: 2.9211e-04\n Epoch 46/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.5870e-04 - val_loss: 0.0083 - val_mse: 1.7516e-04\n Epoch 47/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0072 - mse: 1.2776e-04 - val_loss: 0.0069 - val_mse: 3.1085e-04\n Epoch 48/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0070 - mse: 1.1037e-04 - val_loss: 0.0090 - val_mse: 1.9641e-04\n Epoch 49/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.2342e-04 - val_loss: 0.0087 - val_mse: 2.9335e-04\n Epoch 50/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.2199e-04 - val_loss: 0.0071 - val_mse: 1.6971e-04\n Epoch 51/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0083 - mse: 1.4028e-04 - val_loss: 0.0111 - val_mse: 3.7563e-04\n Epoch 52/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.7357e-04 - val_loss: 0.0091 - val_mse: 2.7233e-04\n Epoch 53/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.2993e-04 - val_loss: 0.0093 - val_mse: 2.9423e-04\n Epoch 54/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0078 - mse: 1.3151e-04 - val_loss: 0.0072 - val_mse: 2.2456e-04\n Epoch 55/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0090 - mse: 1.6556e-04 - val_loss: 0.0071 - val_mse: 1.9486e-04\n Epoch 56/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0072 - mse: 1.2739e-04 - val_loss: 0.0113 - val_mse: 3.4445e-04\n Epoch 57/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0070 - mse: 1.0624e-04 - val_loss: 0.0068 - val_mse: 1.9313e-04\n Epoch 58/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0075 - mse: 1.1394e-04 - val_loss: 0.0073 - val_mse: 1.7004e-04\n Epoch 59/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0095 - mse: 1.6963e-04 - val_loss: 0.0075 - val_mse: 2.1849e-04\n Epoch 60/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0086 - mse: 1.5963e-04 - val_loss: 0.0094 - val_mse: 2.2123e-04\n Epoch 61/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 8.4366e-05 - val_loss: 0.0077 - val_mse: 2.2877e-04\n Epoch 62/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0077 - mse: 1.3357e-04 - val_loss: 0.0066 - val_mse: 1.8032e-04\n Epoch 63/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0066 - mse: 9.2224e-05 - val_loss: 0.0073 - val_mse: 2.0599e-04\n Epoch 64/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 8.2988e-05 - val_loss: 0.0082 - val_mse: 1.9170e-04\n Epoch 65/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0077 - mse: 1.2470e-04 - val_loss: 0.0117 - val_mse: 3.3148e-04\n Epoch 66/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0077 - mse: 1.2306e-04 - val_loss: 0.0099 - val_mse: 2.6347e-04\n Epoch 67/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0074 - mse: 1.2708e-04 - val_loss: 0.0066 - val_mse: 1.6140e-04\n Epoch 68/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 7.8551e-05 - val_loss: 0.0069 - val_mse: 1.6546e-04\n Epoch 69/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 9.2213e-05 - val_loss: 0.0056 - val_mse: 1.2738e-04\n Epoch 70/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.9408e-05 - val_loss: 0.0066 - val_mse: 1.7455e-04\n Epoch 71/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.1460e-04 - val_loss: 0.0080 - val_mse: 2.1001e-04\n Epoch 72/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0077 - mse: 1.3617e-04 - val_loss: 0.0071 - val_mse: 1.7298e-04\n Epoch 73/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0075 - mse: 1.1852e-04 - val_loss: 0.0095 - val_mse: 2.2529e-04\n Epoch 74/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0079 - mse: 1.1709e-04 - val_loss: 0.0068 - val_mse: 2.0934e-04\n Epoch 75/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0075 - mse: 1.2801e-04 - val_loss: 0.0067 - val_mse: 1.9504e-04\n Epoch 76/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0089 - mse: 1.5742e-04 - val_loss: 0.0080 - val_mse: 2.4277e-04\n Epoch 77/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0081 - mse: 1.3807e-04 - val_loss: 0.0064 - val_mse: 2.4792e-04\n Epoch 78/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 8.3497e-05 - val_loss: 0.0080 - val_mse: 1.6929e-04\n Epoch 79/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.7929e-05 - val_loss: 0.0094 - val_mse: 3.2079e-04\n Epoch 80/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 1.1046e-04 - val_loss: 0.0084 - val_mse: 2.7403e-04\n Epoch 81/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 8.1145e-05 - val_loss: 0.0073 - val_mse: 1.7889e-04\n Epoch 82/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 7.3867e-05 - val_loss: 0.0110 - val_mse: 2.8726e-04\n Epoch 83/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 1.0777e-04 - val_loss: 0.0079 - val_mse: 1.2290e-04\n Epoch 84/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 9.9660e-05 - val_loss: 0.0080 - val_mse: 1.7097e-04\n Epoch 85/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0078 - mse: 1.2465e-04 - val_loss: 0.0123 - val_mse: 2.4871e-04\n Epoch 86/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0078 - mse: 1.3280e-04 - val_loss: 0.0110 - val_mse: 4.5761e-04\n Epoch 87/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.2276e-04 - val_loss: 0.0070 - val_mse: 1.8337e-04\n Epoch 88/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 5.5426e-05 - val_loss: 0.0097 - val_mse: 2.6099e-04\n Epoch 89/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0078 - mse: 1.2732e-04 - val_loss: 0.0054 - val_mse: 1.0984e-04\n Epoch 90/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.7590e-05 - val_loss: 0.0053 - val_mse: 8.7908e-05\n Epoch 91/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 7.9880e-05 - val_loss: 0.0066 - val_mse: 1.5811e-04\n Epoch 92/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 8.1073e-05 - val_loss: 0.0062 - val_mse: 1.0965e-04\n Epoch 93/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 7.7131e-05 - val_loss: 0.0082 - val_mse: 2.6179e-04\n Epoch 94/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 6.9024e-05 - val_loss: 0.0071 - val_mse: 1.4102e-04\n Epoch 95/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0069 - mse: 1.0865e-04 - val_loss: 0.0062 - val_mse: 1.8163e-04\n Epoch 96/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0069 - mse: 9.1299e-05 - val_loss: 0.0061 - val_mse: 1.3345e-04\n Epoch 97/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 7.9084e-05 - val_loss: 0.0062 - val_mse: 1.7969e-04\n Epoch 98/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0072 - mse: 1.1458e-04 - val_loss: 0.0082 - val_mse: 1.8245e-04\n Epoch 99/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0068 - mse: 8.9391e-05 - val_loss: 0.0073 - val_mse: 1.4253e-04\n Epoch 100/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 7.8243e-05 - val_loss: 0.0066 - val_mse: 1.3368e-04\n Epoch 101/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 1.0142e-04 - val_loss: 0.0081 - val_mse: 1.7462e-04\n Epoch 102/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 7.1083e-05 - val_loss: 0.0090 - val_mse: 1.9999e-04\n Epoch 103/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 7.7310e-05 - val_loss: 0.0055 - val_mse: 1.2330e-04\n Epoch 104/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 6.9998e-05 - val_loss: 0.0061 - val_mse: 1.5232e-04\n Epoch 105/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0077 - mse: 1.3061e-04 - val_loss: 0.0112 - val_mse: 2.4474e-04\n Epoch 106/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 6.8639e-05 - val_loss: 0.0061 - val_mse: 1.4186e-04\n Epoch 107/300\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0064 - mse: 9.0115e-05 - val_loss: 0.0079 - val_mse: 1.3575e-04\n Epoch 108/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0074 - mse: 1.1147e-04 - val_loss: 0.0067 - val_mse: 1.2212e-04\n Epoch 109/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 7.5483e-05 - val_loss: 0.0065 - val_mse: 1.4294e-04\n Epoch 110/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 7.6710e-05 - val_loss: 0.0047 - val_mse: 9.3679e-05\n Epoch 111/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0069 - mse: 9.7101e-05 - val_loss: 0.0090 - val_mse: 2.9455e-04\n Epoch 112/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.4727e-05 - val_loss: 0.0058 - val_mse: 1.4088e-04\n Epoch 113/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 9.0757e-05 - val_loss: 0.0081 - val_mse: 2.5385e-04\n Epoch 114/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.0066e-04 - val_loss: 0.0098 - val_mse: 3.0367e-04\n Epoch 115/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 9.9026e-05 - val_loss: 0.0067 - val_mse: 1.8737e-04\n Epoch 116/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 7.5559e-05 - val_loss: 0.0088 - val_mse: 1.4902e-04\n Epoch 117/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0083 - mse: 1.1594e-04 - val_loss: 0.0080 - val_mse: 1.5817e-04\n Epoch 118/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 9.1852e-05 - val_loss: 0.0080 - val_mse: 2.3247e-04\n Epoch 119/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.2927e-04 - val_loss: 0.0061 - val_mse: 1.2387e-04\n Epoch 120/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 6.8821e-05 - val_loss: 0.0080 - val_mse: 1.8310e-04\n Epoch 121/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 9.2615e-05 - val_loss: 0.0068 - val_mse: 1.6435e-04\n Epoch 122/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.2821e-05 - val_loss: 0.0070 - val_mse: 1.1260e-04\n Epoch 123/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0070 - mse: 9.1530e-05 - val_loss: 0.0072 - val_mse: 2.3776e-04\n Epoch 124/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 8.6660e-05 - val_loss: 0.0061 - val_mse: 1.7995e-04\n Epoch 125/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 6.0655e-05 - val_loss: 0.0081 - val_mse: 3.0223e-04\n Epoch 126/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 6.6649e-05 - val_loss: 0.0067 - val_mse: 1.8752e-04\n Epoch 127/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 6.8041e-05 - val_loss: 0.0067 - val_mse: 1.9133e-04\n Epoch 128/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0068 - mse: 9.9772e-05 - val_loss: 0.0087 - val_mse: 1.8831e-04\n Epoch 129/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0070 - mse: 9.8302e-05 - val_loss: 0.0069 - val_mse: 1.7968e-04\n Epoch 130/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.9842e-05 - val_loss: 0.0071 - val_mse: 1.0258e-04\n Epoch 131/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 7.1312e-05 - val_loss: 0.0075 - val_mse: 1.4695e-04\n Epoch 132/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 8.5862e-05 - val_loss: 0.0100 - val_mse: 2.6444e-04\n Epoch 133/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0068 - mse: 9.0690e-05 - val_loss: 0.0118 - val_mse: 4.1715e-04\n Epoch 134/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 1.0103e-04 - val_loss: 0.0056 - val_mse: 1.4445e-04\n Epoch 135/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 4.8866e-05 - val_loss: 0.0052 - val_mse: 1.4140e-04\n Epoch 136/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 6.8648e-05 - val_loss: 0.0065 - val_mse: 2.3243e-04\n Epoch 137/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.2946e-04 - val_loss: 0.0070 - val_mse: 1.5256e-04\n Epoch 138/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 7.3030e-05 - val_loss: 0.0061 - val_mse: 1.5503e-04\n Epoch 139/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.2716e-05 - val_loss: 0.0081 - val_mse: 1.8602e-04\n Epoch 140/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 8.4998e-05 - val_loss: 0.0082 - val_mse: 1.5034e-04\n Epoch 141/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 6.2398e-05 - val_loss: 0.0057 - val_mse: 1.1957e-04\n Epoch 142/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 6.6173e-05 - val_loss: 0.0056 - val_mse: 1.7083e-04\n Epoch 143/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 6.0733e-05 - val_loss: 0.0057 - val_mse: 1.0661e-04\n Epoch 144/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 8.0522e-05 - val_loss: 0.0064 - val_mse: 1.1473e-04\n Epoch 145/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.6711e-05 - val_loss: 0.0079 - val_mse: 1.1944e-04\n Epoch 146/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 7.4152e-05 - val_loss: 0.0098 - val_mse: 2.1069e-04\n Epoch 147/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.6855e-05 - val_loss: 0.0060 - val_mse: 1.3591e-04\n Epoch 148/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 6.3899e-05 - val_loss: 0.0070 - val_mse: 1.6339e-04\n Epoch 149/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 7.5358e-05 - val_loss: 0.0052 - val_mse: 1.1788e-04\n Epoch 150/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0044 - mse: 4.2842e-05 - val_loss: 0.0048 - val_mse: 1.0681e-04\n Epoch 151/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0072 - mse: 1.2054e-04 - val_loss: 0.0095 - val_mse: 3.0137e-04\n Epoch 152/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0066 - mse: 8.1178e-05 - val_loss: 0.0073 - val_mse: 2.0710e-04\n Epoch 153/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.5720e-05 - val_loss: 0.0048 - val_mse: 1.0204e-04\n Epoch 154/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0069 - mse: 9.0737e-05 - val_loss: 0.0091 - val_mse: 2.3716e-04\n Epoch 155/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.4583e-05 - val_loss: 0.0068 - val_mse: 1.6047e-04\n Epoch 156/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 6.0576e-05 - val_loss: 0.0059 - val_mse: 1.2939e-04\n Epoch 157/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 6.3907e-05 - val_loss: 0.0081 - val_mse: 1.7977e-04\n Epoch 158/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 7.3962e-05 - val_loss: 0.0106 - val_mse: 3.1322e-04\n Epoch 159/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0082 - mse: 1.5051e-04 - val_loss: 0.0045 - val_mse: 5.7628e-05\n Epoch 160/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 6.6603e-05 - val_loss: 0.0060 - val_mse: 9.9346e-05\n Epoch 161/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 5.5048e-05 - val_loss: 0.0064 - val_mse: 1.1103e-04\n Epoch 162/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.4024e-05 - val_loss: 0.0074 - val_mse: 1.3934e-04\n Epoch 163/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 5.5069e-05 - val_loss: 0.0053 - val_mse: 1.3712e-04\n Epoch 164/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0047 - mse: 4.6915e-05 - val_loss: 0.0079 - val_mse: 1.4469e-04\n Epoch 165/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0054 - mse: 6.3470e-05 - val_loss: 0.0082 - val_mse: 2.7247e-04\n Epoch 166/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.0336e-04 - val_loss: 0.0094 - val_mse: 2.3560e-04\n Epoch 167/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 6.8783e-05 - val_loss: 0.0053 - val_mse: 8.4373e-05\n Epoch 168/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 5.9468e-05 - val_loss: 0.0068 - val_mse: 1.5222e-04\n Epoch 169/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0073 - mse: 1.1458e-04 - val_loss: 0.0053 - val_mse: 1.1981e-04\n Epoch 170/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.7259e-05 - val_loss: 0.0049 - val_mse: 1.0878e-04\n Epoch 171/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 8.1650e-05 - val_loss: 0.0064 - val_mse: 1.3175e-04\n Epoch 172/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 6.3932e-05 - val_loss: 0.0047 - val_mse: 9.2474e-05\n Epoch 173/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 9.6580e-05 - val_loss: 0.0057 - val_mse: 1.4144e-04\n Epoch 174/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 4.9481e-05 - val_loss: 0.0043 - val_mse: 8.3490e-05\n Epoch 175/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0054 - mse: 5.8062e-05 - val_loss: 0.0057 - val_mse: 1.3072e-04\n Epoch 176/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 6.8270e-05 - val_loss: 0.0063 - val_mse: 1.4447e-04\n Epoch 177/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 8.5488e-05 - val_loss: 0.0068 - val_mse: 1.1309e-04\n Epoch 178/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 1.0531e-04 - val_loss: 0.0084 - val_mse: 1.8008e-04\n Epoch 179/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 6.2985e-05 - val_loss: 0.0045 - val_mse: 5.8746e-05\n Epoch 180/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0054 - mse: 5.6227e-05 - val_loss: 0.0061 - val_mse: 1.0869e-04\n Epoch 181/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 7.0476e-05 - val_loss: 0.0086 - val_mse: 1.6577e-04\n Epoch 182/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 8.1801e-05 - val_loss: 0.0048 - val_mse: 6.9696e-05\n Epoch 183/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.8887e-05 - val_loss: 0.0063 - val_mse: 7.5618e-05\n Epoch 184/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 7.3379e-05 - val_loss: 0.0058 - val_mse: 1.3934e-04\n Epoch 185/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0068 - mse: 9.1260e-05 - val_loss: 0.0075 - val_mse: 2.0659e-04\n Epoch 186/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 9.0080e-05 - val_loss: 0.0047 - val_mse: 6.5638e-05\n Epoch 187/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 6.1882e-05 - val_loss: 0.0062 - val_mse: 7.2243e-05\n Epoch 188/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 4.7554e-05 - val_loss: 0.0059 - val_mse: 1.1862e-04\n Epoch 189/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 8.3313e-05 - val_loss: 0.0068 - val_mse: 1.3685e-04\n Epoch 190/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0075 - mse: 1.0537e-04 - val_loss: 0.0051 - val_mse: 7.0838e-05\n Epoch 191/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.7702e-05 - val_loss: 0.0078 - val_mse: 1.7585e-04\n Epoch 192/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 6.4796e-05 - val_loss: 0.0060 - val_mse: 8.8326e-05\n Epoch 193/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 4.7219e-05 - val_loss: 0.0062 - val_mse: 1.5796e-04\n Epoch 194/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 5.1677e-05 - val_loss: 0.0067 - val_mse: 1.3277e-04\n Epoch 195/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 6.9632e-05 - val_loss: 0.0079 - val_mse: 1.5329e-04\n Epoch 196/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 9.0809e-05 - val_loss: 0.0057 - val_mse: 7.1136e-05\n Epoch 197/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 5.8524e-05 - val_loss: 0.0059 - val_mse: 1.4199e-04\n Epoch 198/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 6.9521e-05 - val_loss: 0.0061 - val_mse: 7.4527e-05\n Epoch 199/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 7.2456e-05 - val_loss: 0.0052 - val_mse: 1.5655e-04\n Epoch 200/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0047 - mse: 4.3549e-05 - val_loss: 0.0047 - val_mse: 5.5717e-05\n Epoch 201/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0047 - mse: 4.4822e-05 - val_loss: 0.0042 - val_mse: 7.8345e-05\n Epoch 202/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0048 - mse: 4.8816e-05 - val_loss: 0.0046 - val_mse: 9.4846e-05\n Epoch 203/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0070 - mse: 1.0794e-04 - val_loss: 0.0058 - val_mse: 1.6083e-04\n Epoch 204/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.6473e-05 - val_loss: 0.0052 - val_mse: 9.5970e-05\n Epoch 205/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0054 - mse: 6.1393e-05 - val_loss: 0.0037 - val_mse: 5.3126e-05\n Epoch 206/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 5.2160e-05 - val_loss: 0.0075 - val_mse: 1.1487e-04\n Epoch 207/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 6.2329e-05 - val_loss: 0.0045 - val_mse: 8.6454e-05\n Epoch 208/300\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0056 - mse: 7.1358e-05 - val_loss: 0.0079 - val_mse: 2.2958e-04\n Epoch 209/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 7.1106e-05 - val_loss: 0.0057 - val_mse: 9.5187e-05\n Epoch 210/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0046 - mse: 3.5775e-05 - val_loss: 0.0039 - val_mse: 5.2507e-05\n Epoch 211/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 5.4912e-05 - val_loss: 0.0052 - val_mse: 8.2427e-05\n Epoch 212/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.3008e-05 - val_loss: 0.0069 - val_mse: 1.4625e-04\n Epoch 213/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 7.0521e-05 - val_loss: 0.0060 - val_mse: 1.0048e-04\n Epoch 214/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0047 - mse: 4.2954e-05 - val_loss: 0.0073 - val_mse: 1.1561e-04\n Epoch 215/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 6.2314e-05 - val_loss: 0.0058 - val_mse: 1.0344e-04\n Epoch 216/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 4.5261e-05 - val_loss: 0.0069 - val_mse: 1.4167e-04\n Epoch 217/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 4.4381e-05 - val_loss: 0.0078 - val_mse: 1.3661e-04\n Epoch 218/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0069 - mse: 9.3258e-05 - val_loss: 0.0069 - val_mse: 1.1803e-04\n Epoch 219/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 6.7221e-05 - val_loss: 0.0051 - val_mse: 9.8572e-05\n Epoch 220/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0048 - mse: 4.8778e-05 - val_loss: 0.0054 - val_mse: 1.0263e-04\n Epoch 221/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 5.3534e-05 - val_loss: 0.0048 - val_mse: 9.5925e-05\n Epoch 222/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 6.7529e-05 - val_loss: 0.0065 - val_mse: 1.1518e-04\n Epoch 223/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0076 - mse: 1.1581e-04 - val_loss: 0.0062 - val_mse: 9.1742e-05\n Epoch 224/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 6.0290e-05 - val_loss: 0.0052 - val_mse: 8.1851e-05\n Epoch 225/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 5.2247e-05 - val_loss: 0.0045 - val_mse: 8.3312e-05\n Epoch 226/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0056 - mse: 6.6073e-05 - val_loss: 0.0062 - val_mse: 1.0039e-04\n Epoch 227/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.6409e-05 - val_loss: 0.0067 - val_mse: 1.5190e-04\n Epoch 228/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 7.0581e-05 - val_loss: 0.0090 - val_mse: 2.0530e-04\n Epoch 229/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0070 - mse: 9.1087e-05 - val_loss: 0.0052 - val_mse: 1.2105e-04\n Epoch 230/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.5316e-05 - val_loss: 0.0057 - val_mse: 7.6297e-05\n Epoch 231/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 5.1771e-05 - val_loss: 0.0071 - val_mse: 1.3378e-04\n Epoch 232/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 7.0156e-05 - val_loss: 0.0047 - val_mse: 1.2579e-04\n Epoch 233/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0046 - mse: 4.3290e-05 - val_loss: 0.0070 - val_mse: 1.1702e-04\n Epoch 234/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 7.3415e-05 - val_loss: 0.0057 - val_mse: 1.2236e-04\n Epoch 235/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0066 - mse: 8.6901e-05 - val_loss: 0.0046 - val_mse: 1.0557e-04\n Epoch 236/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0047 - mse: 4.1018e-05 - val_loss: 0.0042 - val_mse: 7.6049e-05\n Epoch 237/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 4.9177e-05 - val_loss: 0.0064 - val_mse: 1.4833e-04\n Epoch 238/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.7200e-05 - val_loss: 0.0067 - val_mse: 2.1210e-04\n Epoch 239/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 8.0688e-05 - val_loss: 0.0067 - val_mse: 1.3086e-04\n Epoch 240/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 6.1370e-05 - val_loss: 0.0051 - val_mse: 9.5057e-05\n Epoch 241/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0068 - mse: 8.2176e-05 - val_loss: 0.0077 - val_mse: 1.6205e-04\n Epoch 242/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 5.2551e-05 - val_loss: 0.0051 - val_mse: 6.8989e-05\n Epoch 243/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0049 - mse: 4.6727e-05 - val_loss: 0.0075 - val_mse: 1.2030e-04\n Epoch 244/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 8.1997e-05 - val_loss: 0.0085 - val_mse: 1.3121e-04\n Epoch 245/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 6.4805e-05 - val_loss: 0.0092 - val_mse: 1.8028e-04\n Epoch 246/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.2186e-05 - val_loss: 0.0064 - val_mse: 1.7425e-04\n Epoch 247/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0048 - mse: 4.3518e-05 - val_loss: 0.0054 - val_mse: 1.2773e-04\n Epoch 248/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 6.6771e-05 - val_loss: 0.0054 - val_mse: 1.5097e-04\n Epoch 249/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0066 - mse: 9.5822e-05 - val_loss: 0.0046 - val_mse: 7.3126e-05\n Epoch 250/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0044 - mse: 4.1224e-05 - val_loss: 0.0062 - val_mse: 1.3743e-04\n Epoch 251/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0048 - mse: 4.6620e-05 - val_loss: 0.0044 - val_mse: 1.0271e-04\n Epoch 252/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 7.5948e-05 - val_loss: 0.0068 - val_mse: 8.7230e-05\n Epoch 253/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0054 - mse: 5.4778e-05 - val_loss: 0.0044 - val_mse: 6.5804e-05\n Epoch 254/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0055 - mse: 6.3418e-05 - val_loss: 0.0055 - val_mse: 1.0392e-04\n Epoch 255/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.6216e-05 - val_loss: 0.0054 - val_mse: 6.0154e-05\n Epoch 256/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.4180e-05 - val_loss: 0.0043 - val_mse: 5.8443e-05\n Epoch 257/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 7.1766e-05 - val_loss: 0.0078 - val_mse: 1.2650e-04\n Epoch 258/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 7.9813e-05 - val_loss: 0.0049 - val_mse: 1.2098e-04\n Epoch 259/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 6.5999e-05 - val_loss: 0.0048 - val_mse: 1.1527e-04\n Epoch 260/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0074 - mse: 8.7428e-05 - val_loss: 0.0072 - val_mse: 1.8533e-04\n Epoch 261/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0079 - mse: 1.2692e-04 - val_loss: 0.0076 - val_mse: 1.0674e-04\n Epoch 262/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.8040e-05 - val_loss: 0.0052 - val_mse: 1.2378e-04\n Epoch 263/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.0862e-05 - val_loss: 0.0069 - val_mse: 1.3954e-04\n Epoch 264/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.8548e-05 - val_loss: 0.0063 - val_mse: 1.0337e-04\n Epoch 265/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 7.5242e-05 - val_loss: 0.0057 - val_mse: 1.8311e-04\n Epoch 266/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0053 - mse: 5.4029e-05 - val_loss: 0.0049 - val_mse: 5.9990e-05\n Epoch 267/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0060 - mse: 7.1162e-05 - val_loss: 0.0046 - val_mse: 9.5780e-05\n Epoch 268/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0069 - mse: 7.8567e-05 - val_loss: 0.0075 - val_mse: 2.4731e-04\n Epoch 269/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 8.2296e-05 - val_loss: 0.0087 - val_mse: 1.5353e-04\n Epoch 270/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0068 - mse: 1.0643e-04 - val_loss: 0.0069 - val_mse: 1.2236e-04\n Epoch 271/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.7793e-05 - val_loss: 0.0048 - val_mse: 1.2510e-04\n Epoch 272/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0047 - mse: 4.1083e-05 - val_loss: 0.0063 - val_mse: 1.4366e-04\n Epoch 273/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.6742e-05 - val_loss: 0.0049 - val_mse: 1.6983e-04\n Epoch 274/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0058 - mse: 6.0277e-05 - val_loss: 0.0073 - val_mse: 1.5486e-04\n Epoch 275/300\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0056 - mse: 6.4204e-05 - val_loss: 0.0080 - val_mse: 3.2585e-04\n Epoch 276/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 1.0421e-04 - val_loss: 0.0054 - val_mse: 1.3319e-04\n Epoch 277/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0046 - mse: 4.1245e-05 - val_loss: 0.0057 - val_mse: 9.8379e-05\n Epoch 278/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0054 - mse: 5.6719e-05 - val_loss: 0.0064 - val_mse: 1.4399e-04\n Epoch 279/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 8.8348e-05 - val_loss: 0.0067 - val_mse: 1.2456e-04\n Epoch 280/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 8.4842e-05 - val_loss: 0.0060 - val_mse: 1.5448e-04\n Epoch 281/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 4.8014e-05 - val_loss: 0.0047 - val_mse: 9.8158e-05\n Epoch 282/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.0804e-05 - val_loss: 0.0064 - val_mse: 1.3491e-04\n Epoch 283/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0063 - mse: 7.7454e-05 - val_loss: 0.0051 - val_mse: 5.3983e-05\n Epoch 284/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 4.9816e-05 - val_loss: 0.0096 - val_mse: 1.6865e-04\n Epoch 285/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0066 - mse: 8.5170e-05 - val_loss: 0.0060 - val_mse: 8.4507e-05\n Epoch 286/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0059 - mse: 6.3074e-05 - val_loss: 0.0066 - val_mse: 1.1274e-04\n Epoch 287/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0064 - mse: 7.5881e-05 - val_loss: 0.0056 - val_mse: 1.1819e-04\n Epoch 288/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0051 - mse: 4.8760e-05 - val_loss: 0.0050 - val_mse: 8.6427e-05\n Epoch 289/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0071 - mse: 8.5625e-05 - val_loss: 0.0071 - val_mse: 1.2134e-04\n Epoch 290/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0067 - mse: 8.8004e-05 - val_loss: 0.0077 - val_mse: 1.1360e-04\n Epoch 291/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0061 - mse: 7.4987e-05 - val_loss: 0.0064 - val_mse: 2.5261e-04\n Epoch 292/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0057 - mse: 6.6741e-05 - val_loss: 0.0113 - val_mse: 2.2855e-04\n Epoch 293/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0093 - mse: 1.6509e-04 - val_loss: 0.0056 - val_mse: 1.0089e-04\n Epoch 294/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0052 - mse: 4.9412e-05 - val_loss: 0.0054 - val_mse: 6.5134e-05\n Epoch 295/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 5.0847e-05 - val_loss: 0.0082 - val_mse: 1.7439e-04\n Epoch 296/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.6717e-05 - val_loss: 0.0052 - val_mse: 8.8916e-05\n Epoch 297/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0050 - mse: 4.7274e-05 - val_loss: 0.0060 - val_mse: 1.0869e-04\n Epoch 298/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0065 - mse: 8.1333e-05 - val_loss: 0.0073 - val_mse: 1.6940e-04\n Epoch 299/300\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0062 - mse: 7.4596e-05 - val_loss: 0.0044 - val_mse: 6.9456e-05\n Epoch 300/300\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0054 - mse: 5.4123e-05 - val_loss: 0.0044 - val_mse: 4.4640e-05\n\n\nWe plot the loss function to diagnostic the model and the dataset, from the plot we can identify\n\n- A separation between the test and train loss function might indicate overfitting\n- A large gap between the curves might indicate an unrepresentative train dataset\n\n\n\n```python\nplot_loss(history)\n```\n\nNext we predict and compare our predictions with the observed occurrences. Now this model is very accurate and for every combination of predictor features we will have the exact same outcome.\n\n\n```python\ny_test_pred = model.predict(X_test)\nplt.figure(figsize=(12,6))\nplt.plot(X_test[:,0],y_test,'o',label='Test')\nplt.plot(X_test[:,0],y_test_pred,'o',label='Predicted test')\nplt.xlabel('Porosity')\nplt.ylabel('Production')\nplt.legend()\nplt.grid(True)\n```\n\nThe next thing we do is we test the goodness of the model. Lets evaluate the model 10 times to estimate the Goodness, Precision and Acurracy of the model. \n\nWe could only do this once, because of the deterministic nature of the model, all 10 evaluations we will give the same result\n\n\n```python\nmc_predictions = evaluate_cases(model, X_test, 8, y_test,10)\ndf = get_dataframe(mc_predictions, y_test, X_test)\n```\n\n 42/42 [==============================] - 0s 559us/step\n 42/42 [==============================] - 0s 512us/step\n 42/42 [==============================] - 0s 487us/step\n 42/42 [==============================] - 0s 534us/step\n 42/42 [==============================] - 0s 511us/step\n 42/42 [==============================] - 0s 511us/step\n 42/42 [==============================] - 0s 535us/step\n 42/42 [==============================] - 0s 536us/step\n 42/42 [==============================] - 0s 632us/step\n 42/42 [==============================] - 0s 585us/step\n\n\nHow does the cross plot for predicted versus true value look like?\n\nWhat about the Pearson's product moment correlation coefficient?\n\n\n```python\nr= stats.pearsonr(df.Pred,df.Truth)\nerror_line(df.Pred,df.Truth,df.Sigma,r[0])\n```\n\nWhat is the Goodness, Precision and Accuracy of the model?\n\n\n```python\nSigma = np.sqrt(np.var(mc_predictions.T, axis=1))\n\nscore = scorer(mc_predictions.T, y_test, Sigma)\n\nIF_array = score.IndicatorFunction()\nn_quantiles = 11\nperc = np.linspace(0.0, 1.00, n_quantiles)\n\n```\n\n C:\\Users\\em42363\\Anaconda3\\envs\\new\\lib\\site-packages\\scipy\\stats\\_distn_infrastructure.py:1987: RuntimeWarning: divide by zero encountered in double_scalars\n x = np.asarray((x - loc)/scale, dtype=dtyp)\n\n\nVery precise! But inaccurate\n\n\n```python\nprint('Accuracy = {0:2.2f}'.format(score.Accuracy()))\nprint('Precision = {0:2.2f}'.format(score.Precision()))\nprint('Goodness = {0:2.2f}'.format(score.Goodness()))\n```\n\n Accuracy = 0.03\n Precision = 1.00\n Goodness = -0.02\n\n\nThe precision is 1 and the goodness is 0!! The model is inaccurate and precise\n\nHow does the histogram of predictions for a random case look like? All 10 occurrences have the same result\n\n\n```python\nhistogram(mc_predictions)\n```\n\nWe can use the accuracy plot to diagnose our model. You can find more details on the use of the accuracy plots in the provided article.\n\nHow does the accuracy plot look like for a deterministic model?\n\n\n```python\nerror_accuracy_plot(perc, IF_array, mc_predictions.T, y_test, Sigma)\n```\n\nOur model is **inaccurate and imprecise.**\n\n## Neural network model, probabilistic\n\nFor this second model we use **dropout** to introduce randomness into our model\n\n### Neural network model\n\nSimilarly as before, we define the model and include dropout layers in our deep learning model.\n\n\n```python\ndef PermaDropout(rate):\n return Lambda(lambda x: K.dropout(x, level=rate)) # Fraction of the input units to drop\n\nclass create_model(keras.Model):\n def __init__(self,dropout, **kwargs):\n super().__init__(**kwargs)\n self.input_layer = keras.layers.Flatten(input_shape=[x.shape[1]])\n self.hidden1 = keras.layers.Dense(32, activation='relu')\n self.hidden2 = keras.layers.Dense(32, activation='relu')\n self.hidden3 = keras.layers.Dense(32, activation='relu')\n self.output_layer = keras.layers.Dense(1)\n self.dropout_layer = PermaDropout(rate=dropout)\n\n def call(self, input, training=True):\n input_layer = self.input_layer(input)\n input_layer = self.dropout_layer(input_layer)\n hidden1 = self.hidden1(input_layer)\n hidden1 = self.dropout_layer(hidden1, training=training)\n hidden2 = self.hidden2(hidden1)\n hidden2 = self.dropout_layer(hidden2, training=training)\n #hidden3 = self.hidden3(hidden2)\n #hidden3 = self.dropout_layer(hidden3, training=training)\n output_layer = self.output_layer(hidden2)\n return output_layer\n```\n\n### Training\n\nWe instantiate the model and define a dropout value that was previously optimized using the uncertainty model goodness metric\n\n\n```python\n#model = create_model(0.0525)\nmodel = create_model(0.06)\nopt = keras.optimizers.Adam(learning_rate=0.016)\n\nmodel.compile(loss='mae',\n optimizer=opt,\n metrics='mse')\n```\n\n\n```python\nhistory=model.fit(\n X_train,\n y_train,\n batch_size=16,\n epochs=100,\n verbose=True,\n validation_data=(X_test,y_test)\n)\n```\n\n Epoch 1/100\n 42/42 [==============================] - 1s 3ms/step - loss: 0.0813 - mse: 0.0138 - val_loss: 0.0475 - val_mse: 0.0058\n Epoch 2/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0385 - mse: 0.0033 - val_loss: 0.0410 - val_mse: 0.0047\n Epoch 3/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0331 - mse: 0.0026 - val_loss: 0.0254 - val_mse: 0.0019\n Epoch 4/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0273 - mse: 0.0019 - val_loss: 0.0276 - val_mse: 0.0024\n Epoch 5/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0274 - mse: 0.0018 - val_loss: 0.0298 - val_mse: 0.0028\n Epoch 6/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0300 - mse: 0.0029 - val_loss: 0.0279 - val_mse: 0.0025\n Epoch 7/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0276 - mse: 0.0024 - val_loss: 0.0284 - val_mse: 0.0022\n Epoch 8/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0302 - mse: 0.0020 - val_loss: 0.0306 - val_mse: 0.0019\n Epoch 9/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0322 - mse: 0.0025 - val_loss: 0.0351 - val_mse: 0.0024\n Epoch 10/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0369 - mse: 0.0030 - val_loss: 0.0431 - val_mse: 0.0033\n Epoch 11/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0352 - mse: 0.0028 - val_loss: 0.0291 - val_mse: 0.0025\n Epoch 12/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0293 - mse: 0.0021 - val_loss: 0.0367 - val_mse: 0.0031\n Epoch 13/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0268 - mse: 0.0017 - val_loss: 0.0285 - val_mse: 0.0023\n Epoch 14/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0283 - mse: 0.0023 - val_loss: 0.0224 - val_mse: 0.0020\n Epoch 15/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0273 - mse: 0.0019 - val_loss: 0.0237 - val_mse: 0.0015\n Epoch 16/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0270 - mse: 0.0019 - val_loss: 0.0230 - val_mse: 0.0019\n Epoch 17/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0280 - mse: 0.0023 - val_loss: 0.0302 - val_mse: 0.0027\n Epoch 18/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0270 - mse: 0.0019 - val_loss: 0.0313 - val_mse: 0.0028\n Epoch 19/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0295 - mse: 0.0023 - val_loss: 0.0279 - val_mse: 0.0026\n Epoch 20/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0269 - mse: 0.0017 - val_loss: 0.0275 - val_mse: 0.0023\n Epoch 21/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0284 - mse: 0.0024 - val_loss: 0.0259 - val_mse: 0.0019\n Epoch 22/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0281 - mse: 0.0022 - val_loss: 0.0274 - val_mse: 0.0023\n Epoch 23/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0280 - mse: 0.0021 - val_loss: 0.0248 - val_mse: 0.0015\n Epoch 24/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0260 - mse: 0.0017 - val_loss: 0.0299 - val_mse: 0.0022\n Epoch 25/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0296 - mse: 0.0025 - val_loss: 0.0291 - val_mse: 0.0030\n Epoch 26/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0261 - mse: 0.0016 - val_loss: 0.0290 - val_mse: 0.0024\n Epoch 27/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0262 - mse: 0.0021 - val_loss: 0.0257 - val_mse: 0.0023\n Epoch 28/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0270 - mse: 0.0019 - val_loss: 0.0248 - val_mse: 0.0020\n Epoch 29/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0261 - mse: 0.0019 - val_loss: 0.0237 - val_mse: 0.0018\n Epoch 30/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0287 - mse: 0.0021 - val_loss: 0.0333 - val_mse: 0.0035\n Epoch 31/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0296 - mse: 0.0023 - val_loss: 0.0265 - val_mse: 0.0024\n Epoch 32/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0302 - mse: 0.0025 - val_loss: 0.0341 - val_mse: 0.0023\n Epoch 33/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0271 - mse: 0.0016 - val_loss: 0.0312 - val_mse: 0.0035\n Epoch 34/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0265 - mse: 0.0021 - val_loss: 0.0308 - val_mse: 0.0027\n Epoch 35/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0311 - mse: 0.0024 - val_loss: 0.0288 - val_mse: 0.0028\n Epoch 36/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0295 - mse: 0.0027 - val_loss: 0.0279 - val_mse: 0.0018\n Epoch 37/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0285 - mse: 0.0020 - val_loss: 0.0219 - val_mse: 0.0019\n Epoch 38/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0274 - mse: 0.0023 - val_loss: 0.0302 - val_mse: 0.0022\n Epoch 39/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0258 - mse: 0.0016 - val_loss: 0.0295 - val_mse: 0.0021\n Epoch 40/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0269 - mse: 0.0022 - val_loss: 0.0269 - val_mse: 0.0020\n Epoch 41/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0296 - mse: 0.0022 - val_loss: 0.0306 - val_mse: 0.0023\n Epoch 42/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0281 - mse: 0.0023 - val_loss: 0.0306 - val_mse: 0.0031\n Epoch 43/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0278 - mse: 0.0024 - val_loss: 0.0254 - val_mse: 0.0025\n Epoch 44/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0231 - mse: 0.0015 - val_loss: 0.0263 - val_mse: 0.0034\n Epoch 45/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0290 - mse: 0.0024 - val_loss: 0.0283 - val_mse: 0.0031\n Epoch 46/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0277 - mse: 0.0018 - val_loss: 0.0251 - val_mse: 0.0013\n Epoch 47/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0246 - mse: 0.0017 - val_loss: 0.0298 - val_mse: 0.0020\n Epoch 48/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0254 - mse: 0.0021 - val_loss: 0.0258 - val_mse: 0.0018\n Epoch 49/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0285 - mse: 0.0022 - val_loss: 0.0265 - val_mse: 0.0016\n Epoch 50/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0286 - mse: 0.0028 - val_loss: 0.0261 - val_mse: 0.0018\n Epoch 51/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0241 - mse: 0.0017 - val_loss: 0.0260 - val_mse: 0.0019\n Epoch 52/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0242 - mse: 0.0016 - val_loss: 0.0251 - val_mse: 0.0018\n Epoch 53/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0233 - mse: 0.0014 - val_loss: 0.0259 - val_mse: 0.0028\n Epoch 54/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0236 - mse: 0.0014 - val_loss: 0.0262 - val_mse: 0.0025\n Epoch 55/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0256 - mse: 0.0019 - val_loss: 0.0274 - val_mse: 0.0021\n Epoch 56/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0274 - mse: 0.0021 - val_loss: 0.0292 - val_mse: 0.0029\n Epoch 57/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0267 - mse: 0.0020 - val_loss: 0.0211 - val_mse: 0.0017\n Epoch 58/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0260 - mse: 0.0018 - val_loss: 0.0277 - val_mse: 0.0027\n Epoch 59/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0282 - mse: 0.0021 - val_loss: 0.0249 - val_mse: 0.0016\n Epoch 60/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0264 - mse: 0.0016 - val_loss: 0.0241 - val_mse: 0.0015\n Epoch 61/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0276 - mse: 0.0023 - val_loss: 0.0238 - val_mse: 0.0021\n Epoch 62/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0257 - mse: 0.0017 - val_loss: 0.0306 - val_mse: 0.0029\n Epoch 63/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0248 - mse: 0.0017 - val_loss: 0.0248 - val_mse: 0.0019\n Epoch 64/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0241 - mse: 0.0022 - val_loss: 0.0248 - val_mse: 0.0016\n Epoch 65/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0270 - mse: 0.0021 - val_loss: 0.0287 - val_mse: 0.0025\n Epoch 66/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0248 - mse: 0.0019 - val_loss: 0.0257 - val_mse: 0.0019\n Epoch 67/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0252 - mse: 0.0018 - val_loss: 0.0221 - val_mse: 0.0017\n Epoch 68/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0245 - mse: 0.0018 - val_loss: 0.0251 - val_mse: 0.0018\n Epoch 69/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0307 - mse: 0.0029 - val_loss: 0.0275 - val_mse: 0.0021\n Epoch 70/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0240 - mse: 0.0023 - val_loss: 0.0289 - val_mse: 0.0017\n Epoch 71/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0243 - mse: 0.0015 - val_loss: 0.0236 - val_mse: 0.0015\n Epoch 72/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0280 - mse: 0.0022 - val_loss: 0.0291 - val_mse: 0.0024\n Epoch 73/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0285 - mse: 0.0018 - val_loss: 0.0258 - val_mse: 0.0019\n Epoch 74/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0230 - mse: 0.0017 - val_loss: 0.0235 - val_mse: 0.0018\n Epoch 75/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0248 - mse: 0.0020 - val_loss: 0.0249 - val_mse: 0.0016\n Epoch 76/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0262 - mse: 0.0028 - val_loss: 0.0318 - val_mse: 0.0039\n Epoch 77/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0254 - mse: 0.0018 - val_loss: 0.0221 - val_mse: 0.0017\n Epoch 78/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0241 - mse: 0.0016 - val_loss: 0.0255 - val_mse: 0.0019\n Epoch 79/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0255 - mse: 0.0019 - val_loss: 0.0301 - val_mse: 0.0022\n Epoch 80/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0250 - mse: 0.0019 - val_loss: 0.0299 - val_mse: 0.0029\n Epoch 81/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0261 - mse: 0.0025 - val_loss: 0.0259 - val_mse: 0.0023\n Epoch 82/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0211 - mse: 0.0011 - val_loss: 0.0257 - val_mse: 0.0025\n Epoch 83/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0277 - mse: 0.0022 - val_loss: 0.0295 - val_mse: 0.0025\n Epoch 84/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0272 - mse: 0.0021 - val_loss: 0.0282 - val_mse: 0.0026\n Epoch 85/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0235 - mse: 0.0016 - val_loss: 0.0234 - val_mse: 0.0018\n Epoch 86/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0262 - mse: 0.0019 - val_loss: 0.0262 - val_mse: 0.0027\n Epoch 87/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0249 - mse: 0.0020 - val_loss: 0.0270 - val_mse: 0.0032\n Epoch 88/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0272 - mse: 0.0019 - val_loss: 0.0304 - val_mse: 0.0023\n Epoch 89/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0297 - mse: 0.0024 - val_loss: 0.0321 - val_mse: 0.0032\n Epoch 90/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0236 - mse: 0.0016 - val_loss: 0.0273 - val_mse: 0.0032\n Epoch 91/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0238 - mse: 0.0016 - val_loss: 0.0253 - val_mse: 0.0020\n Epoch 92/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0238 - mse: 0.0017 - val_loss: 0.0283 - val_mse: 0.0038\n Epoch 93/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0250 - mse: 0.0017 - val_loss: 0.0272 - val_mse: 0.0032\n Epoch 94/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0216 - mse: 0.0015 - val_loss: 0.0245 - val_mse: 0.0025\n Epoch 95/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0264 - mse: 0.0019 - val_loss: 0.0282 - val_mse: 0.0021\n Epoch 96/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0291 - mse: 0.0027 - val_loss: 0.0236 - val_mse: 0.0022\n Epoch 97/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0223 - mse: 0.0014 - val_loss: 0.0259 - val_mse: 0.0022\n Epoch 98/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0255 - mse: 0.0016 - val_loss: 0.0335 - val_mse: 0.0035\n Epoch 99/100\n 42/42 [==============================] - 0s 1ms/step - loss: 0.0232 - mse: 0.0013 - val_loss: 0.0243 - val_mse: 0.0019\n Epoch 100/100\n 42/42 [==============================] - 0s 2ms/step - loss: 0.0255 - mse: 0.0023 - val_loss: 0.0304 - val_mse: 0.0026\n\n\nNext we plot the loss for the training and testing dataset. We observe no overfitting in our model. We had to increase the number of epochs because of the regularization parameter\n\n\n```python\nplot_loss(history)\n```\n\n\n```python\ny_test_pred = model.predict(X_test)\n\nplt.figure(figsize=(12,6))\nplt.plot(X_test[:,0],y_test,'o',label='Test')\nplt.plot(X_test[:,0],y_test_pred,'o',label='Predicted test')\n\nplt.xlabel('Porosity')\nplt.ylabel('Production')\nplt.legend()\nplt.grid(True)\n```\n\n### Goodness of the uncertainty model\n\nLet's evaluate the goodness of the model.\n\nThis is no longer a deterministic approach and we will evaluate the model only 200 times, next we will print the Goodness, Precision and Acurracy of the model.\n\n\n```python\nmc_predictions = evaluate_cases(model, X_test, 8, y_test,200)\n```\n\n 42/42 [==============================] - 0s 576us/step\n 42/42 [==============================] - 0s 551us/step\n 42/42 [==============================] - 0s 512us/step\n 42/42 [==============================] - 0s 525us/step\n 42/42 [==============================] - 0s 572us/step\n 42/42 [==============================] - 0s 539us/step\n 42/42 [==============================] - 0s 537us/step\n 42/42 [==============================] - 0s 579us/step\n 42/42 [==============================] - 0s 540us/step\n 42/42 [==============================] - 0s 517us/step\n 42/42 [==============================] - 0s 517us/step\n 42/42 [==============================] - 0s 563us/step\n 42/42 [==============================] - 0s 543us/step\n 42/42 [==============================] - 0s 553us/step\n 42/42 [==============================] - 0s 518us/step\n 42/42 [==============================] - 0s 504us/step\n 42/42 [==============================] - 0s 530us/step\n 42/42 [==============================] - 0s 553us/step\n 42/42 [==============================] - 0s 565us/step\n 42/42 [==============================] - 0s 526us/step\n 42/42 [==============================] - 0s 543us/step\n 42/42 [==============================] - 0s 537us/step\n 42/42 [==============================] - 0s 502us/step\n 42/42 [==============================] - 0s 529us/step\n 42/42 [==============================] - 0s 532us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 495us/step\n 42/42 [==============================] - 0s 520us/step\n 42/42 [==============================] - 0s 531us/step\n 42/42 [==============================] - 0s 525us/step\n 42/42 [==============================] - 0s 522us/step\n 42/42 [==============================] - 0s 503us/step\n 42/42 [==============================] - 0s 538us/step\n 42/42 [==============================] - 0s 504us/step\n 42/42 [==============================] - 0s 514us/step\n 42/42 [==============================] - 0s 541us/step\n 42/42 [==============================] - 0s 500us/step\n 42/42 [==============================] - 0s 506us/step\n 42/42 [==============================] - 0s 523us/step\n 42/42 [==============================] - 0s 483us/step\n 42/42 [==============================] - 0s 516us/step\n 42/42 [==============================] - 0s 507us/step\n 42/42 [==============================] - 0s 484us/step\n 42/42 [==============================] - 0s 534us/step\n 42/42 [==============================] - 0s 510us/step\n 42/42 [==============================] - 0s 554us/step\n 42/42 [==============================] - 0s 492us/step\n 42/42 [==============================] - 0s 504us/step\n 42/42 [==============================] - 0s 503us/step\n 42/42 [==============================] - 0s 508us/step\n 42/42 [==============================] - 0s 523us/step\n 42/42 [==============================] - 0s 545us/step\n 42/42 [==============================] - 0s 535us/step\n 42/42 [==============================] - 0s 533us/step\n 42/42 [==============================] - 0s 502us/step\n 42/42 [==============================] - 0s 483us/step\n 42/42 [==============================] - 0s 533us/step\n 42/42 [==============================] - 0s 510us/step\n 42/42 [==============================] - 0s 537us/step\n 42/42 [==============================] - 0s 539us/step\n 42/42 [==============================] - 0s 514us/step\n 42/42 [==============================] - 0s 535us/step\n 42/42 [==============================] - 0s 535us/step\n 42/42 [==============================] - 0s 521us/step\n 42/42 [==============================] - 0s 537us/step\n 42/42 [==============================] - 0s 499us/step\n 42/42 [==============================] - 0s 509us/step\n 42/42 [==============================] - 0s 489us/step\n 42/42 [==============================] - 0s 512us/step\n 42/42 [==============================] - 0s 500us/step\n 42/42 [==============================] - 0s 536us/step\n 42/42 [==============================] - 0s 583us/step\n 42/42 [==============================] - 0s 585us/step\n 42/42 [==============================] - 0s 556us/step\n 42/42 [==============================] - 0s 512us/step\n 42/42 [==============================] - 0s 485us/step\n 42/42 [==============================] - 0s 536us/step\n 42/42 [==============================] - 0s 549us/step\n 42/42 [==============================] - 0s 545us/step\n 42/42 [==============================] - 0s 522us/step\n 42/42 [==============================] - 0s 511us/step\n 42/42 [==============================] - 0s 508us/step\n 42/42 [==============================] - 0s 497us/step\n 42/42 [==============================] - 0s 542us/step\n 42/42 [==============================] - 0s 548us/step\n 42/42 [==============================] - 0s 522us/step\n 42/42 [==============================] - 0s 521us/step\n 42/42 [==============================] - 0s 512us/step\n 42/42 [==============================] - 0s 533us/step\n 42/42 [==============================] - 0s 493us/step\n 42/42 [==============================] - 0s 493us/step\n 42/42 [==============================] - 0s 522us/step\n 42/42 [==============================] - 0s 518us/step\n 42/42 [==============================] - 0s 520us/step\n 42/42 [==============================] - 0s 527us/step\n 42/42 [==============================] - 0s 499us/step\n 42/42 [==============================] - 0s 543us/step\n 42/42 [==============================] - 0s 527us/step\n 42/42 [==============================] - 0s 562us/step\n 42/42 [==============================] - 0s 532us/step\n 42/42 [==============================] - 0s 528us/step\n 42/42 [==============================] - 0s 528us/step\n 42/42 [==============================] - 0s 508us/step\n 42/42 [==============================] - 0s 601us/step\n 42/42 [==============================] - 0s 517us/step\n 42/42 [==============================] - 0s 525us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 538us/step\n 42/42 [==============================] - 0s 553us/step\n 42/42 [==============================] - 0s 494us/step\n 42/42 [==============================] - 0s 497us/step\n 42/42 [==============================] - 0s 563us/step\n 42/42 [==============================] - 0s 514us/step\n 42/42 [==============================] - 0s 496us/step\n 42/42 [==============================] - 0s 510us/step\n 42/42 [==============================] - 0s 507us/step\n 42/42 [==============================] - 0s 494us/step\n 42/42 [==============================] - 0s 544us/step\n 42/42 [==============================] - 0s 489us/step\n 42/42 [==============================] - 0s 527us/step\n 42/42 [==============================] - 0s 561us/step\n 42/42 [==============================] - 0s 504us/step\n 42/42 [==============================] - 0s 503us/step\n 42/42 [==============================] - 0s 513us/step\n 42/42 [==============================] - 0s 487us/step\n 42/42 [==============================] - 0s 533us/step\n 42/42 [==============================] - 0s 504us/step\n 42/42 [==============================] - 0s 511us/step\n 42/42 [==============================] - 0s 553us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 501us/step\n 42/42 [==============================] - 0s 511us/step\n 42/42 [==============================] - 0s 508us/step\n 42/42 [==============================] - 0s 559us/step\n 42/42 [==============================] - 0s 554us/step\n 42/42 [==============================] - 0s 516us/step\n 42/42 [==============================] - 0s 566us/step\n 42/42 [==============================] - 0s 501us/step\n 42/42 [==============================] - 0s 619us/step\n 42/42 [==============================] - 0s 657us/step\n 42/42 [==============================] - 0s 754us/step\n 42/42 [==============================] - 0s 657us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 570us/step\n 42/42 [==============================] - 0s 542us/step\n 42/42 [==============================] - 0s 463us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 539us/step\n 42/42 [==============================] - 0s 543us/step\n 42/42 [==============================] - 0s 497us/step\n 42/42 [==============================] - 0s 525us/step\n 42/42 [==============================] - 0s 512us/step\n 42/42 [==============================] - 0s 524us/step\n 42/42 [==============================] - 0s 536us/step\n 42/42 [==============================] - 0s 499us/step\n 42/42 [==============================] - 0s 545us/step\n 42/42 [==============================] - 0s 520us/step\n 42/42 [==============================] - 0s 556us/step\n 42/42 [==============================] - 0s 555us/step\n 42/42 [==============================] - 0s 544us/step\n 42/42 [==============================] - 0s 548us/step\n 42/42 [==============================] - 0s 486us/step\n 42/42 [==============================] - 0s 485us/step\n 42/42 [==============================] - 0s 499us/step\n 42/42 [==============================] - 0s 523us/step\n 42/42 [==============================] - 0s 485us/step\n 42/42 [==============================] - 0s 528us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 469us/step\n 42/42 [==============================] - 0s 475us/step\n 42/42 [==============================] - 0s 473us/step\n 42/42 [==============================] - 0s 574us/step\n 42/42 [==============================] - 0s 486us/step\n 42/42 [==============================] - 0s 536us/step\n 42/42 [==============================] - 0s 499us/step\n 42/42 [==============================] - 0s 514us/step\n 42/42 [==============================] - 0s 514us/step\n 42/42 [==============================] - 0s 642us/step\n 42/42 [==============================] - 0s 566us/step\n 42/42 [==============================] - 0s 532us/step\n 42/42 [==============================] - 0s 496us/step\n 42/42 [==============================] - 0s 513us/step\n 42/42 [==============================] - 0s 514us/step\n 42/42 [==============================] - 0s 534us/step\n 42/42 [==============================] - 0s 561us/step\n 42/42 [==============================] - 0s 518us/step\n 42/42 [==============================] - 0s 584us/step\n 42/42 [==============================] - 0s 698us/step\n 42/42 [==============================] - 0s 559us/step\n 42/42 [==============================] - 0s 585us/step\n 42/42 [==============================] - 0s 584us/step\n 42/42 [==============================] - 0s 560us/step\n 42/42 [==============================] - 0s 584us/step\n 42/42 [==============================] - 0s 618us/step\n 42/42 [==============================] - 0s 535us/step\n 42/42 [==============================] - 0s 511us/step\n 42/42 [==============================] - 0s 515us/step\n 42/42 [==============================] - 0s 584us/step\n 42/42 [==============================] - 0s 778us/step\n 42/42 [==============================] - 0s 608us/step\n\n\n\n```python\ndf = get_dataframe(mc_predictions, y_test, X_test)\n```\n\nHow does the cross validation plot look like?\nWhat about the Pearson's product moment correlation coefficient?\n\n\n```python\nr= stats.pearsonr(df.Pred,df.Truth)\nerror_line(df.Pred,df.Truth,df.Sigma,r[0])\n```\n\nWhat is the Goodness, Precision and Accuracy of the model?\n\n\n```python\nSigma = np.sqrt(np.var(mc_predictions.T, axis=1))\n\nscore = scorer(mc_predictions.T, y_test, Sigma)\n\nIF_array = score.IndicatorFunction()\nn_quantiles = 11\nperc = np.linspace(0.0, 1.00, n_quantiles)\n\n```\n\n\n```python\nprint('Accuracy = {0:2.2f}'.format(score.Accuracy()))\nprint('Precision = {0:2.2f}'.format(score.Precision()))\nprint('Goodness = {0:2.2f}'.format(score.Goodness()))\n```\n\n Accuracy = 0.03\n Precision = 1.00\n Goodness = 0.63\n\n\nFor a random point we can plot the histogram of predictions and estimate the standard deviation of the mean value\n\n\n```python\nhistogram_fixed(mc_predictions,5);\n```\n\nHow does the accuracy plot look like for the defined model?\n\n\n```python\nerror_accuracy_plot(perc, IF_array, mc_predictions.T, y_test, Sigma)\n```\n\n## Exploration of the hyperparameter space\n\nThe model we instantiated in the last section was selected using the following algorithm:\n\n**Input**: m hyperparameter combinations to evaluate\n**Output**: optimal dropout with maximum uncertainty model goodness for a given learning rate\n1. Use any design of experiments (DOE) to sample m dropout and learning rate values of the search space.\n2. Use the objective function defined in equation 8 \n3. **while** i\n RangeIndex: 600 entries, 0 to 599\n Data columns (total 8 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 Unnamed: 0 600 non-null int64 \n 1 number 600 non-null int64 \n 2 value 600 non-null float64\n 3 duration 600 non-null object \n 4 params_Dropout 600 non-null float64\n 5 params_learn_rate 600 non-null float64\n 6 system_attrs_grid_id 600 non-null int64 \n 7 system_attrs_search_space 600 non-null object \n dtypes: float64(3), int64(3), object(2)\n memory usage: 37.6+ KB\n\n\nThis is how the search space evaluated with the uncertainty model goodness metric looks like:\n\n\n```python\nimport scipy.ndimage\nimport matplotlib.tri as tri\nfrom scipy.ndimage.filters import gaussian_filter\n\nz=df['value'].values\nx=df['params_Dropout'].values\ny=df['params_learn_rate'].values\n\nfig, (ax1) = plt.subplots(nrows=1,figsize=(12,6))\n\nnpoints=300\nsmooth=2\n\n# Create grid values first.\nxi = np.linspace(x.min(), x.max(), npoints)\nyi = np.linspace(y.min(), y.max(), npoints)\n\n# Linearly interpolate the data (x, y) on a grid defined by (xi, yi).\ntriang = tri.Triangulation(x, y)\ninterpolator = tri.LinearTriInterpolator(triang, z)\nXi, Yi = np.meshgrid(xi, yi)\nzi = interpolator(Xi, Yi)\n\nzi = gaussian_filter(zi, smooth)\n\nlevels=10\n\nax1.contour(xi, yi, zi, levels=levels, linewidths=0.1, colors='k')\ncntr1 = ax1.contourf(xi, yi, zi, levels=levels, cmap=\"inferno\",alpha=0.9)\n\ncbar = plt.colorbar(cntr1, ax=ax1)\n\ncbar.set_label('Uncertainty model Goodness', rotation=270,labelpad=30)\n\nax1.set(xlim=(df.params_Dropout.min(), df.params_Dropout.max()),ylim=(df.params_learn_rate.min(), df.params_learn_rate.max()))\nax1.scatter(x,y,s=3,color='darkgray')\nax1.set_ylabel('Learn rate')\nax1.set_xlabel('Dropout')\nplt.show()\n\n```\n\n## Conclusions and observations\n\n* The work introduces a novel workflow to tune uncertainty models by using the uncertainty model goodness metric.\n\n* This inclusion allows the calculation of robust uncertainty models from machine learning-based ensembles of estimates and robust forecasting.\n\n* This approach is critical to any prediction problem with significant uncertainty.\n\n### Eduardo Maldonado Cruz, Graduate Research Assistant, The University of Texas at Austin\n\n#### [Twitter](https://twitter.com/emaldonadocruz) | [GitHub](https://github.com/emaldonadocruz) | [LinkedIn](https://www.linkedin.com/in/eduardo-maldonado-8386a898/)\n\n### Michael Pyrcz, Associate Professor, The University of Texas at Austin \n\n#### [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1)\n", "meta": {"hexsha": "a40711c0dab4a05b963d3c6b35049443049a29d6", "size": 557664, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Rate_forecasting_using_Uncertainty_NN.ipynb", "max_stars_repo_name": "emaldonadocruz/Python_numerical_demos", "max_stars_repo_head_hexsha": "0fbdb6764ace68d9920aaa9f5ff4061805390bdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Rate_forecasting_using_Uncertainty_NN.ipynb", "max_issues_repo_name": "emaldonadocruz/Python_numerical_demos", "max_issues_repo_head_hexsha": "0fbdb6764ace68d9920aaa9f5ff4061805390bdd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rate_forecasting_using_Uncertainty_NN.ipynb", "max_forks_repo_name": "emaldonadocruz/Python_numerical_demos", "max_forks_repo_head_hexsha": "0fbdb6764ace68d9920aaa9f5ff4061805390bdd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 165.1848341232, "max_line_length": 105324, "alphanum_fraction": 0.8301647587, "converted": true, "num_tokens": 41797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.34411647820698654}} {"text": "# Select suitable MDL test\n\n# Purpose\nFind suitable roll decay tests from MDL, to reproduce in Motions later on.\n\n# Methodology\nLook at the results from the KLVCC2 ship.\n* Load model tests from MDL\n* Determine damping\n\n# WIP - improvements\n(WORK IN PROGRESS)\nUse this section only if the notebook is not final.\n\nNotable TODOs:\n* todo 1\n* todo 2\n* todo 3\n\n## Results\nDescribe and comment the most important results.\n\n# Suggested next steps\nState suggested next steps, based on results obtained in this notebook.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom bqplot import pyplot as plt2\nimport ipywidgets as widgets\n#plt.style.use('paper')\n\n#import data\nimport copy\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\nfrom mdldb.run import Run\n\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 461 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.dpi : 100 ## figure dots per inch')\n\n\n\n```python\nfrom mdldb.hdf5_file import Hdf5File\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorCubic,EstimatorQuadraticB\n```\n\n\n```python\ndb = database.get_db()\n```\n\n\n```python\nsql = \"\"\"\nSELECT * from run\nWHERE model_number='M5057-01-A' and test_type='roll decay' and project_number=40178362;\n\"\"\"\ndf_rolldecays = pd.read_sql(sql=sql, con=db.engine, index_col='id')\n\ndf_rolldecays['ship_speed'].fillna(0, inplace=True)\n\n```\n\n\n```python\ndf_rolldecays\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
project_numberseries_numberrun_numbertest_numbermodel_numbership_nameloading_condition_idascii_nameship_speedcommentfile_path_asciifile_path_ascii_tempfile_path_logfile_path_hdf5datetest_typefacilityangle1angle2Körfallstyp
id
21337401783621941M5057-01-AM5057-01-A16694.00.0Roll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNoneNoneNone
21338401783621951M5057-01-AM5057-01-A16695.00.0Roll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-03roll decayMDLNoneNoneNone
21339401783621961M5057-01-AM5057-01-A16696.00.0Roll decay, 0 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-11-28roll decayMDLNoneNoneNone
21340401783621971M5057-01-AM5057-01-A16697.015.5Roll decay, 15.5 knNaNNone\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...\\\\sspa.local\\gbg\\LABmeasuredataMDL\\40178362\\00...2018-04-04roll decayMDLNoneNoneNone
\n
\n\n\n\n\n```python\ndf_rolldecays[['date','ship_speed']]\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
dateship_speed
id
213372018-04-030.0
213382018-04-030.0
213392018-11-280.0
213402018-04-0415.5
\n
\n\n\n\n\n```python\nfig,axes=plt.subplots(nrows=len(df_rolldecays))\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n run = db.session.query(Run).get(int(id))\n run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n \n run.df.plot(y='phi', ax=ax)\n ax.set_ylabel(f\"roll [{run.units['phi']}]\")\n ax.grid(True)\n ax.set_ylim([-0.2,0.2])\n \nplt.tight_layout()\n```\n\n\n```python\nfig,axes=plt.subplots(ncols=len(df_rolldecays))\n\nfor (id, row),ax in zip(df_rolldecays.iterrows(),axes):\n\n run = db.session.query(Run).get(int(id))\n run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n \n run.track_plot(ax)\n \nplt.tight_layout()\n```\n\n## Analyze the damping\n\n\n```python\n#run = db.session.query(Run).get(21338)\n#run = db.session.query(Run).get(21339)\nrun = db.session.query(Run).get(21337)\n\n\n\n#run = db.session.query(Run).get(21340)\n\n\t\nrun = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n```\n\n c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n df_.units = units\n\n\n\n```python\nlowpass_filter = LowpassFilterDerivatorTransformer(cutoff=1, minimum_score=0.999)\ncutter = CutTransformer(phi_max=np.deg2rad(15), phi_min=np.deg2rad(1), phi1d_start_tolerance=0.015)\noffset_transformer = OffsetTransformer()\n```\n\n\n```python\n#steps = [\n## ('filter',lowpass_filter),\n# ('cutter', cutter), \n## ('offset_transformer',offset_transformer),\n#]\n#\n#df = run.df.copy()\n#df['phi1d']=np.gradient(df['phi'],df.index)\n#df['phi2d']=np.gradient(df['phi1d'],df.index)\n#\n#\n#preprosessor = Pipeline(steps=steps)\n#preprosessor.fit(X=df[['phi']])\n#X = preprosessor.transform(df[['phi','phi1d','phi2d']])\n#X-=X['phi'].mean()\n\nsteps = [\n ('filter',lowpass_filter),\n ('cutter', cutter), \n# ('offset_transformer',offset_transformer),\n]\n\ndf = run.df.copy()\n\npreprosessor = Pipeline(steps=steps)\npreprosessor.fit(X=df[['phi']])\nX = preprosessor.transform(df[['phi']])\nX-=X['phi'].mean()\n\n```\n\n\n```python\nfig,ax=plt.subplots()\nrun.df.plot(y='phi', ax=ax)\nX.plot(y='phi', ax=ax)\n```\n\n\n```python\nestimator_quadratic_b = EstimatorQuadraticB(fit_method='derivation')\n```\n\n\n```python\nestimator_quadratic_b.fit(X=X)\nestimator_quadratic_b.score(X=X)\n```\n\n\n\n\n 0.9964378071236195\n\n\n\n\n```python\nestimator_cubic = EstimatorCubic(fit_method='derivation', maxfev=1000, ftol=1e-15)\nestimator_cubic.fit(X=X)\nestimator_cubic.score(X=X)\n```\n\n\n\n\n 0.9991335936625841\n\n\n\n\n```python\nestimator_quadratic_b\n```\n\n\n\n\n EstimatorQuadraticB(B_1A:0.016, B_2A:0.060, C_1A:6.108,)\n\n\n\n\n```python\nestimator_cubic\n```\n\n\n\n\n EstimatorCubic(B_1A:0.026, B_2A:-0.033, B_3A:0.190, C_1A:6.078, C_3A:2.383, C_5A:33.349,)\n\n\n\n\n```python\nfig,ax=plt.subplots()\nestimator_quadratic_b.plot_fit(ax=ax)\nestimator_cubic.plot_fit(ax=ax, model_test=False)\n```\n\n\n```python\nestimator_quadratic_b.calculate_amplitudes_and_damping()\nestimator_cubic.calculate_amplitudes_and_damping()\n\nfig,ax=plt.subplots()\nX['phi_deg']=np.rad2deg(X['phi'])\nX.plot(y='phi_deg', ax=ax)\nestimator_quadratic_b.plot_amplitude(ax=ax)\nestimator_cubic.plot_amplitude(ax=ax, include_model_test=False)\n\nfig,ax=plt.subplots()\nestimator_quadratic_b.plot_damping(ax=ax)\nestimator_cubic.plot_damping(ax=ax, include_model_test=False)\n\nfig,ax=plt.subplots()\nestimator_quadratic_b.plot_error(ax=ax)\nestimator_cubic.plot_error(ax=ax)\n```\n\n\n```python\nfig,ax=plt.subplots()\nX_amplitudes = estimator_quadratic_b.X_amplitudes.copy()\nX_amplitudes['omega0_model'] = estimator_quadratic_b.omega0\nX_amplitudes['omega0_diff'] = X_amplitudes['omega0_model']/X_amplitudes['omega0']\nX_amplitudes.plot(y=['omega0_diff'], ax=ax)\n```\n\n## Investigating the saw-signal...\n\n\n```python\nfrom rolldecayestimators import measure\n\n#X_pred = estimator_quadratic_b.predict(X=X)\nt = np.linspace(X.index[0],X.index[-1],1*len(X))\nX_pred =estimator_quadratic_b.simulate(t=t, phi0=X.iloc[0]['phi'], phi1d0=X.iloc[0]['phi1d'])\n\nX_amplitudes_pred = measure.calculate_amplitudes_and_damping(X=X_pred)\nX_amplitudes_ = measure.calculate_amplitudes_and_damping(X=X)\n\nfig,ax=plt.subplots()\nX_amplitudes_pred.plot(y='B_n',style='-', ax=ax)\nX_amplitudes_.plot(y='B_n',style='.', ax=ax)\n#ax.set_xlim([50,55])\n\nfig,ax=plt.subplots()\nX_amplitudes_pred.plot(x='phi',y='B_n',style='-', ax=ax)\n```\n\n\n```python\nkey = 'phi1d'\nphi1d = np.array(X[key])\n\nindex = np.arange(0, len(X.index))\nindex_later = np.roll(index, shift=-1)\nindex_later[-1] = index[-1]\nmask = (\n ((phi1d[index] > 0) &\n (phi1d[index_later] < 0)) |\n ((phi1d[index] < 0) &\n (phi1d[index_later] > 0))\n)\n\nindex_first = index[mask]\nindex_second = index[mask]+1\n\n# y = m + k*x\n# k = (y2-y1)/(x2-x1)\n# m = y1 - k*x1\n# y = 0 --> x = -m/k\nX_1 = X.iloc[index_first].copy()\nX_2 = X.iloc[index_second].copy()\nrows,cols = X_1.shape\n\nx1 = np.array(X_1.index)\nx2 = np.array(X_2.index)\ny1 = np.array(X_1['phi1d'])\ny2 = np.array(X_2['phi1d'])\nk = (y2-y1)/(x2-x1)\nm = y1 - k*x1\nx = -m/k\n\nX_1 = np.array(X_1)\nX_2 = np.array(X_2)\n\nfactor = (x-x1)/(x2-x1)\nfactor = np.tile(factor,[cols,1]).T\nX_zero = X_1 + (X_2-X_1)*factor\n\nX_zerocrossings = pd.DataFrame(data=X_zero, columns=X.columns, index=x)\n```\n\n\n```python\nfig,ax=plt.subplots()\nX.plot(y='phi1d', ax=ax, style='o-')\nX.iloc[index_first].plot(y='phi1d', style='g.', ax=ax)\nX.iloc[index_second].plot(y='phi1d', style='r.', ax=ax)\n\n\nX_zerocrossings.plot(y='phi1d', style='m.',ax=ax)\nax.set_xlim(10.58,10.62)\nax.set_ylim(-0.05,0.05)\nax.grid(True)\n```\n\n\n```python\nX_zerocrossings.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
phiphi_filteredphi1dphi2dphi_deg
27.447465-0.156722-0.156557-5.741935e-160.967098-8.979520
28.7138720.1526370.152594-1.821460e-17-0.9371928.745480
29.981708-0.148606-0.148794-2.499086e-150.914050-8.514520
31.2502080.1453940.1454464.659359e-17-0.8908268.330480
32.518927-0.141878-0.141948-2.962040e-150.871692-8.128986
\n
\n\n\n\n\n```python\nfig,ax=plt.subplots()\nX_zerocrossings = measure.get_peaks(X=X_pred)\nX_pred.plot(y='phi1d', ax=ax)\nX_zerocrossings.plot(y='phi1d', style='r.',ax=ax)\nax.set_xlim(10.5,11)\nax.grid(True)\n```\n\n\n```python\nfig,ax=plt.subplots()\nX_pred.plot(y='phi1d', ax=ax)\nX_zerocrossings.plot(y='phi1d', style='r.',ax=ax)\nax.set_xlim(10.5,13)\nax.grid(True)\n```\n\n\n```python\nX_zerocrossings.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
phiphi1dphi2d
27.453592-0.1574862.406495e-150.961943
28.7243660.1540171.124968e-15-0.940756
29.995219-0.150624-8.847090e-170.920032
31.2659740.1473013.870168e-15-0.899732
32.536743-0.144133-2.555248e-150.880384
\n
\n\n\n\n\n```python\nfig,ax=plt.subplots()\nax.plot(np.diff(X_zerocrossings.index),'.-')\n```\n\n\n```python\nfig,ax=plt.subplots()\nax.plot(np.diff(run.df.index))\n```\n\n\n```python\nsize = 100\nnp.random.seed(0)\nx_data = np.arange(size)\ny_data = np.cumsum(np.random.randn(size) * 100.0)\n\nplt2.figure(title='My First Plot')\nplt2.plot(x_data, y_data)\nplt2.show()\n```\n\n\n VBox(children=(Figure(axes=[Axis(scale=LinearScale()), Axis(orientation='vertical', scale=LinearScale())], fig…\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "d2c5c9e05b92a3b12c1beb4c896c140cb6491c63", "size": 843486, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/01.1_select_suitable_MDL_test_KVLCC2.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/01.1_select_suitable_MDL_test_KVLCC2.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/01.1_select_suitable_MDL_test_KVLCC2.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 605.5175879397, "max_line_length": 140828, "alphanum_fraction": 0.9415971338, "converted": true, "num_tokens": 5471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.3439531166114479}} {"text": "```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use('classic')\n%matplotlib inline\n```\n\n# Class 5: Managing Data with Pandas \n\nPandas is a Python library for managing datasets. Documentation and examples are available on the website for Pandas: http://pandas.pydata.org/. \n\nIn this Notebook, we'll make use of a dataset containing long-run averages of inflation, money growth, and real GDP. The dataset is available here: https://raw.githubusercontent.com/letsgoexploring/economic-data/master/quantity-theory/csv/quantity_theory_data.csv (Python code to generate the dataset: https://github.com/letsgoexploring/economic-data). Recall that the quantity theory of money implies the following linear relationship between the long-run rate of money growth, the long-run rate of inflation, and the long-run rate of real GDP growth in a country:\n\n\\begin{align}\n\\text{inflation} & = \\text{money growth} - \\text{real GDP growth},\n\\end{align}\n\nGenerally, we treat real GDP growth and money supply growth as exogenous so this is a theory about the determination of inflation.\n\n### Import Pandas\n\n\n```python\n# Import the Pandas module as pd\nimport pandas as pd\n```\n\n### Import data from a csv file\n\nPandas has a function called `read_csv()` for reading data from a csv file into a Pandas `DataFrame` object.\n\n\n```python\n# Import quantity theory data into a Pandas DataFrame called 'df' with country names as the index.\n\n# Directly from internet\ndf = pd.read_csv('https://raw.githubusercontent.com/letsgoexploring/economic-data/master/quantity-theory/csv/quantity_theory_data.csv')\n\n# From current working directory\n# df = pd.read_csv('qtyTheoryData.csv')\n```\n\n\n```python\n# Print the first 5 rows\nprint(df.head())\n```\n\n country iso code observations inflation money growth \\\n 0 Albania ALB 21 0.05453 0.12879 \n 1 Algeria DZA 51 0.10913 0.16370 \n 2 Angola AGO 20 0.88679 1.08457 \n 3 Antigua and Barbuda ATG 38 0.04052 0.09903 \n 4 Argentina ARG 54 0.74972 0.79170 \n \n gdp growth \n 0 0.04829 \n 1 0.03896 \n 2 0.08592 \n 3 0.03673 \n 4 0.02468 \n\n\n\n```python\n# Print the last 10 rows\nprint(df.tail(10))\n```\n\n country iso code observations inflation money growth \\\n 168 Ukraine UKR 23 0.61867 0.58537 \n 169 United Arab Emirates ARE 40 0.03659 0.14033 \n 170 United States USA 54 0.03442 0.05753 \n 171 Uruguay URY 54 0.37658 0.41383 \n 172 Vanuatu VUT 36 0.03611 0.08343 \n 173 Venezuela, RB VEN 53 0.20726 0.27581 \n 174 West Bank and Gaza PSE 17 0.03864 0.12528 \n 175 Yemen, Rep. YEM 24 0.14770 0.13852 \n 176 Zambia ZMB 27 0.22850 0.24470 \n 177 Zimbabwe ZWE 32 -0.00128 -0.13307 \n \n gdp growth \n 168 -0.01070 \n 169 0.04811 \n 170 0.03140 \n 171 0.02294 \n 172 0.02972 \n 173 0.02793 \n 174 0.03389 \n 175 0.04008 \n 176 0.01208 \n 177 0.00839 \n\n\n\n```python\n# Print the type of variable 'df'\nprint(type(df))\n```\n\n \n\n\n### Properties of `DataFrame` objects\n\nLike entries in a spreadsheet file, elements in a `DataFrame` object have row (or *index*) and column coordinates. Column names are always strings. Index elements can be integers, strings, or dates.\n\n\n```python\n# Print the columns of df\nprint(df.columns)\n```\n\n Index(['country', 'iso code', 'observations', 'inflation', 'money growth',\n 'gdp growth'],\n dtype='object')\n\n\n\n```python\n# Create a new variable called 'money' equal to the 'money growth' column and print\nmoney = df['money growth']\nprint(money)\n```\n\n 0 0.12879\n 1 0.16370\n 2 1.08457\n 3 0.09903\n 4 0.79170\n ... \n 173 0.27581\n 174 0.12528\n 175 0.13852\n 176 0.24470\n 177 -0.13307\n Name: money growth, Length: 178, dtype: float64\n\n\n\n```python\n# Print the type of the variable money\nprint(type(money))\n```\n\n \n\n\nA Pandas `Series` stores one column of data. Like a `DataFrame`, a `Series` object has an index. Note that `money` has the same index as `df`. Instead of having a column, the `Series` has a `name` attribute.\n\n\n```python\n# Print the name of the 'money' variable\nprint(money.name)\n```\n\n money growth\n\n\nSelect multiple columns of a `DataFrame` by puting the desired column names in a set a of square brackets (i.e., in a `list`).\n\n\n```python\n# Print the first 5 rows of just the inflation, money growth, and gdp growth columns\nprint(df[['inflation','money growth','gdp growth']].head())\n```\n\n inflation money growth gdp growth\n 0 0.05453 0.12879 0.04829\n 1 0.10913 0.16370 0.03896\n 2 0.88679 1.08457 0.08592\n 3 0.04052 0.09903 0.03673\n 4 0.74972 0.79170 0.02468\n\n\nAs mentioned, the set of row coordinates is the index. Unless specified otherwise, Pandas automatically assigns an integer index starting at 0 to rows of the `DataFrame`.\n\n\n```python\n# Print the index of 'df'\nprint(df.index)\n```\n\n RangeIndex(start=0, stop=178, step=1)\n\n\nNote that in the index of the `df` is the numbers 0 through 177. We could have specified a different index when we imported the data using `read_csv()`. For example, suppose we want to the country names to be the index of `df`. Since country names are in the first column of the data file, we can pass the argument `index_col=0` to `read_csv()`\n\n\n```python\n# Import quantity theory data into a Pandas DataFrame called 'df' with country names as the index.\ndf = pd.read_csv('https://raw.githubusercontent.com/letsgoexploring/economic-data/master/quantity-theory/csv/quantity_theory_data.csv',index_col=0)\n\n# Print first 5 rows of df\nprint(df.head())\n```\n\n iso code observations inflation money growth \\\n country \n Albania ALB 21 0.05453 0.12879 \n Algeria DZA 51 0.10913 0.16370 \n Angola AGO 20 0.88679 1.08457 \n Antigua and Barbuda ATG 38 0.04052 0.09903 \n Argentina ARG 54 0.74972 0.79170 \n \n gdp growth \n country \n Albania 0.04829 \n Algeria 0.03896 \n Angola 0.08592 \n Antigua and Barbuda 0.03673 \n Argentina 0.02468 \n\n\nUse the `loc` attribute to select rows of the `DataFrame` by index *values*.\n\n\n```python\n# Create a new variable called 'usa_row' equal to the 'United States' row and print\nusa_row = df.loc['United States']\nprint(usa_row)\n```\n\n iso code USA\n observations 54\n inflation 0.03442\n money growth 0.05753\n gdp growth 0.0314\n Name: United States, dtype: object\n\n\nUse `iloc` attribute to select row based on integer location (starting from 0).\n\n\n```python\n# Create a new variable called 'third_row' equal to the third row in the DataFrame and print\nthird_row = df.iloc[2]\nprint(third_row)\n```\n\n iso code AGO\n observations 20\n inflation 0.88679\n money growth 1.08457\n gdp growth 0.08592\n Name: Angola, dtype: object\n\n\nThere are several ways to return a single element of a Pandas `DataFrame`. For example, here are three that we want to return the value of inflation for the United States from the DataFrame `df`:\n\n1. `df.loc['United States','inflation']`\n2. `df.loc['United States']['inflation']`\n3. `df['inflation']['United States']`\n\nThe first method points directly to the element in the `df` while the second and third methods return *copies* of the element. That means that you can modify the value of inflation for the United States by running:\n\n df.loc['United States','inflation'] = new_value\n \nBut running either:\n\n df.loc['United States']['inflation'] = new_value\n \nor:\n\n df['inflation']['United States'] = new_value\n\nwill return an error.\n\n\n```python\n# Print the inflation rate of the United States (By index and column together)\nprint('Long-run average inflation in US: ',df.loc['United States','inflation'])\n```\n\n Long-run average inflation in US: 0.03442\n\n\n\n```python\n# Print the inflation rate of the United States (first by index, then by column)\nprint('Long-run average inflation in US: ',df.loc['United States']['inflation'])\n```\n\n Long-run average inflation in US: 0.03442\n\n\n\n```python\n# Print the inflation rate of the United States (first by column, then by index)\nprint('Long-run average inflation in US: ',df['inflation']['United States'])\n```\n\n Long-run average inflation in US: 0.03442\n\n\nNew columns are easily created as functions of existing columns.\n\n\n```python\n# Create a new column called 'difference' equal to the money growth column minus \n# the inflation column and print the modified DataFrame\ndf['difference'] = df['money growth'] - df['inflation']\nprint(df['difference'])\n```\n\n country\n Albania 0.07426\n Algeria 0.05457\n Angola 0.19778\n Antigua and Barbuda 0.05851\n Argentina 0.04198\n ... \n Venezuela, RB 0.06855\n West Bank and Gaza 0.08664\n Yemen, Rep. -0.00918\n Zambia 0.01620\n Zimbabwe -0.13179\n Name: difference, Length: 178, dtype: float64\n\n\n\n```python\n# Print the average difference between money growth and inflation\nprint(df.difference.mean())\n```\n\n 0.06339837078651682\n\n\n\n```python\n# Remove the following columns from the DataFrame: 'iso code','observations','difference'\ndf = df.drop(['iso code','observations','difference'],axis=1)\n\n# Print the modified DataFrame\nprint(df)\n```\n\n inflation money growth gdp growth\n country \n Albania 0.05453 0.12879 0.04829\n Algeria 0.10913 0.16370 0.03896\n Angola 0.88679 1.08457 0.08592\n Antigua and Barbuda 0.04052 0.09903 0.03673\n Argentina 0.74972 0.79170 0.02468\n ... ... ... ...\n Venezuela, RB 0.20726 0.27581 0.02793\n West Bank and Gaza 0.03864 0.12528 0.03389\n Yemen, Rep. 0.14770 0.13852 0.04008\n Zambia 0.22850 0.24470 0.01208\n Zimbabwe -0.00128 -0.13307 0.00839\n \n [178 rows x 3 columns]\n\n\n### Methods\n\nA Pandas `DataFrame` has a bunch of useful methods defined for it. `describe()` returns some summary statistics.\n\n\n```python\n# Print the summary statistics for 'df'\nprint(df.describe())\n```\n\n inflation money growth gdp growth\n count 178.000000 178.000000 178.000000\n mean 0.128568 0.191966 0.037594\n std 0.172497 0.170733 0.022616\n min -0.001280 -0.133070 -0.025240\n 25% 0.042493 0.102785 0.024382\n 50% 0.070050 0.140935 0.037745\n 75% 0.132060 0.210498 0.048245\n max 1.277050 1.224430 0.165480\n\n\nThe `corr()` method returns a `DataFrame` containing the correlation coefficients of the specified `DataFrame`.\n\n\n```python\n# Create a variable called 'correlations' containg the correlation coefficients for columns in 'df'\ncorrelations = df.corr()\n\n# Print the correlation coefficients\nprint(correlations)\n```\n\n inflation money growth gdp growth\n inflation 1.000000 0.971200 -0.041515\n money growth 0.971200 1.000000 0.088061\n gdp growth -0.041515 0.088061 1.000000\n\n\n\n```python\n# Print the correlation coefficient for inflation and money growth\nprint('corr of inflation and money growth: ',round(correlations.loc['inflation','money growth'],4))\n\n# Print the correlation coefficient for inflation and real GDP growth\nprint('corr of inflation and gdp growth: ',round(correlations.loc['inflation','gdp growth'],4))\n\n# Print the correlation coefficient for money growth and real GDP growth\nprint('corr of money growth and gdp growth:',round(correlations.loc['money growth','gdp growth'],4))\n```\n\n corr of inflation and money growth: 0.9712\n corr of inflation and gdp growth: -0.0415\n corr of money growth and gdp growth: 0.0881\n\n\n`sort_values()` returns a copy of the original `DataFrame` sorted along the given column. The optional argument `ascending` is set to `True` by default, but can be changed to `False` if you want to print the lowest first.\n\n\n```python\n# Print rows for the countries with the 10 lowest inflation rates\nprint(df.sort_values('inflation').head(10))\n```\n\n inflation money growth gdp growth\n country \n Zimbabwe -0.00128 -0.13307 0.00839\n Djibouti 0.00035 0.07940 0.01683\n Germany 0.01120 0.07852 0.01233\n Hong Kong SAR, China 0.01452 0.10295 0.03778\n Ireland 0.01467 0.13223 0.03552\n France 0.01560 0.07038 0.01316\n Kosovo 0.01659 0.09355 0.03622\n Greece 0.01736 0.01533 -0.00487\n Switzerland 0.01754 0.06243 0.01750\n Austria 0.01757 0.08010 0.01543\n\n\n\n```python\n# Print rows for the countries with the 10 highest inflation rates\nprint(df.sort_values('inflation',ascending=False).head(10))\n```\n\n inflation money growth gdp growth\n country \n Congo, Dem. Rep. 1.27705 1.22443 -0.00239\n Brazil 0.88891 0.92023 0.04208\n Angola 0.88679 1.08457 0.08592\n Argentina 0.74972 0.79170 0.02468\n Nicaragua 0.62762 0.67775 0.02522\n Belarus 0.62519 0.65668 0.05171\n Ukraine 0.61867 0.58537 -0.01070\n Peru 0.48310 0.54905 0.03510\n Armenia 0.46680 0.48970 0.05726\n Azerbaijan 0.45091 0.52949 0.05724\n\n\nNote that `sort_values` and `sort_index` return *copies* of the original `DataFrame`. If, in the previous example, we had wanted to actually modify `df`, we would have need to explicitly overwrite it:\n\n df = df.sort_index(ascending=False)\n\n\n```python\n# Print first 10 rows with the index sorted in descending alphabetical order\nprint(df.sort_index(ascending=False).head(10))\n```\n\n inflation money growth gdp growth\n country \n Zimbabwe -0.00128 -0.13307 0.00839\n Zambia 0.22850 0.24470 0.01208\n Yemen, Rep. 0.14770 0.13852 0.04008\n West Bank and Gaza 0.03864 0.12528 0.03389\n Venezuela, RB 0.20726 0.27581 0.02793\n Vanuatu 0.03611 0.08343 0.02972\n Uruguay 0.37658 0.41383 0.02294\n United States 0.03442 0.05753 0.03140\n United Arab Emirates 0.03659 0.14033 0.04811\n Ukraine 0.61867 0.58537 -0.01070\n\n\n### Quick plotting example\n\nConstruct a graph that visually confirms the quantity theory of money by making a scatter plot with average money growth on the horizontal axis and average inflation on the vertical axis. Set the marker size `s` to 50 and opacity (`alpha`) 0.25. Add a 45 degree line, axis labels, and a title. Lower and upper limits for the horizontal and vertical axes should be -0.2 and 1.2.\n\n\n```python\n# Create data for 45 degree line\nx45 = [-0.2,1.2]\ny45 = [-0.2,1.2]\n\n# Create figure and axis\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\n# Plot 45 degree line and create legend in lower right corner\nax.plot(x45,y45,'-r',label = '$45^{\\circ}$')\nax.legend(loc='lower right')\n\n# Scatter plot of data inflation against money growth\nax.scatter(df['money growth'],df['inflation'],s=50,alpha = 0.25)\nax.set_xlim([-0.2,1.2])\nax.set_ylim([-0.2,1.2])\nax.set_xlabel('money growth')\nax.set_ylabel('inflation')\nax.set_title('Average inflation against average money growth \\nfor '+str(len(df.index))+' countries.')\nax.grid()\n```\n\n### Exporting a `DataFrame` to csv\n\nUse the DataFrame method `to_csv()` to export DataFrame to a csv file.\n\n\n```python\n# Export the DataFrame 'df' to a csv file called 'modified_data.csv'.\ndf.to_csv('modified_data.csv')\n```\n", "meta": {"hexsha": "1893394480c1ee34e37f55bef3edd9131517f671", "size": 53625, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Lecture Notebooks/Econ126_Class_05.ipynb", "max_stars_repo_name": "t-hdd/econ126", "max_stars_repo_head_hexsha": "17029937bd6c40e606d145f8d530728585c30a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lecture Notebooks/Econ126_Class_05.ipynb", "max_issues_repo_name": "t-hdd/econ126", "max_issues_repo_head_hexsha": "17029937bd6c40e606d145f8d530728585c30a1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lecture Notebooks/Econ126_Class_05.ipynb", "max_forks_repo_name": "t-hdd/econ126", "max_forks_repo_head_hexsha": "17029937bd6c40e606d145f8d530728585c30a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 60.7304643262, "max_line_length": 26556, "alphanum_fraction": 0.7326060606, "converted": true, "num_tokens": 4842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.3439531101038274}} {"text": "Copyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the MIT License.\n\n# Bilateral Variational Autoencoder (BiVAE)\n\nThis notebook serves as a tutorial on Bilateral Variational Autoencoder (BiVAE) model for collaborative filtering. The research paper of BiVAE [1] is presented at WSDM'21 conference. For all experiments related to BiVAE model, please refer to [this repository](https://github.com/PreferredAI/bi-vae).\n\nThe implementation of the model is from [Cornac](https://github.com/PreferredAI/cornac) [2], which is a framework for multimodal recommender systems focusing on models that utilize auxiliary data (e.g., item descriptive text and image, social network, etc).\n\n## 0 Global Settings and Imports\n\n\n```python\nimport sys\nimport os\nimport torch\nimport cornac\nimport papermill as pm\nimport scrapbook as sb\nimport pandas as pd\nfrom reco_utils.dataset import movielens\nfrom reco_utils.dataset.python_splitters import python_random_split\nfrom reco_utils.evaluation.python_evaluation import map_at_k, ndcg_at_k, precision_at_k, recall_at_k\nfrom reco_utils.recommender.cornac.cornac_utils import predict_ranking\nfrom reco_utils.common.timer import Timer\nfrom reco_utils.common.constants import SEED\n\nprint(\"System version: {}\".format(sys.version))\nprint(\"PyTorch version: {}\".format(torch.__version__))\nprint(\"Cornac version: {}\".format(cornac.__version__))\n```\n\n System version: 3.6.11 | packaged by conda-forge | (default, Nov 27 2020, 18:57:37) \n [GCC 9.3.0]\n PyTorch version: 1.4.0\n Cornac version: 1.11.0\n\n\n\n```python\n# Select MovieLens data size: 100k, 1m, 10m, or 20m\nMOVIELENS_DATA_SIZE = '100k'\n\n# top k items to recommend\nTOP_K = 10\n\n# Model parameters\nLATENT_DIM = 50\nENCODER_DIMS = [100]\nACT_FUNC = \"tanh\"\nLIKELIHOOD = \"pois\"\nNUM_EPOCHS = 500\nBATCH_SIZE = 128\nLEARNING_RATE = 0.001\n```\n\n## 1 Theory behind BiVAE\n\n### 1.1 Motivation from Dyadic Data\n\nPreference data in collaborative filtering (CF) typically consists of a set of users, a set of items, and a set of interactions, e.g., ratings, clicks, purchases between some user-item pairs. Most of the time, preference data is being represented as an interaction matrix between user and item. Generally, it is a form of dyadic data, with measurements associated with pairs of elements arising from two discrete sets of objects. Naturally, there are two ways to view such data, by users (row-wise) and by items (column-wise).\n\n\n\n\nUltimately, we would like to seek for representations for both sides of dyadic data (users and items) whose combination would be capable of explaining user-item affinities. To tackle this objective, latent factor or matrix factorization models are predominant in the context of CF. The latter owe their success mainly to their simplicity, efficiency, effectiveness, and extensibility. Nevertheless, this category of models is also known to suffer from a limited modeling capacity as it can\nonly capture linear patterns both in the data and latent spaces.\n\nTo go beyond this limitation, there has recently been a surge of interest in using non-linear neural-based approaches. Notably, Variational Autoencoder (VAE) [3] model has been recently applied to CF with strong performance improvements over several competitive approaches. One plausible explanation for the good results achieved by VAE on the CF task is its probabilistic nature. Indeed, the key difference of this model with neural networks is that VAE does not seek to learn deterministic representations, but rather learns distributions over these representations, thereby allowing it to account for uncertainty in the latent space. That property is particularly beneficial when dealing with sparse data where few observations are available. \n\n\n\nDespite its remarkable performance, VAE was originally designed for vector based-data, and thus is not in complete fidelity to the two-way nature of dyadic data. Specifically, in the User-VAE, only users are explicitly represented while items are treated as features in a vector space of users, and similarly for Item-VAE. In consequence of this mismatch between VAE and the two-way nature of preference data, it is not clear how one would extend such model on the item side in a principled way, for example to represent side information such as item textual descriptions, images, etc.\n\n### 1.2 BiVAE Formulation\n\nAs remedy to the drawback of VAE discussed earlier, Bilateral Variational Autoencoder (BiVAE) is proposed. It consists of a generative model of user-item interactions (or dyads), and a pair of inference models (user- and item-based respectively) parameterized using multilayer neural networks, all combined together in a unified framework to auto-encode dyadic preference data. As opposed to the vanilla VAE, the proposed BiVAE is “bilateral” in that it treats users and items symmetrically, making it more apt for two-way or dyadic data. In particular, BiVAE can capture uncertainty on both sides of dyadic data, which would improve its robustness and performance on sparse preference data, compared to classical one-sided variational autoencoders.\n\n\n\n**Notation.** The data that we seek to learn from is the user-item preference matrix, of size $U\\times I$, denoted $\\mathbf{R} = (r_{ui})$, where $r_{ui}$ is the interaction, e.g., integer rating, between user $u$ and item $i$. We use the notation $\\mathbf{r}_{u*}$ to refer to the row in $\\mathbf{R}$ corresponding to user $u$. Similarly, $\\mathbf{r}_{*i}$ refers to the $i$th column of $\\mathbf{R}$. The latent variables are the per user and item representations denoted respectively $\\mathbf{\\theta}_{u}$, $\\mathbf{\\beta}_i \\in \\mathbb{R}^{K}$.\n\n\n\n**Generative Model.** Figure above depicts BiVAE generative model, as compared to VAE, in plate notations. The latent variables are drawn from prior distributions. Without loss of generality, the Gaussian priors with diagonal covariance matrices are being used. BiVAE further adopts the standard multivariate isotropic Gaussian as the prior over all user/item latent variables. That is, $p(\\bf{\\theta}_u) = \\mathcal{N}(\\bf{0},\\bf{I})$ and $p(\\bf{\\beta}_i) = \\mathcal{N}(\\bf{0},\\bf{I})$, $\\forall i,u$. \n\nConditional on the latent variables, the observations are drawn from a univariate exponential family,\n\n$$\np(r_{ui}|\\bf{\\theta}_u,\\bf{\\beta}_i) = \\mathrm{EXPFAM}(r_{ui}; \\eta(\\bf{\\theta}_u; \\bf{\\beta}_i;\\omega)) = h(r_{ui})\\exp\\{\\eta(\\bf{\\theta}_u;\\bf{\\beta}_i;\\omega)r_{ui} - a(\\eta(\\bf{\\theta}_u;\\bf{\\beta}_i;\\omega))\\}\n$$\n\nwhere $h(\\cdot)$, $\\eta(\\cdot)$ and $a(\\cdot)$ denote respectively the base measure, natural parameter and log-normalizer of the exponential family. For simplicity, $r_{ui}$ is assumed to be the sufficient statistic by itself. This form of the exponential family still encompasses many popular univariate distributions, including the Poisson, Bernoulli, Gaussian with unit variance, Gamma with fixed shape parameter, etc. Therefore, BiVAE framework can accommodate various types of preference data, such as counts, binary, continuous, etc. The conditional likelihood is further parameterized in such a way that,\n\n$$\n\\mathbb{E}(r_{ui}|\\bf{\\theta}_u,\\bf{\\beta}_i) = \\frac{d a(\\eta)}{d \\eta} = g_{\\omega}(\\bf{\\theta}_u;\\bf{\\beta}_i)\n$$\n\nwhere $g_\\omega(\\cdot)$ is some differentiable function (e.g., inner product, neural network, etc.) parameterized by $\\omega$, combining the latent representations to output the mean of the observation $r_{ui}$.\n \nGiven some $\\bf{R}$, the goal is to find the values of the parameters $\\omega$ that would most likely have generated the observations, and to infer the posterior over the latent variables $p(\\bf{\\theta}_{1:U},\\bf{\\beta}_{1:I}|\\bf{R})$. The latter will allow us to make predictions about unknown preferences and form recommendations. However, the posterior and likelihood are intractable and thereby, exact inference and learning are infeasible. Therefore, BiVAE relies on variational Bayes (VB), a popular and efficient approach to deal with complex probabilistic models.\n\n**Inference Model.**\nThe starting point of VB is to introduce a tractable inference model $q$, governed by a set of *variational parameters* $\\nu$, which will be used as a proxy for the true but intractable posterior. A variational distribution, which breaks the coupling between $\\beta$ and $\\theta$ - a main source of intractability in our model, is chosen as:\n\n$$\nq(\\bf{\\theta}_{1:U},\\bf{\\beta}_{1:I}|\\bf{R}) = q(\\bf{\\theta}_{1:U}|\\bf{R})q(\\bf{\\beta}_{1:I}|\\bf{R})\n$$\n\nwith \n\n$$\n\\begin{align}\nq(\\bf{\\theta}_{1:U}|\\bf{R}) &= \\prod_{u} q(\\bf{\\theta}_u|\\bf{R}_{u*})\\nonumber\\\\\nq(\\bf{\\beta}_{1:I}|\\bf{R}) &= \\prod_{i} q(\\bf{\\beta}_i|\\bf{R}_{*i})\\nonumber\n\\end{align}\n$$\n\nWithout loss of generality, the following forms are adopted:\n\n$$\n\\begin{align}\nq(\\bf{\\theta}_u|\\bf{R}_{u*}) &= \\mathcal{N}(\\tilde{\\bf{\\mu}}_{\\tilde\\psi}(\\bf{R}_{u*}),\\tilde{\\bf\\sigma}_{\\tilde\\psi}(\\bf{R}_{u*}))\\nonumber\\\\\nq(\\bf{\\beta}_i|\\bf{R}_{*i}) &= \\mathcal{N}(\\tilde{\\bf\\mu}_{\\tilde\\phi}(\\bf{R}_{*i}),\\tilde{\\bf\\sigma}_{\\tilde\\phi}(\\bf{R}_{*i}))\\nonumber\n\\end{align}\n$$\n\nwhere $\\nu=\\{\\tilde\\phi,\\tilde\\psi\\}$, $\\tilde{\\bf\\mu}(\\cdot)$ and $\\tilde{\\bf\\sigma}(\\cdot)$ are vector-valued functions (e.g., multilayer perceptrons) parameterized by $\\tilde\\phi$/$\\tilde\\psi$, outputting respectively the mean and covariance parameters of the variational distributions.\n\nWith $q$ in place, we can proceed with approximate inference by optimizing the Evidence Lower BOund (ELBO), w.r.t. the model $\\omega$ and variational $\\nu$ parameters, given in our case by,\n\n$$\n\\mathcal{L} = \\sum_{u,i}\\mathbb{E}_{q(\\bf{\\theta}_u|\\bf{R}_{u*})}\\mathbb{E}_{q(\\bf{\\beta}_i|\\bf{R}_{*i})}[\\log p(r_{ui}|\\bf{\\theta}_u,\\bf{\\beta}_i)]\n- \\sum_{u} \\mathrm{KL}(q(\\bf{\\theta}_u|\\bf{R}_{u*})|| p(\\bf{\\theta}_u)) - \\sum_{i} \\mathrm{KL}(q(\\bf{\\beta}_i|\\bf{R}_{*i})|| p(\\bf{\\beta}_i))\n$$\n\n### 1.3 Optimization\n\nIn practice, stochastic optimization is used to fit BiVAE to observations. While the KL terms in the ELBO are available analytically, the expectations over the conditional log-likelihood are intractable and thereby, the direct optimization of ELBO is not possible. To overcome this difficulty, the *reparameterization trick* is used to build an unbiased Monte Carlo estimator of the ELBO:\n\n$$\n\\tilde{\\mathcal{L}} = \\sum_{u,i} \\log p(r_{ui} | \\tilde{\\bf\\theta}_u,\\tilde{\\bf\\beta}_i) - \\sum_{u} \\mathrm{KL}(q(\\bf{\\theta}_u|\\bf{r}_{u*}) || p(\\bf{\\theta}_u)) - \\sum_{i} \\mathrm{KL}(q(\\bf{\\beta}_i|\\bf{r}_{*i})|| p(\\bf{\\beta}_i))\n$$\n\nwhere \n\n$$\n\\begin{align}\n\\tilde{\\bf\\theta}_u &= \\mathcal{T}(\\bf\\epsilon,\\tilde{\\bf\\psi})= \\tilde{\\bf\\mu}_{\\tilde\\psi}(\\bf{r}_{u*}) + \\tilde{\\bf\\sigma}_{\\tilde\\psi}(\\bf{r}_{u*})\\odot\\bf\\epsilon \\nonumber\\\\\n\\tilde{\\bf\\beta}_{i} &= \\mathcal{T}(\\bf\\epsilon,\\tilde{\\bf\\phi})= \\tilde{\\bf\\mu}_{\\tilde\\phi}(\\bf{r}_{*i}) + \\tilde{\\bf\\sigma}_{\\tilde\\phi}(\\bf{r}_{*i})\\odot\\bf\\epsilon \\nonumber\n\\end{align}\n$$\n\nwith $\\bf\\epsilon \\sim \\mathcal{N}(\\bf{0},\\bf{I})$.\n\nNow all the quantities involved are tractable. However, performing unbiased stochastic optimization over the above objective is not convenient, due to the mixing between $r_{ui}$, $\\bf{r}_{u*}$ and $\\bf{r}_{*i}$. To overcome this difficulty and ease subsampling of observations, the two-way nature of BiVAE model is exploited to perform alternate optimization in a Gauss-Seidel fashion. Precisely, the parameters are organized into two blocks consisting of user-related and item-related parameters respectively, then alternate the optimization of each block while holding the other one fixed. For more details on the optimization procedure, please refer to the original paper [1].\n\n## 2 Cornac implementation of BiVAE\n\nBiVAE is implemented in the Cornac framework as part of the [model collections](https://github.com/PreferredAI/cornac#models).\n* Detailed documentations of the BiVAE model in Cornac can be found [here](https://cornac.readthedocs.io/en/latest/models.html#module-cornac.models.bivaecf.recom_bivaecf).\n* Source codes of the BiVAE implementation is available on [Cornac](https://github.com/PreferredAI/cornac/tree/master/cornac/models/bivaecf).\n* For all experiments related to BiVAE, please refer to [this repository](https://github.com/PreferredAI/bi-vae).\n\n\n## 3 Experiments on MovieLens\n\n\n### 3.1 Load and split data\n\nTo evaluate the performance of item recommendation, we adopted the provided `python_random_split` tool for the consistency. Data is randomly split into training and test sets with the ratio of 75/25.\n\n\nNote that Cornac also cover different [built-in schemes](https://cornac.readthedocs.io/en/latest/eval_methods.html) for model evaluation.\n\n\n```python\ndata = movielens.load_pandas_df(\n size=MOVIELENS_DATA_SIZE,\n header=[\"userID\", \"itemID\", \"rating\"]\n)\n\ndata.head()\n```\n\n 100%|██████████| 4.81k/4.81k [00:01<00:00, 2.42kKB/s]\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
userIDitemIDrating
01962423.0
11863023.0
2223771.0
3244512.0
41663461.0
\n
\n\n\n\n\n```python\ntrain, test = python_random_split(data, 0.75)\n```\n\n### 3.2 Cornac Dataset\n\nTo work with models implemented in Cornac, we need to construct an object from [Dataset](https://cornac.readthedocs.io/en/latest/data.html#module-cornac.data.dataset) class.\n\nDataset Class in Cornac serves as the main object that the models will interact with. In addition to data transformations, Dataset provides a bunch of useful iterators for looping through the data, as well as supporting different negative sampling techniques.\n\n\n```python\ntrain_set = cornac.data.Dataset.from_uir(train.itertuples(index=False), seed=SEED)\n\nprint('Number of users: {}'.format(train_set.num_users))\nprint('Number of items: {}'.format(train_set.num_items))\n```\n\n Number of users: 943\n Number of items: 1642\n\n\n### 3.3 Train the BiVAE model\n\nThe BiVAE has a few important parameters that we need to consider:\n\n- `k`: dimension of the latent space (i.e. the size of $\\bf{\\theta}_u$ and $\\bf{\\beta}_i$ ).\n- `encoder_structure`: dimension(s) of hidden layer(s) of the user and item encoders.\n- `act_fn`: non-linear activation function used in the encoders.\n- `likelihood`: choice of the likelihood function being optimized.\n- `n_epochs`: number of passes through training data.\n- `batch_size`: size of mini-batches of data during training.\n- `learning_rate`: step size in the gradient update rules.\n\nTo train the model, we simply need to call the `fit()` method.\n\n\n```python\nbivae = cornac.models.BiVAECF(\n k=LATENT_DIM,\n encoder_structure=ENCODER_DIMS,\n act_fn=ACT_FUNC,\n likelihood=LIKELIHOOD,\n n_epochs=NUM_EPOCHS,\n batch_size=BATCH_SIZE,\n learning_rate=LEARNING_RATE,\n seed=SEED,\n use_gpu=torch.cuda.is_available(),\n verbose=True\n)\n\nwith Timer() as t:\n bivae.fit(train_set)\nprint(\"Took {} seconds for training.\".format(t))\n```\n\n\n 0%| | 0/500 [00:003. Feladatsor
\n\n\n\n
\n
\n
\n\n
\n,,Ny name is Gear.''---,,pardon?\"
\n,,Gear, dshii, ii, ay, are.\"---,,Mr. Jiea?\"
\n(In a hotel of Paris)\n
\n
\n
\n\n\n
\n
\n
\n\n
\n
\n\n##
Backward differentiation formulas (BDF módszerek)
\n\n### BDF módszerek reprezentálása\n\n$$y_{i+1}=\\sum_{j=1}^ka_jy_{i+1-j}+hb_0f_{i+1}$$\nJelölések:\n+ $k$ lépések száma\n+ $p=k$ módszer rendje\n+ lokális csonkolási hibában $C_{p+1}=\\frac{1}{k+1}$\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$k$$b_0$$a_1$$a_2$$a_3$$a_4$$a_5$$a_6$
$$1$$$$1$$$$1$$
$$2$$$$\\frac{2}{3}$$$$-\\frac{1}{3}$$
$$3$$$$\\frac{6}{11}$$$$\\frac{18}{11}$$$$-\\frac{9}{11}$$$$\\frac{2}{11}$$
$$4$$$$\\frac{12}{25}$$$$\\frac{48}{25}$$$$-\\frac{36}{25}$$$$\\frac{16}{25}$$$$-\\frac{3}{25}$$
$$5$$$$\\frac{60}{137}$$$$\\frac{300}{137}$$$$-\\frac{300}{137}$$$$\\frac{200}{137}$$$$-\\frac{75}{137}$$$$\\frac{12}{137}$$
$$6$$$$\\frac{60}{147}$$$$\\frac{360}{147}$$$$-\\frac{450}{147}$$$$\\frac{400}{147}$$$$-\\frac{225}{147}$$$$\\frac{72}{147}$$$$-\\frac{10}{147}$$
\n
\n
\n\n\n1.feladat. Számoljuk ki $k=1,2,3$ esetekben a $$\\sum_{j=1}^k\\frac{1}{j}\\nabla^jy_{n+1}=hf_{n+1}$$\nfelíráson alapuló BDF módszereket!\n\n
\n\n2.feladat. Írjunk programot az előző feladatra általános $k$ esetre!\n\n\n```octave\nBDFcoefficients(2)\n```\n\n ans = 3/2 -2 1/2\r\n\n\n### A-, $A(\\alpha)$- és L-stabilitás\n\n3.feladat. Írjunk programot, mely kiszámolja a BDF3 módszer $A(\\alpha)$ stabilitási tartományának szögét!\n\n\n```octave\nLW = 'LineWidth'; lw = 1;\nclr = [221 221 221]/255;\n% Az egysegkor definialasa\nN = 1000;\ntheta = linspace(0,2*pi,N);\nxi = exp(1i*theta);\n\n% Az egyes karakterisztikus polinomok (\\pi(xi)=0 egyenletre vonatkozoan)\nBDF1=@(xi)(1-1./xi);\nBDF2=@(xi)(3*xi.^2-4*xi+1)./(2*xi.^2);\nBDF3=@(xi)(11*xi.^3-18*xi.^2+9*xi-2)./(6*xi.^3);\nBDF4=@(xi)(25*xi.^4-48*xi.^3+36*xi.^2-16*xi+3)./(12*xi.^4);\nBDF5=@(xi)(137*xi.^5-300*xi.^4+300*xi.^3-200*xi.^2+75*xi+-12)./(60*xi.^5);\nBDF6=@(xi)(147*xi.^6-360*xi.^5+450*xi.^4-400*xi.^3+225*xi.^2-72*xi+10)./(60*xi.^6);\nz1=BDF1(xi);\nz2=BDF2(xi);\nz3=BDF3(xi);\nz4=BDF4(xi);\nz5=BDF5(xi);\nz6=BDF6(xi);\nplot(z1,'k-',LW,lw), hold on\nplot(z2,'k-',LW,lw), \nplot(z3,'k-',LW,lw), \nplot(z4,'k-',LW,lw), \nplot(z5,'k-',LW,lw), \nplot(z6,'k-',LW,lw), \n%fill(real(z),imag(z),clr)\n%plot([min(real(z)) max(real(z))],[0 0],'b--',LW,lw)\n%plot([0 0],[min(imag(z)) max(imag(z))],'b--',LW,lw)\naxis tight, axis equal, hold off\ntitle('A BDF1-6 modszerek abszolut stabilitasi tartomanyai')\n\n\n```\n\n4.feladat. Tekintsük az alábbi rendszert\n
\n
\n\n
\n\n$u'(t)=\\left[ \\begin{array}{cc}\n-2 & 1 \\\\ 998 & -999\n\\end{array} \\right]u(t)+\\left[ \\begin{array}{c}\n2\\sin(t) \\\\ 999[\\cos(t)-\\sin(t)]\n\\end{array} \\right]$, \n$u(0)$=$\\left( \\begin{array}{c}\n0 \\\\\n0\n\\end{array} \\right)$\n
\n\nA feladat pontos megoldása\n\n
\n\n$u(t)=-\\frac{1}{999}\\exp(-t)\\left( \\begin{array}{c}\n1 \\\\\n1\n\\end{array} \\right)+\\frac{1}{999}\\exp(-1000t)\\left( \\begin{array}{c}\n1 \\\\\n-998\n\\end{array} \\right)+\\left( \\begin{array}{c}\n\\sin(t) \\\\\n\\cos(t)\n\\end{array} \\right)$\n
\n\nAlkalmazzuk a rendszer megoldására az IE és Trapéz módszereket és pontos megoldással együtt ábrázolva magyarázzuk meg az $L$-stabilitás jelenségét!\n\n\n```octave\n\n```\n\n### BDF módszerek implementálása\n\n5.feladat. Tekintsük az alábbi kezdetiérték-problémát:\n\n\\begin{cases}\nx'(t)= x(t)+t&\\\\\nx(0)=2, &\n\\end{cases}\n\nahol $t\\in [0,1]$. Számoljuk ki a feladat közelítő megoldását BDF2 módszer segítségével és mérjük a konvergencia rendet maximum normában finom rács technikával.\n\n\n```octave\n\n```\n\n6.feladat. [Two-Mass and Spring system] Tekintsük az előző feladatsorról megismert kéttömegű lengőendszer vertikális kitérését leíró rendszert:\n\\begin{align}\nu_1^{'}&=u_2\\\\\nu_2^{'}&=-\\frac{s_1}{m_1}u_1+\\frac{s_2}{m_1}(u_3-u_1)\\\\\nu_3^{'}&=u_4\\\\\nu_4^{'}&=-\\frac{s_2}{m_2}(u_3-u_1)\n\\end{align}\nahol $m_1=10$kg és $m_2=2$kg adott tömegek, $s_1=100$ és $s_2=120$ adott rugóhoz tartozó állandók. A feladathoz tartozó kezdeti érték vektora\n$$u_1(0)=0.5,\\quad u_2(0)=0,\\quad u_3(0)=0.25,\\quad u_4(0)=0.$$\n\nA kitérést a tömeg egyensúlyi helyzetétől mérve pozitív irányítással lefelé értjük. A kilengést és a hosszt magában foglaló ábárzoláshoz szükséges paraméterek értékei $r_1=10$ és $r_2=15$.\n\nA feladat megoldására a BDF4 módszert alkalmazzuk. Vizsgáljuk meg, hogy mekkora a kitérés mértéke az egyes tömegekre nézve az első 5 másodpercben ha $N=100$. Miben tér el ez a módszer az Adams-Moulton és Milne-Simpson prediktor-korrektor típusú módszerektől? Finomrács technika segítségével mérjük meg a módszer becsült rendjét kettes normában! \n\n\n\n```octave\n\n```\n\n\n```octave\n\n```\n\n ans =\n \n 4 65537\n \n ratekomp1 =\n \n 3.9916 3.9736 3.9864\n \n ratekomp2 =\n \n 3.9672 3.9649 3.9835\n \n ratekomp3 =\n \n 3.9926 3.9744 3.9868\n \n ratekomp4 =\n \n 3.9668 3.9648 3.9834\n \n a =\n \n 3.9864 3.9835 3.9868 3.9834\n \n ans = 3.9834\n\n\n
\n
\n\n### Explicit Gear módszerekről\n\n$$y_{i+1}=\\sum_{j=1}^ka_jy_{i-j}+hb_1f_{i}$$\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$k$$b_1$$a_1$$a_2$$a_3$$a_4$$a_5$$a_6$
$$1$$$$1$$$$1$$
$$2$$$$2$$$$0$$$$1$$
$$3$$$$3$$$$-\\frac{3}{2}$$$$\\frac{6}{2}$$$$-\\frac{1}{2}$$
$$4$$$$4$$$$-\\frac{10}{3}$$$$\\frac{18}{3}$$$$-\\frac{6}{3}$$$$\\frac{1}{3}$$
$$5$$$$5$$$$-\\frac{65}{12}$$$$\\frac{120}{12}$$$$-\\frac{60}{12}$$$$\\frac{20}{12}$$$$-\\frac{3}{12}$$
$$6$$$$6$$$$-\\frac{77}{10}$$$$\\frac{150}{10}$$$$-\\frac{100}{10}$$$$\\frac{50}{10}$$$$-\\frac{15}{10}$$$$\\frac{2}{10}$$
\n
\n
\nAz implementálás a már tanult AB módszerekhez hasonló. A gyakorlatban ritkán használják explicit merev megoldóként a kis abszolút stabilitási tartománya miatt.\n\n\n```octave\n\n```\n", "meta": {"hexsha": "a5d2e4e3486317677f88824987a4ad465565b6a2", "size": 57611, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "3.feladatsor.ipynb", "max_stars_repo_name": "feipaat/KozdiffNumerikus2-ELTE-", "max_stars_repo_head_hexsha": "0b9f69d576026b2dc148f7f04f28a600c93a20d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3.feladatsor.ipynb", "max_issues_repo_name": "feipaat/KozdiffNumerikus2-ELTE-", "max_issues_repo_head_hexsha": "0b9f69d576026b2dc148f7f04f28a600c93a20d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.feladatsor.ipynb", "max_forks_repo_name": "feipaat/KozdiffNumerikus2-ELTE-", "max_forks_repo_head_hexsha": "0b9f69d576026b2dc148f7f04f28a600c93a20d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 114.7629482072, "max_line_length": 17688, "alphanum_fraction": 0.8341809724, "converted": true, "num_tokens": 3721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3433489092862711}} {"text": "# Project 3 - Promoter Regions\n\nEtudiants:\n- ORTIZ Angelo\n- HANOUTI Célina\n\n\n```python\n# Les imports nécessaires pour ce mini-projet\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n%load_ext autoreload\n%autoreload 2\nimport utils\nimport project\n```\n\n## 2 Préliminaires : données et lecture des fichiers\n\n\n```python\ncerevisae, chromos_flattened, counts, freqs = \\\n utils.read_file(\"sequences/yeast_s_cerevisae_genomic_chr1-4.fna\")\nprint(\"S. cerevisae contient\", len(cerevisae), \"chromosones et\", \\\n len(chromos_flattened), \"nucléotides\")\nprint(\"Voici les nombres d'occurrence et les fréquences d'apparition de chaque nucléotide :\")\npd.DataFrame({'Occurrences': counts, 'Fréquence': freqs}, index=utils.nucleotide.keys())\n```\n\n S. cerevisae contient 4 chromosones et 2515853 nucléotides\n Voici les nombres d'occurrence et les fréquences d'apparition de chaque nucléotide :\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
OccurrencesFréquence
A7543420.299835
C5059430.201102
G5031630.199997
T7524050.299066
\n
\n\n\n\n## 3.1 Description empirique\n\nQ2) D'après l'hypothèse d'indépendance des occurrences des lettres dans le génome, pour un mot $w = w_1.w_2\\dots w_k$ de longueur $k$ donné, on connaît les fréquences des lettres $w_i$ le composant.\nDonc, la probabilité de trouver ce mot est donnée par \n$$P(w) = \\prod_{i=1}^{k} P(w_i).$$\n\nOn peut alors calculer le nombre d'occurrences du mot $w$ dans une séquence de longueur $l$ :\n$$\\text{comptage_attendu} = (l - k + 1)\\cdot P(w),$$\noù $l-k+1$ est le nombre de positions des occurrences du mot $w$.\n\n\n\nQ3) Dans les histogrammes ci-dessous, les écarts entre les nombres d’occurrences attendus et ceux observés sont repérés avec la droite $\\mathcal{L}: y = x$.\nEn effet, plus la distance entre un point et cette droite est grande, plus l'écart est important.\n\nOn remarque dans les histogrammes obtenus la présence de mots qui détiennent une fonction spéciale, étant donné que l'écart entre le comptage observé et le comptage attendu augmente avec la taille des n-grammes, notamment pour les longueurs 6 et 8.\n\nCeci correspond bien à l'hypothèse sur la taille des région promoteurs, qui comptent souvent entre 6 et 10 nucléobases.\nOn trouve ainsi 3 mots pour la séquence MET, 1 mot pour PHO, et 1 mot pour GAL, qui sont susceptibles d'appartenir à une région promoteur.\n\n\n```python\nfiles = [\"sequences/regulatory_seqs_MET.fasta\", \"sequences/regulatory_seq_PHO.fasta\", \\\n \"sequences/regulatory_seqs_GAL.fasta\"]\nks = [2, 4, 6, 8]\n\n # la séquence de nucléotides des séquences de contrôle\nchromos_list = project.plot_scatter(files, ks)\n\n# la distribution de probabilité des nucléotides sur la concaténation des 3 fichiers\nprobas = utils.nucleotide_frequency(chromos_list) \n```\n\n## 3.2 Simulation de séquences aléatoires\n\nQ3) On estime la probabilité d'observer un mot un certain nombre $n$ de fois par le proportion de séquences simulées où le mot est apparu au moins $n$ fois, c'est-à-dire\n$$P(N \\geq n) \\approx P_{emp}(N \\geq n) = \\frac{1}{S}\\cdot \\sum_{i=1}^{S} \\unicode{x1D7D9}_{N \\geq n},$$\noù $S$ est le nombre de simulations effectuées.\n\nQ4) Vous trouverez dans la cellule ci-dessous les histogrammes des distributions du comptage d'occurrences $P_{emp}(N \\geq n)$ pour les mots **ATCTGC**, **ATATAT**, **TTTAAA** et **AAAAAA**.\n\nOn remarque que les mots ATATAT et TTTAAA ont la même probabilité d'apparaître, puisque la probabilité empirique d'un nombre d'occurrences nul est zéro.\nCependant, leurs distributions de comptage d'occurrences est différente.\nEn effet, la distribution du mot TTTAAA decroît légèrement plus vite que celle du mot ATATAT. \nCeci peut s'expliquer par le fait que le mot ATATAT chevauche avec lui-même, ce qui donne lieu a plus d'occurrences.\nPour observer ce comportement, il suffit de regarder le nombre d'occurrences maximal des deux mots, et leur comportement entre 15 et 20 occurrences.\n\n\n```python\nproject.plot_histogram(chromos_list, probas, 1000)\n```\n\nQ5) On peut calculer un intervalle de confiance pour la probabilité d'observer un mot avec sa probabilité empirique : \n$$p_{emp} \\sim \\mathcal{N}\\left(p, \\sqrt \\frac{p\\cdot (1-p)}{n}\\right),$$\noù $n$ est le nombre (suffisamment grand) de simulations effectuées.\n\nPour un risque de 5 % ($z_{2.5\\%} = 1.96$), on obtient l'intervalle\n$$\\left[p_{emp} - 1.96 \\cdot \\sqrt \\frac{p_{emp}\\cdot (1-p_{emp})}{n}, \np_{emp} - 1.96 \\cdot \\sqrt \\frac{p_{emp}\\cdot (1-p_{emp})}{n} \\right]$$\n\n## 3.3 Modèles de dinucléotides et trinucléotides\n\nQ1) On prend $\\mathcal{X} = \\{A, C, G, T\\}$. Le modèle décrit correspond à une chaîne de Markov homogène d'ordre 1 car il remplit les 3 conditions :\n- c'est un processus stochastique à temps discret avec les v.a. $X_i$ correpondant à la nucléobase à la position $i$ dans un génome ;\n- l'ensemble des états $\\mathcal{X}$ est fini ;\n- la propriété de markov d'ordre 1 est vérifiée : $\\forall i \\geq 0, P(X_{i+1}|X_0,\\dots, X_i) = P(X_{i+1}|X_i)$. Autrement dit, la loi du prochain nucléotide de la séquence ne dépend que du nucléotide précédent.\n\nDe plus, cette chaîne de Markov est homogène car les probabilités de transition ne dépendent pas d'une variable temporelle.\n\nPar ailleurs, la probabilité stationnaire de cette chaîne correspond aux proportions des nucléobases dans un génome auxquelles on s'attend.\n\nQ5) De la même manière que dans la question 3.1.2), le nombre d'occurrences attendu est\n$$\\text{comptage_attendu} = (l - k + 1)\\cdot P(w),$$\nsauf que, dans ce cas, la probabilité d'apparition du mot est calculée différemment. En effet, on utilise la propriété de Markov d'ordre 1 pour obtenir le résultat suivant :\n$$\n\\begin{align}\n P(w) &= P(w_1)\\cdot \\prod_{i=2}^{k} P(w_i|w_1, \\dots, w_{i-1}) \\\\\n P(w) &= P(w_1)\\cdot \\prod_{i=2}^{k} P(w_i|w_{i-1}).\n\\end{align}\n$$\n\nPour la probabilité du premier nucléotide, à savoir $P(w_1)$, on a utilisé $\\pi^\\ast$, i.e. la distribution stationnaire de la chaîne de Markov, pour le calcul de la probabilité ci-dessus.\nOn a néanmoins remarqué lors du calcul de cette distribution que les $\\pi^{(n)}$ convergent très rapidement.\nC'est pourquoi il aurait été aussi sensé d'utiliser $\\pi^{(0)}$.\n\nQ6) Dans la cellule ci-dessous, on s'aperçoit que le modèle des dinucléotides est plus représentatif des séquences de génome utilisées que le modèle des nucléotides.\n\nCependant, cet effet s'attenue au fur et à mesure que la longueur des n-grammes augmente.\n\nOn pourra donc dire que le modèle des **nucléotides** reste utile pour la recherche des mots promoteurs, puisque leur longueur varie entre 6 et 10.\n\n\n```python\nproject.plot_counts(chromos_list, probas)\n```\n\n## 3.4 Probabilité de mots\n\nQ1) En faisant l'hypothèse d'indépendance des positions d'occurrences d'un mot **non chevauchant** $w$, on peut approcher le comptage du nombre d'occurrences dans une séquence de longueur $l$ avec la loi $Bin(P(w),\\ l-k+1)$, où $P(w)$ sera calculée au moyen des modèles de nucléotides et de dinucléotides.\n\nQ2) Etant donné que la longueur des séquences est au moins de l'ordre de 10 000, le deuxième paramètre de ladite loi binomiale est beaucoup plus grand que la probabilité $P(w)$.\n\nDe ce fait, on peut approcher cette loi avec la loi $Pois(P(w)\\cdot (l-k+1))$.\n\nQ3) Les figures ci-dessous montrent les distributions de probabilité empirique des mots ATCTGC, ATATAT, TTTAAA et AAAAAA obtenues en simulant 1000 séquences aléatoires avec le modèle des nucléotides.\nNous avons représenté également un nuage de points représentant le complémentaire de la répartition de la loi de Poisson avec $P(w)$ obtenu suivant les modèles de nucléotides et dinucléotides (par chaîne de Markov).\n\n**N.B. On fera dans la suite une analyse par rapport à la courbe de la loi de Poisson utilisant le modèle des chaînes de Markov.**\n\nOn remarque que l'histogramme représentant la probabilité empirique du mot ATCTGC, qui ne se chevauche pas, est très proche de la loi de Poisson. Malgré le fait que le mot ATATAT n'est pas chevauchant avec lui même, L’histogramme de la probabilité empirique de ce mot est quelque peu eloigné de la loi de Poisson correspondante.\n\nEn revanche, étant chavauchant avec lui même, l’histogramme de la probabilité empirique du mot AAAAAA s’écarte beaucoup de la loi de Poisson.\n\nDe ces faits, l’hypothèse d'indépendance en les différentes positions d'occurrences d'un mot et l'utilisation de la loi binomiale pour le comptage ne sont pas pértinents pour les mots qui chevauchent avec eux-mêmes.\n\n\n```python\nproject.plot_histogram(chromos_list, probas, 1000, expected=True)\n```\n\nQ5) Un mot qui apparaît significativement plus qu'attendu est un mot dont la probabilité empirique de dépasser le comptage observé est faible. Pour cela, nous avons trié les mots par ordre croissant de cette probabilité. Puis, on a fixé un seuil de coupure $\\epsilon$ tel que les mots les plus inattendus sont ceux dont la probabilité empirique est inférieure à ce seuil.\n$$P(N_{w} \\geq n_{w}) < \\epsilon$$\nOn fixe $\\epsilon$ à 0.02\n\n### Modèle de nucléotides\nPour $k = 2$, les mots les plus inattendus sont :\n\n'GC', 'TT'.\n\nPour $k = 4$, les mots les plus inattendus sont :\n\n'AAAA', 'TTTT', 'CAGC'.\n\nPour $n = 6$, les mots les plus inattendus sont :\n\n'AAAAAA', 'CACGTG', 'TCATCT', 'CAAGAA', 'GCAGCA', 'TGCCAA', 'TTTTTT', 'CGTGGG'.\n\n#### Conclusion\nAvec ce modèle, les séquences 'AAAAAA', 'TTTTTT', 'GCAGCA' se trouvent dans les sites de fixation.\n\n### Modèle de dinucléotides\n\nPour $k = 2$, il n'y a pas de mot inattendu.\n\nPour $k = 4$, les mots les plus inattendus sont :\n\n'ACGT', 'AAAA', 'CGTG'\n\nPour $n = 6$, les mots les plus inattendus sont :\n\n'AAAAAA', 'TATATA', 'TCATCT', 'CACGTG', 'ACGTGG', 'CGTGGG', 'GAAGAA', 'CAAGAA', 'ACGTGC', 'TGCCAA'.\n\n#### Conclusion\nAvec ce modèle, les séquences 'AAAAAA', 'ACGTGG', 'ACGTGC', 'CACGTG' se trouvent dans les sites de fixation.\nMis à part la séquence 'AAAAAA' qui appartient forcément à un site de fixation, le modèle des dinucléotides ne permet pas de trouver les mots chevauchant avec eux-mêmes susceptibles de se trouver dans une région promoteur.\n\n\n```python\n_, chromos_PHO, counts_PHO, freqs_PHO = utils.read_file(files[1])\nnt, dint = project.sort_unexpected_words(chromos_PHO, freqs_PHO, [2, 4, 6 ,8], 0.002)\n```\n\n\n```python\nprint(\"Nucléotides\")\nprint(\"===========\")\nprint(\"k = 2 :\", nt[0])\nprint(\"k = 4 :\", nt[1][:3])\nprint(\"k = 6 :\", nt[2][:8])\n```\n\n Nucléotides\n ===========\n k = 2 : [('GC', 7.69693389768289e-06), ('TT', 0.0002337053950783874)]\n k = 4 : [('AAAA', 2.5964341787698686e-11), ('TTTT', 1.0729857979896451e-07), ('CAGC', 6.06612669363793e-05)]\n k = 6 : [('AAAAAA', 0.0), ('CACGTG', 1.6920897301098137e-06), ('TCATCT', 2.195556734641002e-06), ('CAAGAA', 4.8302813431266856e-06), ('GCAGCA', 5.856189141728585e-06), ('TGCCAA', 6.05191253999493e-06), ('TTTTTT', 1.312040984391416e-05), ('CGTGGG', 1.8057310173680285e-05)]\n\n\n\n```python\nprint(\"Dinucléotides\")\nprint(\"=============\")\nprint(\"k = 2 :\", dint[0])\nprint(\"k = 4 :\", dint[1][:3])\nprint(\"k = 6 :\", dint[2][:10])\n```\n\n Dinucléotides\n =============\n k = 2 : []\n k = 4 : [('ACGT', 1.378394142981243e-05), ('AAAA', 6.324769583387901e-05), ('CGTG', 7.843519915196051e-05)]\n k = 6 : [('AAAAAA', 2.220446049250313e-16), ('TATATA', 8.609168137274636e-07), ('TCATCT', 1.1803502472096383e-06), ('CACGTG', 1.4190981796335933e-06), ('ACGTGG', 5.357991372800797e-06), ('CGTGGG', 7.022354704400158e-06), ('GAAGAA', 2.4193239793968147e-05), ('CAAGAA', 4.516515199359805e-05), ('ACGTGC', 5.3097112990396766e-05), ('TGCCAA', 7.366812330045214e-05)]\n\n\n\n```python\nproject.unexpected_words(chromos_PHO, freqs_PHO, 6, 0.002)\n```\n\n Convergence after 3 iterations\n word: AAAAAA\t\tOccurrences: 43\t\tP(N >= 43) = 0.0000\n word: AAACGT\t\tOccurrences: 7\t\tP(N >= 7) = 0.0004\n word: AAGAAA\t\tOccurrences: 11\t\tP(N >= 11) = 0.0009\n word: AAGAAG\t\tOccurrences: 8\t\tP(N >= 8) = 0.0004\n word: ACCTTG\t\tOccurrences: 4\t\tP(N >= 4) = 0.0005\n word: ACGTAT\t\tOccurrences: 5\t\tP(N >= 5) = 0.0003\n word: ACGTGC\t\tOccurrences: 5\t\tP(N >= 5) = 0.0001\n word: ACGTGG\t\tOccurrences: 5\t\tP(N >= 5) = 0.0000\n word: ACTACT\t\tOccurrences: 4\t\tP(N >= 4) = 0.0011\n word: AGAAGA\t\tOccurrences: 6\t\tP(N >= 6) = 0.0019\n word: AGGGCA\t\tOccurrences: 4\t\tP(N >= 4) = 0.0020\n word: ATCTCT\t\tOccurrences: 4\t\tP(N >= 4) = 0.0015\n word: ATGCCA\t\tOccurrences: 5\t\tP(N >= 5) = 0.0009\n word: CAAGAA\t\tOccurrences: 10\t\tP(N >= 10) = 0.0000\n word: CACGTG\t\tOccurrences: 6\t\tP(N >= 6) = 0.0000\n word: CATCTC\t\tOccurrences: 4\t\tP(N >= 4) = 0.0009\n word: CCACGT\t\tOccurrences: 3\t\tP(N >= 3) = 0.0013\n word: CCCGTT\t\tOccurrences: 3\t\tP(N >= 3) = 0.0007\n word: CCGCAC\t\tOccurrences: 3\t\tP(N >= 3) = 0.0016\n word: CGTATA\t\tOccurrences: 4\t\tP(N >= 4) = 0.0017\n word: CGTGCG\t\tOccurrences: 3\t\tP(N >= 3) = 0.0011\n word: CGTGGG\t\tOccurrences: 4\t\tP(N >= 4) = 0.0000\n word: CTCATC\t\tOccurrences: 5\t\tP(N >= 5) = 0.0001\n word: CTCGTA\t\tOccurrences: 4\t\tP(N >= 4) = 0.0003\n word: CTCTAC\t\tOccurrences: 3\t\tP(N >= 3) = 0.0017\n word: CTGCAC\t\tOccurrences: 4\t\tP(N >= 4) = 0.0007\n word: GAAACG\t\tOccurrences: 5\t\tP(N >= 5) = 0.0011\n word: GAAGAA\t\tOccurrences: 9\t\tP(N >= 9) = 0.0000\n word: GAGATC\t\tOccurrences: 4\t\tP(N >= 4) = 0.0006\n word: GATAAG\t\tOccurrences: 5\t\tP(N >= 5) = 0.0015\n word: GCACGT\t\tOccurrences: 5\t\tP(N >= 5) = 0.0001\n word: GCAGCA\t\tOccurrences: 6\t\tP(N >= 6) = 0.0014\n word: GGAAGA\t\tOccurrences: 5\t\tP(N >= 5) = 0.0003\n word: GTATAT\t\tOccurrences: 5\t\tP(N >= 5) = 0.0006\n word: GTGCAG\t\tOccurrences: 4\t\tP(N >= 4) = 0.0012\n word: TATACG\t\tOccurrences: 4\t\tP(N >= 4) = 0.0014\n word: TATATA\t\tOccurrences: 10\t\tP(N >= 10) = 0.0000\n word: TCATCT\t\tOccurrences: 8\t\tP(N >= 8) = 0.0000\n word: TCCTCT\t\tOccurrences: 3\t\tP(N >= 3) = 0.0012\n word: TCTTTG\t\tOccurrences: 5\t\tP(N >= 5) = 0.0011\n word: TGAGCT\t\tOccurrences: 4\t\tP(N >= 4) = 0.0017\n word: TGATGT\t\tOccurrences: 4\t\tP(N >= 4) = 0.0011\n word: TGCCAA\t\tOccurrences: 7\t\tP(N >= 7) = 0.0001\n word: TGGCAC\t\tOccurrences: 4\t\tP(N >= 4) = 0.0007\n word: TGTGGC\t\tOccurrences: 3\t\tP(N >= 3) = 0.0017\n word: TTATCA\t\tOccurrences: 7\t\tP(N >= 7) = 0.0008\n word: TTGGCA\t\tOccurrences: 5\t\tP(N >= 5) = 0.0020\n word: TTTATC\t\tOccurrences: 6\t\tP(N >= 6) = 0.0017\n word: TTTCCT\t\tOccurrences: 5\t\tP(N >= 5) = 0.0006\n word: TTTTCG\t\tOccurrences: 6\t\tP(N >= 6) = 0.0013\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "c2bfaab9a6839937033683170174a9faa37ea07c", "size": 390148, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "report.ipynb", "max_stars_repo_name": "hanouticelina/promoter--regions", "max_stars_repo_head_hexsha": "b1965dfe754d91fa0cb90b9b1535dc49cf6f1f73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "report.ipynb", "max_issues_repo_name": "hanouticelina/promoter--regions", "max_issues_repo_head_hexsha": "b1965dfe754d91fa0cb90b9b1535dc49cf6f1f73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "report.ipynb", "max_forks_repo_name": "hanouticelina/promoter--regions", "max_forks_repo_head_hexsha": "b1965dfe754d91fa0cb90b9b1535dc49cf6f1f73", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 545.6615384615, "max_line_length": 126472, "alphanum_fraction": 0.938115792, "converted": true, "num_tokens": 5434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.3427852346428398}} {"text": "# Transformação de Fontes\n\nJupyter Notebook desenvolvido por [Gustavo S.S.](https://github.com/GSimas)\n\n**Transformação de fontes é o processo de substituir uma fonte de tensão\nvs em série com um resistor R por uma fonte de corrente is em paralelo com\num resistor R, ou vice-versa.**\n\nAssim como na transformação estrela-triângulo, uma\ntransformação de fontes não afeta a parte remanescente do circuito.\n\n\n\nPortanto, a transformação de fontes requer que\n\n\\begin{align}\n{\\Large v_s = i_sR}\n\\\\\n\\\\{\\Large i_s = \\frac{v_s}{R}}\n\\end{align}\n\nA transformação de fontes também se aplica a fontes dependentes, desde\nque tratemos adequadamente a variável dependente.\n\n\n\n**Exemplo 4.6**\n\nUse transformação de fontes para determinar vo no circuito da Figura 4.17.\n\n\n\n\n```python\nprint(\"Exemplo 4.6\")\n#trasforma fonte 1 (corrente -> tensao)\n#vs1 = is*R = 12V\n\n#Req em serie entre 4 e 2\n#Req1 = 4 + 2 = 6\n\n#transforma fonte 2 (tensao -> corrente)\n#is2 = 12/3 = 4A\n\n#transforma fonte 1 (tensao -> corrente)\n#is1 = 12/6 = 2A\n\n#Req paralelo entre 6 e 3\n#Req2 = 6*3/(6 + 3) = 2\n\n#fonte resultante\n#ir = is2 - is1 = 4 - 2 = 2A\n\n#transforma fonte 2 (corrente -> tensao)\n#vs2 = Req2*ir = 2 * 2 = 4V\n\n#divisor tensao\n#v0 = vs2*8/(8 + Req2)\nv0 = 4*8/(8 + 2)\n\nprint(\"Tensao v0\",v0,\"V\")\n```\n\n Exemplo 4.6\n Tensao v0 3.2 V\n\n\n**Problema Prático 4.6**\n\nDetermine io no circuito da Figura 4.19 usando transformação de fontes.\n\n\n\n\n```python\nprint(\"Problema Prático 4.6\")\n#Req serie 4 e 1 = 5\n#Req paralelo 6 e 3 = 2\n\n#transforma fonte 1 (corrente -> tensao)\n#vs1 = R*is1 = 5*2 = 10V\n\n#soma fonte 1 e 2 = 5 + 10 = 15V\n\n#transforma fonte soma (tensao -> corrente)\n#is = 15/2 = 7,5A\n\n#Req paralelo 5 e 2 = 10/7\n\n#soma fonte corrente = 7,5 + 3 = 10,5 A\n\n#divisor corrente\ni0 = 10.5*(10/7)/((10/7) + 7)\n\nprint(\"Corrente i0:\",i0,\"A\")\n```\n\n Problema Prático 4.6\n Corrente i0: 1.7796610169491525 A\n\n\n**Exemplo 4.7**\n\nDetermine vx na Figura 4.20 usando transformação de fontes.\n\n\n\n\n```python\nprint(\"Exemplo 4.7\")\n\n#transforma fonte 1 (tensao -> corrente)\n#is1 = 6/2 = 3 A\n\n#transforma fonte dep. (corrente -> tensao)\n#vs_dep = 0.25Vx * 4 = Vx\n\n#soma fonte dep. e fonte 2 = 18 + Vx\n\n#Req paralelo 2 e 2 = 1\n\n#transforma fontes soma (tensao -> corrente)\n#is_soma = 18/4 + Vx/4\n\n#soma fontes = 18/4 + Vx/4 + 3 = 30/4 + Vx/4 = (30 + Vx)/4\n\n#transforma fontes soma (corrente -> tensao)\n#fonte resultante = ((30 + Vx)/4)*4 = 30 + Vx\n\n#LKT\n#(30 + Vx) - 4*ix - Vx = 0\n#ix = (30 + Vx)/5 = 6 + Vx/5\n#30 - 24 - 4Vx/5 = 0\nvx = 6*5/4\nprint(\"Tensão Vx\",vx,\"V\")\n```\n\n Exemplo 4.7\n Tensão Vx 7.5 V\n\n\n**Problema Prático 4.7**\n\nUse transformação de fontes para determinar ix no circuito exposto na Figura 4.22.\n\n\n\n\n```python\nprint(\"Problema Prático 4.7\")\n\n#transforma fonte dep. (tensao -> corrente)\n#is_dep = 2ix/5\n\n#soma fontes = 0.024 - 2ix\n\n#divisor corrente\n#ix = (24m - 2ix)*5/(5 + 10)\n #ix = (0.12 - 10ix)/15\n #ix + 2ix/3 = 0.008\n #5ix/3 = 0.008\nix = 0.008*3/5\nprint(\"Corrente ix:\",ix,\"A\")\n```\n\n Problema Prático 4.7\n 0.008\n\n\n# Teorema de Thèvenin\n\n**O teorema de Thévenin afirma que um circuito linear de dois terminais\npode ser substituído por um circuito equivalente formado por uma fonte\nde tensão VTh em série com um resistor RTh, onde VTh é a tensão de circuito\naberto nos terminais e RTh, a resistência de entrada ou equivalente nos\nterminais quando as fontes independentes forem desativadas.**\n\nO teorema de Thévenin é muito importante na análise de circuitos, porque\najuda a simplificar um circuito, e um circuito grande pode ser substituído por\numa única fonte de tensão independente e um único resistor.\n\n\n\nPara tanto, suponha\nque os dois circuitos da Figura 4.23 sejam equivalentes – dois circuitos são\nditos equivalentes se tiverem a mesma relação tensão-corrente em seus terminais. Se\nos terminais a-b forem tornados um circuito aberto (eliminando-se a carga),\nnenhuma corrente fluirá e, portanto, a tensão nos terminais a-b da Figura 4.23a\nterá de ser igual à fonte de tensão VTh da Figura 4.23b, já que os dois circuitos\nsão equivalentes. Logo:\n\n\\begin{align}\n{\\Large V_{Th} = v_{oc}}\n\\end{align}\n\nA resistência de entrada (ou\nresistência equivalente) do circuito inativo nos terminais a-b da Figura 4.23a\ndeve ser igual a RTh da Figura 4.23b, pois os dois circuitos são equivalentes.\nPortanto, RTh é a resistência de entrada nos terminais quando as fontes\nindependentes forem desligadas. Logo:\n\n\\begin{align}\n{\\Large R_{Th} = R_{oc}}\n\\end{align}\n\n\n\n- **Caso 1:** Se a rede não tiver fontes dependentes, **desligamos todas as fontes independentes**. RTh é a resistência de entrada da rede, olhando-se entre os terminais a e b.\n- **Caso 2:** Se a rede tiver fontes dependentes, **desligamos todas as fontes independentes**. As fontes dependentes não devem ser desligadas, pois elas são controladas por variáveis de circuito. Aplicamos uma tensão vo aos terminais a e b, e determinamos a corrente resultante io. Então, RTh = vo/io. De forma alternativa, poderíamos inserir uma fonte de corrente io nos terminais a e b, como na Figura 4.25b, e encontrar a tensão entre os terminais vo. Chegamos novamente a RTh = vo/io. Qualquer um dos dois métodos leva ao mesmo resultado. Em ambos os métodos, podemos supor qualquer valor de vo e io. Poderíamos usar, por exemplo, vo = 1 V ou io = 1 A, ou até mesmo valores não especificados de vo ou io.\n\n\n\nMuitas vezes, pode ocorrer de RTh assumir um valor negativo; nesse caso,\na resistência negativa (v = –iR) implica o fato de o circuito estar **fornecendo\nenergia.**\n\n**Exemplo 4.8**\n\nDetermine o circuito equivalente de Thévenin do circuito mostrado na Figura 4.27,\nà esquerda dos terminais a-b. Em seguida, determine a corrente através de RL = 6 Ω,\n16 Ω e 36 Ω.\n\n\n\n\n```python\nprint(\"Exemplo 4.8\")\n\n#Req1 = 4*12/(4 + 12) = 48/16 = 3\n#Rth = 3 + 1 = 4\n\n#transforma fonte 1 (tensao -> corrente)\n#is1 = 32/4 = 8 A\n\n#soma fontes = 8 + 2 = 10 A\n\n#ix = 10*4/(4 + 12) = 40/16 = 5/2\n#Vab = 12*(5/2) = 30 = Vth\n\nVth = 30\nRth = 4\n\nRl = 6\nIl = Vth/(Rl + Rth)\nprint(\"Para RL = 6, Corrente:\",Il,\"A\")\n\nRl = 16\nIl = Vth/(Rl + Rth)\nprint(\"Para RL = 6, Corrente:\",Il,\"A\")\n\nRl = 36\nIl = Vth/(Rl + Rth)\nprint(\"Para RL = 6, Corrente:\",Il,\"A\")\n```\n\n Exemplo 4.8\n Para RL = 6, Corrente: 3.0 A\n Para RL = 6, Corrente: 1.5 A\n Para RL = 6, Corrente: 0.75 A\n\n\n**Problema Prático 4.8**\n\nUsando o teorema de Thévenin, determine o circuito equivalente à esquerda dos terminais do circuito da Figura 4.30. Em seguida, determine I.\n\n\n\n\n```python\nprint(\"Problema Prático 4.8\")\n\n#Req1 = 6 + 6 = 12\n#Rth = Req1*4/(Req1 + 4) = 48/16 = 3\nRth = 3\n\n#Superposicao Vsource\n#Vab1 = Vs*4/(4 + 6 + 6) = 12*4/16 = 3V\n\n#Superposicao Csource\n#Iab = Is*6/(4 + 6 + 6) = 2*6/16 = 3/4\n#Vab2 = Iab*4 = 3V\n\n#Vth = Vab1 + Vab2\nVth = 6\n\nI = Vth/(Rth + 1)\nprint(\"Tensao Vth:\",Vth,\"V\")\nprint(\"Resistencia Rth:\",Rth)\nprint(\"Corrente I:\",I,\"A\")\n```\n\n Problema Prático 4.8\n Tensao Vth: 6 V\n Resistencia Rth: 3\n Corrente I: 1.5 A\n\n\n**Exemplo 4.9**\n\nDetermine o equivalente de Thévenin do circuito da Figura 4.31.\n\n\n\n\n```python\nprint(\"Exemplo 4.9\")\n\nimport numpy as np\n\n#Descobrir Rth - desliga fontes indep., nao se alteram fontes dep.\n#Aplicar tensao vo arbitraria entre terminais a b\n#vo = 1 V\n#Analise de malhas\n\n#-2Vx + 2(i1 - i2) = 0\n #Vx = i1 - i2\n #Vx = -4i2\n #i1 + 3i2 = 0\n#-Vx + 2(i2 - i1) + 6(i2 - i3) = 0\n #2i2 - 2i1 + 6i2 - 6i3 = Vx\n #-3i1 + 9i2 - 6i3 = 0\n #-i1 + 3i2 - 2i3 = 0\n#Vo + 6(i3 - i2) + 2i3 = 0\n #6i3 - 6i2 + 2i3 = -1\n #-6i2 + 8i3 = -1\n\ncoef = np.matrix(\"1 3 0;-1 3 -2;0 -6 8\")\nres = np.matrix(\"0;0;-1\")\nI = np.linalg.inv(coef)*res\n\n#i3 = -i0\nio = -I[2]\n#Rth = Vo/io\nRth = 1/io\nprint(\"Resistencia Rth:\",float(Rth))\n\n#Descobrir Vth\n#Analise de tensao em terminais a b\n#Analise de Malhas\n\n#i1 = 5 A\n#-2Vx + 2(i2 - i3) = 0\n #Vx = i2 - i3\n #Vx = 4(5 - i3) = 20 - 4i3\n #i2 + 3i3 = 20\n#4(i3 - 5) + 2(i3 - i2) + 6i3 = 0\n #4i3 +2i3 - 2i2 + 6i3 = 20\n #-2i2 + 12i3 = 20\n #-i2 + 6i3 = 10\n\ncoef = np.matrix(\"1 3;-1 6\")\nres = np.matrix(\"20;10\")\nI = np.linalg.inv(coef)*res\nVth = 6*I[1]\n\nprint(\"Tensão Vth:\",float(Vth),\"V\")\n```\n\n Exemplo 4.9\n Resistencia Rth: 6.0\n Tensão Vth: 20.0 V\n\n\n**Problema Prático 4.9**\n\nDetermine o equivalente de Thévenin do circuito da Figura 4.34 à esquerda dos terminais.\n\n\n\n\n```python\nprint(\"Problema Prático 4.9\")\n\n#Descobrir Rth\n#Vo = 1V\n#Analise Nodal\n\n#i1 - Ix/2 = 0\n #v1/5 - Ix/2 = 0\n #Ix = (v1 - 1)/3\n #v1/5 - (v1 - 1)/6 = 0\n #v1/5 - v1/6 = -1/6\n #v1/30 = -1/6\n #v1 = -5\n#Ix = (v1 - 1)/3 = -6/3 = -2 A\n#i2 = 1/4 A\n#io = -Ix + i2 = 9/4 A\n\n#Rth = 1/(9/4) = 4/9\nRth = 4/9\nprint(\"Resistencia Rth:\",Rth)\n\n#Descobrir Vth\n#Analise de Malhas\n#-6 + 5i1 + 3Ix + 4Ix = 0\n #5i1 + 7Ix = 6\n#3Ix/2 + i1 = Ix\n #Ix/2 + i1 = 0\n #2i1 + Ix = 0\n\ncoef = np.matrix(\"5 7;2 1\")\nres = np.matrix(\"6;0\")\nI = np.linalg.inv(coef)*res\nIx = float(I[1])\nVth = 4*Ix\nprint(\"Tensão Vth:\",Vth,\"V\")\n```\n\n Problema Prático 4.9\n Resistencia Rth: 0.4444444444444444\n Tensão Vth: 5.333333333333333 V\n\n\n**Exemplo 4.10**\n\nDetermine o equivalente de Thévenin do circuito da Figura 4.35a nos terminais a-b.\n\n\n\n\n```python\nprint(\"Exemplo 4.10\")\n#vab = -vo = -1 V\n#i1 = 1/4 A\n#ix = 1/2 A\n#i0 = 2ix - ix - i1 = 1 - 1/2 - 1/4 = 1/4 A\n#Rth = -1/(1/4) = -4\nRth = -4\nprint(\"Resistencia Rth:\", Rth)\nprint(\"Tensao Vth:\",0,\"V\")\n```\n\n Exemplo 4.10\n Resistencia Rth: -4\n Tensao Vth: 0 V\n\n\n**Problema Prático 4.10**\n\nObtenha o equivalente de Thévenin do circuito da Figura 4.36.\n\n\n\n\n```python\nprint(\"Problema Prático 4.10\")\n#iab = 1 A\n#-vx + 10i1 + 4vx + 15(i1 - iab) = 0\n #3vx + 25i1 - 15iab = 0\n #vx = -5i1\n #-15i1 + 25i1 = 15\n #10i1 = 15\n #i1 = 1,5 A = 3/2 A\n#vx = -5i1 = -7,5 V = -15/2 V\n#vdep = 4*vx = -30V\n\n#vab = vo = 15(i1 - iab) = 15/2 = 7,5V\n#Rth = vo/(-iab) = -7,5\nRth = -7.5\nprint(\"Tensao Vth:\",0,\"V\")\nprint(\"Resistencia Rth\",Rth)\n```\n\n Problema Prático 4.10\n Tensao Vth: 0 V\n Resistencia Rth -7.5\n\n", "meta": {"hexsha": "c58f277897a75dcf90730881b231a07d12a292ed", "size": 17439, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Aula 7 - Teorema de Thevenin.ipynb", "max_stars_repo_name": "ofgod2/Circuitos-electricos-Boylestad-12ed-Portugues", "max_stars_repo_head_hexsha": "60e815f6904858f3cda8b5c7ead8ea77aa09c7fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-08-13T13:33:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T16:46:06.000Z", "max_issues_repo_path": "Aula 7 - Teorema de Thevenin.ipynb", "max_issues_repo_name": "ofgod2/Circuitos-electricos-Boylestad-12ed-Portugues", "max_issues_repo_head_hexsha": "60e815f6904858f3cda8b5c7ead8ea77aa09c7fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-08-24T17:36:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-24T17:36:15.000Z", "max_forks_repo_path": "Aula 7 - Teorema de Thevenin.ipynb", "max_forks_repo_name": "ofgod2/Circuitos-electricos-Boylestad-12ed-Portugues", "max_forks_repo_head_hexsha": "60e815f6904858f3cda8b5c7ead8ea77aa09c7fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2019-03-29T14:31:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T17:59:23.000Z", "avg_line_length": 26.6651376147, "max_line_length": 718, "alphanum_fraction": 0.4926314582, "converted": true, "num_tokens": 4238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.3427852311173148}} {"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Quantum simulation of electronic structure\n\n\n \n \n \n \n
\n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nThe quantum simulation of electronic structure is one of the most promising applications of quantum computers. It has potential applications to materials and drug design. This tutorial provides an introduction to OpenFermion, a library for obtaining and manipulating representations of fermionic and qubit Hamiltonians as well as compiling quantum simulation circuits in Cirq.\n\n\n```\ntry:\n import openfermion as of\n import openfermionpyscf as ofpyscf\nexcept ImportError:\n print(\"Installing OpenFermion and OpenFermion-PySCF...\")\n !pip install openfermion openfermionpyscf --quiet\n```\n\n\n```\nimport numpy as np\nfrom scipy.sparse import linalg\n\nimport cirq\nimport openfermion as of\nimport openfermionpyscf as ofpyscf\n```\n\n## Background\n\nA system of $N$ fermionic modes is\ndescribed by a set of fermionic *annihilation operators*\n$\\{a_p\\}_{p=0}^{N-1}$ satisfying the *canonical anticommutation relations*\n$$\\begin{aligned}\n \\{a_p, a_q\\} &= 0, \\\\\n \\{a_p, a^\\dagger_q\\} &= \\delta_{pq},\n \\end{aligned}$$ where $\\{A, B\\} := AB + BA$. The adjoint\n$a^\\dagger_p$ of an annihilation operator $a_p$ is called a *creation\noperator*, and we refer to creation and annihilation operators as\nfermionic *ladder operators*.\n \nThe canonical anticommutation relations impose a number of consequences on the structure of the vector space on which the ladder operators act; see [Michael Nielsen's notes](http://michaelnielsen.org/blog/archive/notes/fermions_and_jordan_wigner.pdf) for a good discussion.\n\nThe electronic structure Hamiltonian is commonly written in the form\n$$\n\\sum_{pq} T_{pq} a_p^\\dagger a_q + \\sum_{pqrs} V_{pqrs} a_p^\\dagger a_q^\\dagger a_r a_s\n$$\nwhere the $T_{pq}$ and $V_{pqrs}$ are coefficients which depend on the physical system being described. We are interested in calculating the lowest eigenvalue of the Hamiltonian. This eigenvalue is also called the ground state energy.\n\n\n## FermionOperator and QubitOperator\n\n### `openfermion.FermionOperator`\n\n- Stores a weighted sum (linear combination) of fermionic terms\n- A fermionic term is a product of ladder operators\n- Examples of things that can be represented by `FermionOperator`:\n$$\n\\begin{align}\n& a_1 \\nonumber \\\\\n& 1.7 a^\\dagger_3 \\nonumber \\\\\n&-1.7 \\, a^\\dagger_3 a_1 \\nonumber \\\\\n&(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 \\nonumber \\\\\n&(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 - 1.7 \\, a^\\dagger_3 a_1 \\nonumber\n\\end{align}\n$$\n\n- A fermionic term is internally represented as a tuple of tuples\n- Each inner tuple represents a single ladder operator as (index, action)\n- Examples of fermionic terms:\n$$\n\\begin{align}\nI & \\mapsto () \\nonumber \\\\\na_1 & \\mapsto ((1, 0),) \\nonumber \\\\\na^\\dagger_3 & \\mapsto ((3, 1),) \\nonumber \\\\\na^\\dagger_3 a_1 & \\mapsto ((3, 1), (1, 0)) \\nonumber \\\\\na^\\dagger_4 a^\\dagger_3 a_9 a_1 & \\mapsto ((4, 1), (3, 1), (9, 0), (1, 0)) \\nonumber\n\\end{align}\n$$\n\n- `FermionOperator` is a sum of terms, represented as a dictionary from term to coefficient\n\n\n```\nop = of.FermionOperator(((4, 1), (3, 1), (9, 0), (1, 0)), 1+2j) + of.FermionOperator(((3, 1), (1, 0)), -1.7)\n\nprint(op.terms)\n```\n\n {((4, 1), (3, 1), (9, 0), (1, 0)): (1+2j), ((3, 1), (1, 0)): -1.7}\n\n\nAlternative notation, useful when playing around:\n\n$$\n\\begin{align}\nI & \\mapsto \\textrm{\"\"} \\nonumber \\\\\na_1 & \\mapsto \\textrm{\"1\"} \\nonumber \\\\\na^\\dagger_3 & \\mapsto \\textrm{\"3^\"} \\nonumber \\\\\na^\\dagger_3 a_1 & \\mapsto \\textrm{\"3^}\\;\\textrm{1\"} \\nonumber \\\\\na^\\dagger_4 a^\\dagger_3 a_9 a_1 & \\mapsto \\textrm{\"4^}\\;\\textrm{3^}\\;\\textrm{9}\\;\\textrm{1\"} \\nonumber\n\\end{align}\n$$\n\n\n```\nop = of.FermionOperator('4^ 3^ 9 1', 1+2j) + of.FermionOperator('3^ 1', -1.7)\n\nprint(op.terms)\n```\n\n {((4, 1), (3, 1), (9, 0), (1, 0)): (1+2j), ((3, 1), (1, 0)): -1.7}\n\n\nJust print the operator for a nice readable representation:\n\n\n```\nprint(op)\n```\n\n -1.7 [3^ 1] +\n (1+2j) [4^ 3^ 9 1]\n\n\n### `openfermion.QubitOperator`\n\nSame as `FermionOperator`, but the possible actions are 'X', 'Y', and 'Z' instead of 1 and 0.\n\n\n```\nop = of.QubitOperator(((1, 'X'), (2, 'Y'), (3, 'Z')))\nop += of.QubitOperator('X3 Z4', 3.0)\n\nprint(op)\n```\n\n 1.0 [X1 Y2 Z3] +\n 3.0 [X3 Z4]\n\n\n`FermionOperator` and `QubitOperator` actually inherit from the same parent class: `openfermion.SymbolicOperator`.\n\n## The Jordan-Wigner and Bravyi-Kitaev transforms\n\nA fermionic transform maps `FermionOperator`s to `QubitOperator`s in a way that preserves the canonical anticommutation relations. The most basic transforms are the Jordan-Wigner transform (JWT) and Bravyi-Kitaev transform (BKT). Note that the BKT requires the total number of qubits to be predetermined. Whenever a fermionic transform is being applied implicitly, it is the JWT.\n\n\n```\nop = of.FermionOperator('2^ 15')\n\nprint(of.jordan_wigner(op))\nprint()\nprint(of.bravyi_kitaev(op, n_qubits=16))\n```\n\n (0.25+0j) [X2 Z3 Z4 Z5 Z6 Z7 Z8 Z9 Z10 Z11 Z12 Z13 Z14 X15] +\n 0.25j [X2 Z3 Z4 Z5 Z6 Z7 Z8 Z9 Z10 Z11 Z12 Z13 Z14 Y15] +\n -0.25j [Y2 Z3 Z4 Z5 Z6 Z7 Z8 Z9 Z10 Z11 Z12 Z13 Z14 X15] +\n (0.25+0j) [Y2 Z3 Z4 Z5 Z6 Z7 Z8 Z9 Z10 Z11 Z12 Z13 Z14 Y15]\n \n (-0.25+0j) [Z1 X2 X3 X7 Z15] +\n -0.25j [Z1 X2 X3 Y7 Z11 Z13 Z14] +\n 0.25j [Z1 Y2 X3 X7 Z15] +\n (-0.25+0j) [Z1 Y2 X3 Y7 Z11 Z13 Z14]\n\n\n### Exercise\n\nBelow are some examples of how `FermionOperator`s are mapped to `QubitOperator`s by the Jordan-Wigner transform (the notation 'h.c.' stands for 'hermitian conjugate'):\n$$\n\\begin{align*}\n a_p^\\dagger &\\mapsto \\frac12 (X_p - i Y_p) Z_0 \\cdots Z_{p-1}\\\\\n a_p^\\dagger a_p &\\mapsto \\frac12 (I - Z_p)\\\\\n (\\beta a_p^\\dagger a_q + \\text{h.c.}) &\\mapsto \\frac12 [\\text{Re}(\\beta) (X_p ZZ \\cdots ZZ X_q + Y_p ZZ \\cdots ZZ Y_q) + \\text{Im}(\\beta) (Y_p ZZ \\cdots ZZ X_q - X_p ZZ \\cdots ZZ Y_q)]\n\\end{align*}\n$$\nVerify these mappings for $p=2$ and $q=7$. The `openfermion.hermitian_conjugated` function may be useful here.\n\n\n```\na2 = of.FermionOperator('2')\nprint(of.jordan_wigner(a2))\nprint()\n\na2dag = of.FermionOperator('2^')\nprint(of.jordan_wigner(a2dag*a2))\nprint()\n\na7 = of.FermionOperator('7')\na7dag = of.FermionOperator('7^')\nprint(of.jordan_wigner((1+2j)*(a2dag*a7) + (1-2j)*(a7dag*a2)))\n```\n\n 0.5 [Z0 Z1 X2] +\n 0.5j [Z0 Z1 Y2]\n \n (0.5+0j) [] +\n (-0.5+0j) [Z2]\n \n (0.5+0j) [X2 Z3 Z4 Z5 Z6 X7] +\n (-1+0j) [X2 Z3 Z4 Z5 Z6 Y7] +\n (1+0j) [Y2 Z3 Z4 Z5 Z6 X7] +\n (0.5+0j) [Y2 Z3 Z4 Z5 Z6 Y7]\n\n\n### Solution\n\n\n```\na2 = of.FermionOperator('2')\na2dag = of.FermionOperator('2^')\na7 = of.FermionOperator('7')\na7dag = of.FermionOperator('7^')\n\nprint(of.jordan_wigner(a2dag))\nprint()\nprint(of.jordan_wigner(a2dag*a2))\nprint()\n\nop = (2+3j)*a2dag*a7\nop += of.hermitian_conjugated(op)\nprint(of.jordan_wigner(op))\n```\n\n 0.5 [Z0 Z1 X2] +\n -0.5j [Z0 Z1 Y2]\n \n (0.5+0j) [] +\n (-0.5+0j) [Z2]\n \n (1+0j) [X2 Z3 Z4 Z5 Z6 X7] +\n (-1.5+0j) [X2 Z3 Z4 Z5 Z6 Y7] +\n (1.5+0j) [Y2 Z3 Z4 Z5 Z6 X7] +\n (1+0j) [Y2 Z3 Z4 Z5 Z6 Y7]\n\n\n### Exercise\n\nUse the `+` and `*` operators to verify that after applying the JWT to ladder operators, the resulting `QubitOperator`s satisfy\n$$\n\\begin{align}\n a_2 a_7 + a_7 a_2 &= 0 \\\\\n a_2 a_7^\\dagger + a_7^\\dagger a_2 &= 0\\\\\n a_2 a_2^\\dagger + a_2^\\dagger a_2 &= 1\n\\end{align}\n$$\n\n### Solution\n\n\n```\na2_jw = of.jordan_wigner(a2)\na2dag_jw = of.jordan_wigner(a2dag)\na7_jw = of.jordan_wigner(a7)\na7dag_jw = of.jordan_wigner(a7dag)\n\nprint(a2_jw * a7_jw + a7_jw * a2_jw)\nprint(a2_jw * a7dag_jw + a7dag_jw * a2_jw)\nprint(a2_jw * a2dag_jw + a2dag_jw * a2_jw)\n```\n\n 0\n 0\n (1+0j) []\n\n\n## Array data structures\n\n- When `FermionOperator`s have specialized structure we can store coefficients in numpy arrays, enabling fast numerical manipulation.\n- Array data structures can always be converted to `FermionOperator` using `openfermion.get_fermion_operator`.\n\n### InteractionOperator\n\n- Stores the one- and two-body tensors $T_{pq}$ and $V_{pqrs}$ of the molecular Hamiltonian\n\n$$\n\\sum_{pq} T_{pq} a_p^\\dagger a_q + \\sum_{pqrs} V_{pqrs} a_p^\\dagger a_q^\\dagger a_r a_s\n$$\n\n- Default data structure for molecular Hamiltonians\n- Convert from `FermionOperator` using `openfermion.get_interaction_operator`\n\n### DiagonalCoulombHamiltonian\n\n- Stores the one- and two-body coefficient matrices $T_{pq}$ and $V_{pq}$ of a Hamiltonian with a diagonal Coulomb term:\n\n$$\n\\sum_{pq} T_{pq} a_p^\\dagger a_q + \\sum_{pq} V_{pq} a_p^\\dagger a_p a_q^\\dagger a_q\n$$\n\n- Leads to especially efficient algorithms for quantum simulation\n- Convert from `FermionOperator` using `openfermion.get_diagonal_coulomb_hamiltonian`\n\n### QuadraticHamiltonian\n\n- Stores the Hermitian matrix $M_{pq}$ and antisymmetric matrix $\\Delta_{pq}$ describing a general quadratic Hamiltonian\n\n$$\n\\sum_{p, q} M_{pq} a^\\dagger_p a_q + \\frac12 \\sum_{p, q} (\\Delta_{pq} a^\\dagger_p a^\\dagger_q + \\text{h.c.})\n$$\n\n- Routines included for efficient diagonalization (can handle thousands of fermionic modes)\n- Convert from `FermionOperator` using `openfermion.get_quadratic_hamiltonian`\n\n## Generating the Hamiltonian for a molecule\n\nThe cell below demonstrates using one of our electronic structure package plugins, OpenFermion-PySCF, to generate a molecular Hamiltonian for a hydrogen molecule. Note that the Hamiltonian is returned as an `InteractionOperator`. We'll convert it to a `FermionOperator` and print the result.\n\n\n```\n# Set molecule parameters\ngeometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.8))]\nbasis = 'sto-3g'\nmultiplicity = 1\ncharge = 0\n\n# Perform electronic structure calculations and\n# obtain Hamiltonian as an InteractionOperator\nhamiltonian = ofpyscf.generate_molecular_hamiltonian(\n geometry, basis, multiplicity, charge)\n\n# Convert to a FermionOperator\nhamiltonian_ferm_op = of.get_fermion_operator(hamiltonian)\n\nprint(hamiltonian_ferm_op)\n```\n\n 0.66147151365 [] +\n -1.2178260299951058 [0^ 0] +\n 0.3316650744318082 [0^ 0^ 0 0] +\n 0.09231339177803066 [0^ 0^ 2 2] +\n 0.3316650744318082 [0^ 1^ 1 0] +\n 0.09231339177803066 [0^ 1^ 3 2] +\n 0.09231339177803066 [0^ 2^ 0 2] +\n 0.3267206861819477 [0^ 2^ 2 0] +\n 0.09231339177803066 [0^ 3^ 1 2] +\n 0.3267206861819477 [0^ 3^ 3 0] +\n 0.3316650744318082 [1^ 0^ 0 1] +\n 0.09231339177803066 [1^ 0^ 2 3] +\n -1.2178260299951058 [1^ 1] +\n 0.3316650744318082 [1^ 1^ 1 1] +\n 0.09231339177803066 [1^ 1^ 3 3] +\n 0.09231339177803066 [1^ 2^ 0 3] +\n 0.3267206861819477 [1^ 2^ 2 1] +\n 0.09231339177803066 [1^ 3^ 1 3] +\n 0.3267206861819477 [1^ 3^ 3 1] +\n 0.32672068618194783 [2^ 0^ 0 2] +\n 0.09231339177803066 [2^ 0^ 2 0] +\n 0.32672068618194783 [2^ 1^ 1 2] +\n 0.09231339177803066 [2^ 1^ 3 0] +\n -0.5096378744364826 [2^ 2] +\n 0.09231339177803066 [2^ 2^ 0 0] +\n 0.34339576784573445 [2^ 2^ 2 2] +\n 0.09231339177803066 [2^ 3^ 1 0] +\n 0.34339576784573445 [2^ 3^ 3 2] +\n 0.32672068618194783 [3^ 0^ 0 3] +\n 0.09231339177803066 [3^ 0^ 2 1] +\n 0.32672068618194783 [3^ 1^ 1 3] +\n 0.09231339177803066 [3^ 1^ 3 1] +\n 0.09231339177803066 [3^ 2^ 0 1] +\n 0.34339576784573445 [3^ 2^ 2 3] +\n -0.5096378744364826 [3^ 3] +\n 0.09231339177803066 [3^ 3^ 1 1] +\n 0.34339576784573445 [3^ 3^ 3 3]\n\n\nLet's calculate the ground energy (lowest eigenvalue) of the Hamiltonian. First, we'll map the `FermionOperator` to a `QubitOperator` using the JWT. Then, we'll convert the `QubitOperator` to a SciPy sparse matrix and get its lowest eigenvalue.\n\n\n```\n# Map to QubitOperator using the JWT\nhamiltonian_jw = of.jordan_wigner(hamiltonian_ferm_op)\n\n# Convert to Scipy sparse matrix\nhamiltonian_jw_sparse = of.get_sparse_operator(hamiltonian_jw)\n\n# Compute ground energy\neigs, _ = linalg.eigsh(hamiltonian_jw_sparse, k=1, which='SA')\nground_energy = eigs[0]\n\nprint('Ground_energy: {}'.format(ground_energy))\nprint('JWT transformed Hamiltonian:')\nprint(hamiltonian_jw)\n```\n\n Ground_energy: -1.134147666677095\n JWT transformed Hamiltonian:\n (-0.16733398905695201+0j) [] +\n (-0.04615669588901533+0j) [X0 X1 Y2 Y3] +\n (0.04615669588901533+0j) [X0 Y1 Y2 X3] +\n (0.04615669588901533+0j) [Y0 X1 X2 Y3] +\n (-0.04615669588901533+0j) [Y0 Y1 X2 X3] +\n (0.16251648748871642+0j) [Z0] +\n (0.1658325372159041+0j) [Z0 Z1] +\n (0.11720364720195856+0j) [Z0 Z2] +\n (0.1633603430909739+0j) [Z0 Z3] +\n (0.16251648748871636+0j) [Z1] +\n (0.1633603430909739+0j) [Z1 Z2] +\n (0.11720364720195856+0j) [Z1 Z3] +\n (-0.1974429369975584+0j) [Z2] +\n (0.17169788392286722+0j) [Z2 Z3] +\n (-0.19744293699755838+0j) [Z3]\n\n\n### Exercise\nCompute the ground energy of the same Hamiltonian, but via the Bravyi-Kitaev transform. Verify that you get the same value.\n\n\n```\n# Map to QubitOperator using the JWT\nhamiltonian_bk = of.bravyi_kitaev(hamiltonian_ferm_op)\n\n# Convert to Scipy sparse matrix\nhamiltonian_bk_sparse = of.get_sparse_operator(hamiltonian_bk)\n\n# Compute ground energy\neigs, _ = linalg.eigsh(hamiltonian_bk_sparse, k=1, which='SA')\nground_energy = eigs[0]\n\nprint('Ground_energy: {}'.format(ground_energy))\nprint('BK transformed Hamiltonian:')\nprint(hamiltonian_bk)\n```\n\n Ground_energy: -1.1341476666770918\n BK transformed Hamiltonian:\n (-0.16733398905695201+0j) [] +\n (0.04615669588901533+0j) [X0 Z1 X2] +\n (0.04615669588901533+0j) [X0 Z1 X2 Z3] +\n (0.04615669588901533+0j) [Y0 Z1 Y2] +\n (0.04615669588901533+0j) [Y0 Z1 Y2 Z3] +\n (0.16251648748871642+0j) [Z0] +\n (0.16251648748871636+0j) [Z0 Z1] +\n (0.1633603430909739+0j) [Z0 Z1 Z2] +\n (0.1633603430909739+0j) [Z0 Z1 Z2 Z3] +\n (0.11720364720195856+0j) [Z0 Z2] +\n (0.11720364720195856+0j) [Z0 Z2 Z3] +\n (0.1658325372159041+0j) [Z1] +\n (-0.19744293699755838+0j) [Z1 Z2 Z3] +\n (0.17169788392286722+0j) [Z1 Z3] +\n (-0.1974429369975584+0j) [Z2]\n\n\n### Solution\n\n\n```\n# Map to QubitOperator using the BKT\nhamiltonian_bk = of.bravyi_kitaev(hamiltonian_ferm_op)\n\n# Convert to Scipy sparse matrix\nhamiltonian_bk_sparse = of.get_sparse_operator(hamiltonian_bk)\n\n# Compute ground state energy\neigs, _ = linalg.eigsh(hamiltonian_bk_sparse, k=1, which='SA')\nground_energy = eigs[0]\n\nprint('Ground_energy: {}'.format(ground_energy))\nprint('BKT transformed Hamiltonian:')\nprint(hamiltonian_bk)\n```\n\n Ground_energy: -1.134147666677097\n BKT transformed Hamiltonian:\n (-0.16733398905695201+0j) [] +\n (0.04615669588901533+0j) [X0 Z1 X2] +\n (0.04615669588901533+0j) [X0 Z1 X2 Z3] +\n (0.04615669588901533+0j) [Y0 Z1 Y2] +\n (0.04615669588901533+0j) [Y0 Z1 Y2 Z3] +\n (0.16251648748871642+0j) [Z0] +\n (0.16251648748871636+0j) [Z0 Z1] +\n (0.1633603430909739+0j) [Z0 Z1 Z2] +\n (0.1633603430909739+0j) [Z0 Z1 Z2 Z3] +\n (0.11720364720195856+0j) [Z0 Z2] +\n (0.11720364720195856+0j) [Z0 Z2 Z3] +\n (0.1658325372159041+0j) [Z1] +\n (-0.19744293699755838+0j) [Z1 Z2 Z3] +\n (0.17169788392286722+0j) [Z1 Z3] +\n (-0.1974429369975584+0j) [Z2]\n\n\n### Exercise\n\n- The BCS mean-field d-wave model of superconductivity has the Hamiltonian\n\n$$\nH = - t \\sum_{\\langle i,j \\rangle} \\sum_\\sigma (a^\\dagger_{i, \\sigma} a_{j, \\sigma} + a^\\dagger_{j, \\sigma} a_{i, \\sigma}) - \\sum_{\\langle i,j \\rangle} \\Delta_{ij} (a^\\dagger_{i, \\uparrow} a^\\dagger_{j, \\downarrow} - a^\\dagger_{i, \\downarrow} a^\\dagger_{j, \\uparrow} + a_{j, \\downarrow} a_{i, \\uparrow} - a_{j, \\uparrow} a_{i, \\downarrow})\n$$\n\nUse the `mean_field_dwave` function to generate an instance of this model with dimensions 10x10.\n - Convert the Hamiltonian to a `QubitOperator` with the JWT. What is the length of the longest Pauli string that appears?\n - Convert the Hamiltonian to a `QubitOperator` with the BKT. What is the length of the longest Pauli string that appears?\n - Convert the Hamiltonian to a `QuadraticHamiltonian`. Get its ground energy using the `ground_energy` method of `QuadraticHamiltonian`. What would happen if you tried to compute the ground energy by converting to a sparse matrix?\n\n## Hamiltonian simulation with Trotter formulas\n\n- Goal: apply $\\exp(-i H t)$ where $H = \\sum_j H_j$\n- Use an approximation such as $\\exp(-i H t) \\approx (\\prod_{j=1} \\exp(-i H_j t/r))^r$\n- Exposed via the `openfermion.simulate_trotter` function\n- Currently implemented algorithms are from [arXiv:1706.00023](https://arxiv.org/pdf/1706.00023.pdf), [arXiv:1711.04789](https://arxiv.org/pdf/1711.04789.pdf), and [arXiv:1808.02625](https://arxiv.org/pdf/1808.02625.pdf), and are based on the JWT\n- Currently supported Hamiltonian types: `DiagonalCoulombHamiltonian` and `InteractionOperator`\n\nAs a demonstration, we'll simulate time evolution under the hydrogen molecule Hamiltonian we generated earlier.\n\nFirst, let's create a random initial state and apply the exact time evolution by matrix exponentiation:\n\n$$\n\\lvert \\psi \\rangle \\mapsto \\exp(-i H t) \\lvert \\psi \\rangle\n$$\n\n\n```\n# Create a random initial state\nn_qubits = of.count_qubits(hamiltonian)\ninitial_state = of.haar_random_vector(2**n_qubits, seed=7)\n\n# Set evolution time\ntime = 1.0\n\n# Apply exp(-i H t) to the state\nexact_state = linalg.expm_multiply(-1j*hamiltonian_jw_sparse*time, initial_state)\n```\n\nNow, let's create a circuit to perform the evolution and compare the fidelity of the resulting state with the one from exact evolution. The fidelity can be increased by increasing the number of Trotter steps. Note that the Hamiltonian input to `openfermion.simulate_trotter` should be an `InteractionOperator`, not a `FermionOperator`.\n\n\n```\n# Initialize qubits\nqubits = cirq.LineQubit.range(n_qubits)\n\n# Create circuit\ncircuit = cirq.Circuit(\n of.simulate_trotter(\n qubits, hamiltonian, time,\n n_steps=10,\n order=0,\n algorithm=of.LOW_RANK)\n)\n\n# Apply the circuit to the initial state\nresult = circuit.final_state_vector(initial_state=initial_state, ignore_terminal_measurements=False, dtype=np.complex64)\n\n# Compute the fidelity with the final state from exact evolution\nfidelity = abs(np.dot(exact_state, result.conj()))**2\n\nprint(fidelity)\n```\n\n 0.9999820449924582\n\n\n\n```\nprint(circuit.to_text_diagram(transpose=True))\n```\n\n 0 1 2 3\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.052π) Rz(0.052π) Rz(0.03π) Rz(0.03π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.022 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.021\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.01π) @──────────────────@^-0.021 Rz(-0.011π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.01π) Rz(-0.011π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.006\n │ │ │ │\n @─────────────@^-0.006 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(0)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(0) Rz(π) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^0 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^0\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.03π) Rz(0) Rz(0) Rz(0.052π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.03π) Rz(0.052π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.022\n │ │ │ │\n @─────────────@^-0.021 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.011π) @──────────────────@^-0.021 Rz(-0.01π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.011π) Rz(-0.01π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.006 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.006\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(π) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^0\n │ │ │ │\n @─────────────@^0 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.052π) Rz(0) Rz(0) Rz(0.03π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.052π) Rz(0.03π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.022 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.021\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.01π) @──────────────────@^-0.021 Rz(-0.011π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.01π) Rz(-0.011π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.006\n │ │ │ │\n @─────────────@^-0.006 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(0)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(0) Rz(π) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^0 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^0\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.03π) Rz(0) Rz(0) Rz(0.052π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.03π) Rz(0.052π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.022\n │ │ │ │\n @─────────────@^-0.021 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.011π) @──────────────────@^-0.021 Rz(-0.01π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.011π) Rz(-0.01π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.006 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.006\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(π) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^0\n │ │ │ │\n @─────────────@^0 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.052π) Rz(0) Rz(0) Rz(0.03π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.052π) Rz(0.03π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.022 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.021\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.01π) @──────────────────@^-0.021 Rz(-0.011π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.01π) Rz(-0.011π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.006\n │ │ │ │\n @─────────────@^-0.006 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(0)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(0) Rz(π) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^0 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^0\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.03π) Rz(0) Rz(0) Rz(0.052π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.03π) Rz(0.052π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.022\n │ │ │ │\n @─────────────@^-0.021 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.011π) @──────────────────@^-0.021 Rz(-0.01π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.011π) Rz(-0.01π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.006 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.006\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(π) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^0\n │ │ │ │\n @─────────────@^0 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.052π) Rz(0) Rz(0) Rz(0.03π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.052π) Rz(0.03π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.022 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.021\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.01π) @──────────────────@^-0.021 Rz(-0.011π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.01π) Rz(-0.011π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.006\n │ │ │ │\n @─────────────@^-0.006 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(0)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(0) Rz(π) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^0 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^0\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.03π) Rz(0) Rz(0) Rz(0.052π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.03π) Rz(0.052π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.022\n │ │ │ │\n @─────────────@^-0.021 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.011π) @──────────────────@^-0.021 Rz(-0.01π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.011π) Rz(-0.01π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.006 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.006\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(π) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^0\n │ │ │ │\n @─────────────@^0 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.052π) Rz(0) Rz(0) Rz(0.03π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.052π) Rz(0.03π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.022 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.021\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.01π) @──────────────────@^-0.021 Rz(-0.011π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.01π) Rz(-0.011π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.006\n │ │ │ │\n @─────────────@^-0.006 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(0)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(0) Rz(π) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^0 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^0\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n Rz(0.03π) Rz(0) Rz(0) Rz(0.052π)\n │ │ │ │\n Rz(0) Rz(0) Rz(0) Rz(0)\n │ │ │ │\n │ Rz(0.03π) Rz(0.052π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-1\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^-1 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^-0.022\n │ │ │ │\n @─────────────@^-0.021 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^-0.021 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^-0.021 @────────────────@^-0.021\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.011π) @──────────────────@^-0.021 Rz(-0.01π)\n │ │ │ │\n Rz(π) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.011π) Rz(-0.01π) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 Z^0\n │ │ │ │\n @─────────────@^-0.006 Z^0 │\n │ │ │ │\n ×─────────────× @────────────────@^-0.006\n │ │ │ │\n │ │ ×────────────────×\n │ │ │ │\n │ @──────────────────@^0.006 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0.006 @────────────────@^0.006\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(-0.003π) @──────────────────@^0.006 Rz(-0.003π)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(π)\n │ │ │ │\n │ Rz(-0.003π) Rz(-0.003π) │\n │ │ │ │\n │ Rz(π) Rz(0) │\n │ │ │ │\n │ PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 PhISwap(0.25)────PhISwap(0.25)^-0.5\n │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.5 Z^0 │\n │ │ │ │\n Z^0 PhISwap(0.25)──────PhISwap(0.25)^-1 │\n │ │ │ │\n │ Z^0 @────────────────@^0\n │ │ │ │\n @─────────────@^0 ×────────────────×\n │ │ │ │\n ×─────────────× │ │\n │ │ │ │\n │ @──────────────────@^0 │\n │ │ │ │\n │ ×──────────────────× │\n │ │ │ │\n @─────────────@^0 @────────────────@^0\n │ │ │ │\n ×─────────────× ×────────────────×\n │ │ │ │\n Rz(0) @──────────────────@^0 Rz(0)\n │ │ │ │\n Rz(0) ×──────────────────× Rz(0)\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n │ Rz(0) Rz(0) │\n │ │ │ │\n\n\n## Bogoliubov transformation\n\n- Single-particle orbital basis change\n- In the particle-conserving case, takes the form\n$$\nU a_p^\\dagger U^\\dagger = b_p^\\dagger, \\quad b_p^\\dagger = \\sum_{q} u_{pq} a_q^\\dagger\n$$\nand $u$ is unitary.\n- Can be used to diagonalize any quadratic Hamiltonian:\n$$\n\\sum_{p, q} T_{pq} a_p^\\dagger a_q \\mapsto \\sum_{j} \\varepsilon_j b_j^\\dagger b_j + \\text{constant}\n$$\n- Implementation from [arXiv:1711.05395](https://arxiv.org/pdf/1711.05395.pdf); uses linear depth and linear connectivity\n\nAs an example, we'll prepare the ground state of a random particle-conserving quadratic Hamiltonian.\n\n\n```\nn_qubits = 5\nquad_ham = of.random_quadratic_hamiltonian(\n n_qubits, conserves_particle_number=True, seed=7)\n\nprint(of.get_fermion_operator(quad_ham))\n```\n\n 1.690525703800356 [] +\n (0.5315776978980016+0j) [0^ 0] +\n (-1.347208023348913+2.7004721387490935j) [0^ 1] +\n (-0.28362365442898696-1.8784499457335426j) [0^ 2] +\n (0.12594647819298657-1.3106154125325498j) [0^ 3] +\n (-0.3880303291443195-1.1751249212322041j) [0^ 4] +\n (-1.347208023348913-2.7004721387490935j) [1^ 0] +\n (2.5012533818678193+0j) [1^ 1] +\n (0.3391421007279024-3.8305756810505094j) [1^ 2] +\n (-0.3509690502067961+0.090677856754656j) [1^ 3] +\n (1.8575239595653907-1.4736314761076197j) [1^ 4] +\n (-0.28362365442898696+1.8784499457335426j) [2^ 0] +\n (0.3391421007279024+3.8305756810505094j) [2^ 1] +\n (-0.019560786804260433+0j) [2^ 2] +\n (-2.979765944360631+2.5490724453105917j) [2^ 3] +\n (0.5091942820312417+0.344618218148502j) [2^ 4] +\n (0.12594647819298657+1.3106154125325498j) [3^ 0] +\n (-0.3509690502067961-0.090677856754656j) [3^ 1] +\n (-2.979765944360631-2.5490724453105917j) [3^ 2] +\n (3.767336752913784+0j) [3^ 3] +\n (-1.2963431636902167-1.5288970105744286j) [3^ 4] +\n (-0.3880303291443195+1.1751249212322041j) [4^ 0] +\n (1.8575239595653907+1.4736314761076197j) [4^ 1] +\n (0.5091942820312417-0.344618218148502j) [4^ 2] +\n (-1.2963431636902167+1.5288970105744286j) [4^ 3] +\n (-0.3445183403145406+0j) [4^ 4]\n\n\nNow we construct a circuit which maps computational basis states to eigenstates of the Hamiltonian.\n\n\n```\n_, basis_change_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform()\n\nqubits = cirq.LineQubit.range(n_qubits)\ncircuit = cirq.Circuit(\n of.bogoliubov_transform(\n qubits,\n basis_change_matrix))\n\nprint(circuit.to_text_diagram(transpose=True))\n```\n\n 0 1 2 3 4\n │ │ │ │ │\n Rz(0) Rz(0) Rz(π) Rz(-π) Rz(0)\n │ │ │ │ │\n │ │ │ PhISwap(0.25)─────────PhISwap(0.25)^0.073\n │ │ │ │ │\n │ │ PhISwap(0.25)────────PhISwap(0.25)^(5/11) Z^(-7/9)\n │ │ │ │ │\n │ PhISwap(0.25)───────PhISwap(0.25)^0.814 Z^-0.508 │\n │ │ │ │ │\n PhISwap(0.25)─PhISwap(0.25)^0.703 Z^-0.304 PhISwap(0.25)─────────PhISwap(0.25)^0.381\n │ │ │ │ │\n │ Z^-0.767 PhISwap(0.25)────────PhISwap(0.25)^(13/16) Z^0.401\n │ │ │ │ │\n │ PhISwap(0.25)───────PhISwap(0.25)^(7/11) Z^(-13/14) │\n │ │ │ │ │\n │ │ Z^0.393 PhISwap(0.25)─────────PhISwap(0.25)^0.481\n │ │ │ │ │\n │ │ PhISwap(0.25)────────PhISwap(0.25)^0.422 Z^-0.738\n │ │ │ │ │\n │ │ │ Z^-0.824 │\n │ │ │ │ │\n │ │ │ PhISwap(0.25)─────────PhISwap(0.25)^0.506\n │ │ │ │ │\n │ │ │ │ Z^(5/7)\n │ │ │ │ │\n\n\nIn the rotated basis, the quadratic Hamiltonian takes the form\n$$\nH = \\sum_j \\varepsilon_j b_j^\\dagger b_j + \\text{constant}\n$$\nWe can get the $\\varepsilon_j$ and the constant using the `orbital_energies` method of `QuadraticHamiltonian`.\n\n\n```\norbital_energies, constant = quad_ham.orbital_energies()\n\nprint(orbital_energies)\nprint(constant)\n```\n\n [-6.25377614 -1.2291963 0.71202361 5.0062515 8.20078604]\n 1.690525703800356\n\n\nThe ground state of the Hamiltonian is prepared by filling in the orbitals with negative energy.\n\n\n```\n# Apply the circuit with initial state having the first two modes occupied.\nresult = circuit.final_state_vector(initial_state=0b11000, ignore_terminal_measurements=False, dtype=np.complex64)\n\n# Compute the expectation value of the final state with the Hamiltonian\nquad_ham_sparse = of.get_sparse_operator(quad_ham)\nprint(of.expectation(quad_ham_sparse, result))\n\n# Print out the ground state energy; it should match\nprint(quad_ham.ground_energy())\n```\n\n (-5.792446738060052+1.1102230246251565e-16j)\n -5.792446738060049\n\n\nRecall that the Jordan-Wigner transform of $b_j^\\dagger b_j$ is $\\frac12(I-Z)$. Therefore, $\\exp(-i \\varepsilon_j b_j^\\dagger b_j)$ is equivalent to a single-qubit Z rotation under the JWT. Since the operators $b_j^\\dagger b_j$ commute, we have\n$$\n\\exp(-i H t) = \\exp(-i \\sum_j \\varepsilon_j b_j^\\dagger b_j t)\n= \\prod_j \\exp(-i \\varepsilon_j b_j^\\dagger b_j t)\n$$\nThis gives a method for simulating time evolution under a quadratic Hamiltonian:\n- Use a Bogoliubov transformation to change to the basis in which the Hamiltonian is diagonal (Note: this transformation might be the inverse of what you expect. In that case, use `cirq.inverse`)\n- Apply single-qubit Z-rotations with angles proportional to the orbital energies\n- Undo the basis change\n\nThe code cell below creates a random initial state and applies time evolution by direct matrix exponentiation.\n\n\n```\n# Create a random initial state\ninitial_state = of.haar_random_vector(2**n_qubits)\n\n# Set evolution time\ntime = 1.0\n\n# Apply exp(-i H t) to the state\nfinal_state = linalg.expm_multiply(-1j*quad_ham_sparse*time, initial_state)\n```\n\n### Exercise\n\nFill in the code cell below to construct a circuit which applies $\\exp(-i H t)$ using the method described above\n\n\n```\n# Initialize qubits\nqubits = cirq.LineQubit.range(n_qubits)\n\n# Write code below to create the circuit\n# You should define the `circuit` variable here\n# ---------------------------------------------\n\n\n# ---------------------------------------------\n\n# Apply the circuit to the initial state\nresult = circuit.final_state_vector(initial_state=initial_state, ignore_terminal_measurements=False, dtype=np.complex64)\n\n# Compute the fidelity with the correct final state\nfidelity = abs(np.dot(final_state, result.conj()))**2\n\n# Print fidelity; it should be 1\nprint(fidelity)\n```\n\n 0.08926042490120051\n\n\n### Solution\n\n\n```\n# Initialize qubits\nqubits = cirq.LineQubit.range(n_qubits)\n\n# Write code below to create the circuit\n# You should define the `circuit` variable here\n# ---------------------------------------------\ndef exponentiate_quad_ham(qubits, quad_ham):\n _, basis_change_matrix, _ = quad_ham.diagonalizing_bogoliubov_transform()\n orbital_energies, _ = quad_ham.orbital_energies()\n \n yield cirq.inverse(\n of.bogoliubov_transform(qubits, basis_change_matrix))\n for i in range(len(qubits)):\n yield cirq.rz(rads=-orbital_energies[i]).on(qubits[i])\n yield of.bogoliubov_transform(qubits, basis_change_matrix)\n\ncircuit = cirq.Circuit(exponentiate_quad_ham(qubits, quad_ham))\n# ---------------------------------------------\n\n# Apply the circuit to the initial state\nresult = circuit.final_state_vector(initial_state=initial_state, ignore_terminal_measurements=False, dtype=np.complex64)\n\n# Compute the fidelity with the correct final state\nfidelity = abs(np.dot(final_state, result.conj()))**2\n\n# Print fidelity; it should be 1\nprint(fidelity)\n```\n\n 0.999999999999994\n\n", "meta": {"hexsha": "fe6607b0d69e1c77fac035562183868e4a113e58", "size": 104262, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/educators/chemistry.ipynb", "max_stars_repo_name": "alexandrebouayad/Cirq", "max_stars_repo_head_hexsha": "4ba730b17b6af6265ee6458eb40172b847bd5684", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-02-05T22:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T22:17:39.000Z", "max_issues_repo_path": "docs/tutorials/educators/chemistry.ipynb", "max_issues_repo_name": "pavoljuhas/Cirq", "max_issues_repo_head_hexsha": "b6d6577be61d216ce2f29f8c64ae5879cf3087d5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/tutorials/educators/chemistry.ipynb", "max_forks_repo_name": "pavoljuhas/Cirq", "max_forks_repo_head_hexsha": "b6d6577be61d216ce2f29f8c64ae5879cf3087d5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2975133215, "max_line_length": 385, "alphanum_fraction": 0.2749515643, "converted": true, "num_tokens": 23377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.342277142545966}} {"text": "# Temperature Profile\n\n\n```python\n#imports libs and data\n%matplotlib inline\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport numpy as np\nimport pickle, json\n\nimport LPPview.Classes.LPPic_fields as fl\nimport LPPview.Classes.LPPic as LP\nimport LPPview.Classes.LPPic_newwalls as nw\nfrom functions import (simpleplot, ne_Bolz, Te_eff_calcl, phi_drop,\n sigma_maxw_unsat,\n sigma_maxw_sat,\n newSigma_maxw,)\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nqe_v = 1.6021766E-19\nme_v = 9.109E-31 \nmi_v = 219.6E-27\neps0_v = 8.854187817e-12\n\nsavepath = \"../images/\"\n\nsigma_0 = 0.5\nsigma_max= 2.9\n\nPaper_style = json.load(open(\"Paperstyle.json\",'r'))\nmpl.style.use(Paper_style)\n```\n\n\n```python\n#folders = [\"131_eps50\",\n# \"132_eps45\",\n# #\"133_eps25\",\n# \"134_eps10\",\n# \"135_eps200\",\n# \"136_LongX\",\n# ]\nfolders = [\"143_eps200\"]\n#root = \"/run/media/tavant/Data3/\"\nroot = \"/home/tavant/Data/R-theta/\"\n\npaths = [root + fol +\"/\" for fol in folders]\n```\n\n\n```python\ndef returnTemean(run, start = 0.5):\n \n tmax = run._nT\n tmin = int(start*tmax)\n Nt = tmax - tmin + 1\n Temean = np.zeros((run._xmax+1,run._ymax+1))\n\n for t in np.arange(tmin,tmax):\n print(f\"\\r {t} over {tmax} time step\",end = \"\")\n Temean += run.return_fromkey(t,'Eke(1)') + run.return_fromkey(t,'Eke(2)') + run.return_fromkey(t,'Eke(3)')\n \n Temean *= 2/3\n \n return Temean / Nt\n\ndef returnVmean(run, start = 0.5):\n \n tmax = run._nT\n tmin = int(start*tmax)\n Nt = tmax - tmin + 1\n nmean = np.zeros((run._xmax+1,run._ymax+1))\n J1mean = np.zeros((run._xmax+1,run._ymax+1))\n J2mean = np.zeros((run._xmax+1,run._ymax+1))\n J3mean = np.zeros((run._xmax+1,run._ymax+1))\n \n for t in np.arange(tmin,tmax):\n print(f\"\\r {t} over {tmax} time step\",end = \"\")\n \n ntemp = run.return_fromkey(t,'Nume') \n nmean += ntemp\n J1mean += run.return_fromkey(t,'Je(1)') / ntemp\n J2mean += run.return_fromkey(t,'Je(2)') / ntemp\n J3mean += run.return_fromkey(t,'Je(3)') / ntemp\n \n \n return nmean/Nt, -J1mean/qe_v/Nt, -J2mean/qe_v/Nt, -J3mean/qe_v/Nt\n```\n\n## Load the data\n\n\n```python\n#Load the Data\nfilename = 'tabgrid_data.dat'\n\nif True:\n data = pickle.load(open(filename,\"rb\"))\nelse:\n\n data = pickle.load(open(filename,\"rb\"))\n for p in paths:\n run = fl.field(p)\n n = p.split(\"/\")[-2]\n print(n)\n print(\"get Te\")\n Temean = np.zeros((run._xmax+1,run._ymax+1))\n try:\n Temean = returnTemean(run, 0.7)\n except KeyError:\n Temean = np.zeros((run._xmax+1,run._ymax+1))\n\n print(\"Get ve and ne\")\n nmean, J1mean, J2mean, J3mean = returnVmean(run, 0.7)\n\n data[n] = {\"Te\":Temean,\n \"n\":nmean,\n \"v1\":J1mean,\n \"v2\":J2mean,\n \"v3\":J3mean,\n }\n pickle.dump(data,open(filename,\"wb\"))\n\n```\n\n\n```python\n#plot\nfig, axarr = plt.subplots(2,2,figsize = (10,10))\n\naxarr = axarr.flatten()\n\nfor k,v in data.items():\n #print(k)\n for ax, st in zip(axarr, [\"n\",\"v1\",\"v2\",\"v3\"]):\n tab = (v[st].mean(axis = 0))\n ax.plot(tab, label = k)\n \nfor ax in axarr.flatten():\n ax.legend()\n #ax.set_yscale('log')\n ax.grid(True,\"grey\")\n\n\naxarr[0].set_title(\"Electron density\")\naxarr[1].set_title(\"Azymuthal velocity\")\naxarr[2].set_title(\"Radial Velocity\")\naxarr[3].set_title(\"Axial Velocity\")\n\nfig.savefig(\"ne_ve_profiles.png\")\n\n```\n\n\n```python\n\n\nfig2, ax5 = plt.subplots(1,1,figsize = (5,3.5))\n\nRtab = np.linspace(0,2,1001)\nstyles = [\"-\",\"--\",\"-.\",\":\"]\ncompter = 0\nfor k,v in data.items():\n tab = v[\"Te\"].mean(axis = 0)\n tab *= 1\n if k==\"136_LongX\":\n tab *=60/80\n if tab.mean() > 0:\n ax5.plot(Rtab,tab, label = k, linestyle = styles[compter%4])\n compter += 1\n\nax5.set_xlim(0,2)\nax5.set_ylim(ymin=0)\n\ntext_size = 9.5\nkwargs = {\"size\":text_size, \"backgroundcolor\":\"w\" }\n\nax5.text(0.25,60*1,'no SEE', **kwargs)\nax5.text(1.15,55*1,r'$\\epsilon^* = 200 \\/eV$', **kwargs)\nax5.text(0.5,45*1,r'$\\epsilon^* = 50\\/ eV$',**kwargs)\nax5.text(1.4,30*1,r'$\\epsilon^* = 10 \\/eV$', **kwargs)\n\n#ax5.legend()\nax5.grid(True,\"grey\")\nax5.set_xlabel(r\"Radial position $x \\/[cm]$\")\nax5.set_ylabel(r\"Electron Temperature T$_e \\/[eV]$\")\n\nfig2.savefig(\"/home/tavant/these/manuscript/src/Chapitre3/figure/Te_profiles.pdf\")\n\n```\n\n\n```python\n#plot\nfig, ax = plt.subplots(1,figsize = (5,5))\n\nfor k,v in data.items():\n tab = (v[\"v1\"]**2 + v[\"v2\"]**2 + v[\"v3\"]**2).mean(axis = 0)\n tab *= me_v/(2*qe_v)\n ax.plot(tab,\"--\", label = k+\" Kinetic\")\n \n tab = v[\"Te\"].mean(axis = 0)\n if tab.mean() > 0:\n ax.plot(tab, label = k+\" Te\")\n \n\nax.legend()\n\nax.set_title(\"Electron energy\")\n#ax.set_yscale(\"log\")\nax.set_ylim(0.1,30)\nax.set_xlim(0,100);\n```\n\n\n```python\n# plot Te\nfig, ax = plt.subplots(1,figsize = (5,5))\n\nfor k,v in data.items():\n tab = (v[\"v1\"]**2 + v[\"v2\"]**2 + v[\"v3\"]**2).mean(axis = 0)\n tab *= me_v/(2*qe_v)\n tab += v[\"Te\"].mean(axis = 0)\n if v[\"Te\"].mean() >0:\n ax.plot(tab, label = k+\" full Eke\")\n \n tab = v[\"Te\"].mean(axis = 0)\n if tab.mean() > 0:\n ax.plot(tab,'--', label = k+\" Te\")\n \n\nax.legend()\n\nax.set_title(\"Electron total energy\")\n#ax.set_yscale(\"log\")\n#ax.set_ylim(0.1,30)\nax.set_xlim(0,1000)\n```\n\n\n```python\nNcels = 3\n\neps_v = np.array([fl.field(p).inputobject.parameters[\"epsilon_star\"] for p in paths])\neps_v = np.array([50,45,10,200,400,200])\nTe_w = np.array([v[\"Te\"][:,0:Ncels].mean() for k,v in data.items()])\nprint(Te_w)\nEke_wpe = np.array([ (v[\"v2\"][:,0:Ncels]**2).mean()*me_v/qe_v for k,v in data.items()])\nEke_wpa = np.array([(v[\"v3\"][:,0:Ncels]**2 + v[\"v1\"][:,0:Ncels]**2).mean()*me_v/qe_v for k,v in data.items()])\n\nVe_x = np.array([(v[\"v1\"][:,0:Ncels].mean()) for k,v in data.items()])\nVe_y = np.array([v[\"v2\"][:,0:Ncels].mean() for k,v in data.items()])\nVe_z = np.array([v[\"v3\"][:,0:Ncels].mean() for k,v in data.items()])\n\nmask = (Te_w > 0)\nVe_x, Ve_y, Ve_z = (Ve_x[mask], Ve_y[mask], Ve_z[mask])\neps_v, Te_w, Eke_wpe, Eke_wpa = (eps_v[mask], Te_w[mask] , Eke_wpe[mask], Eke_wpa[mask])\n\n\nplt.scatter(eps_v, Te_w , label = \"wall temperature\")\nplt.scatter(eps_v, Eke_wpe , label = \"parralelle energy\")\nplt.scatter(eps_v, Eke_wpa , label = \"Radial energy\")\n#plt.scatter(eps_v, Te_eff_calcl())\n\nplt.legend()\n```\n\n# Symbolic integration\nFor a 3D Maxwellian\n\n\n```python\n# Formal calculus\nimport sympy as sym \nfrom sympy import oo, pi\n\nsym.init_printing() \nTe2 = sym.Symbol('2T_e' , positive=True, nonzero = True)\nTe = sym.Symbol('T_e' , positive=True, nonzero = True)\n\nme = sym.Symbol('m_e', positive=True)\nne = sym.Symbol('n_e', positive=True)\n\nfrom sympy.physics.vector import ReferenceFrame\n\nN = ReferenceFrame('N')\nvx = sym.Symbol(\"v_x\")\nvy = sym.Symbol(\"v_y\")\nvz = sym.Symbol(\"v_z\")\n\nv3 = vx*N.x + vy*N.y + vz*N.z\nvdx = sym.Symbol(\"v_{dx}\", positive = True)\nvdy = sym.Symbol(\"v_{dy}\", positive = True)\nvdz = sym.Symbol(\"v_{dz}\", positive = True)\nvd3 = vdx*N.x + vdy*N.y + vdz*N.z\n\nMaxw3 = ne* sym.sqrt(me/(Te*2*pi))**3 * sym.exp( - (v3-vd3).magnitude()**2* me/(Te*2))\n\ndef integ(expr, var , binf = - oo, bsup = oo ):\n \"\"\"Integrate any expression with respect to a variable var between 2 borns\"\"\"\n \n return sym.integrate(expr, (var,binf,bsup))\n\ndef integ3(exp,binfy = -oo ,bsupy = oo):\n \n i1 = integ(exp, var = vx, binf = -oo, bsup = oo ).simplify()\n i2 = integ(i1, var = vz, binf = -oo, bsup = oo ).simplify()\n i3 = integ(i2, var = vy, binf = binfy, bsup = bsupy )\n return i3\n\nsigma_0, epstar = sym.Rational(1,2), sym.Symbol(\"\\epsilon^*\")\n\ndef sig_lin(e):\n s = sigma_0 + (1 - sigma_0)*e/epstar\n return s\n\n```\n\n\n```python\n# Thermal flux\nGamma_e = integ3(vy*Maxw3, 0, oo)\n```\n\n\n```python\n# SEE Rate\nsigGamma_e = integ3(vy*sig_lin(v3.magnitude()**2*me/2)*Maxw3, 0, oo)\n\nrate = sigGamma_e.simplify()/Gamma_e\nrate = rate.simplify()\nrate\n```\n\n\n```python\n# Substitution\ndef eval_val(eps, Te_v,vx_v,vy_v,vz_v):\n \n SubsDict = {me : me_v,\n epstar : eps,\n vdy: vy_v,\n vdx: vx_v,\n vdz: vz_v,\n Te: Te_v\n }\n\n s = rate.subs(SubsDict).evalf().simplify()\n\n return s\n\n\n```\n\n\n```python\n# Evaluate values\n\nprint(Te_w)\nprint(Ve_x*1e-6)\nprint(Ve_y*1e-6)\nprint(Ve_z*1e-6)\n\n#Ve_x, Ve_y, Ve_z = Ve_x[mask], Ve_y[mask], Ve_z[mask]\n\n#sigm_theo = np.array([eval_val(*args) for args in zip(eps_v, Te_w, Ve_x, Ve_y, Ve_z,)])\n\nsigma_pic_lin = np.array([sig_lin(2*t).subs({epstar: e}).evalf() for t,e in zip(Te_w, eps_v)])\n\nprint(eps_v)\nsigma_pic_lin\n```\n\n [11.21362797 4.93713922 3.67603179 6.40504603]\n [-0.59226227 -0.18757821 -1.00862928 -0.73077377]\n [-0.11153141 0.02806326 -0.84777541 -0.32723849]\n [-0.09976853 -0.17054007 -0.05507064 0.00116052]\n [ 50 10 400 200]\n\n\n\n\n\n array([0.724272559463891, 0.993713922414099, 0.509190079474029,\n 0.532025230125938], dtype=object)\n\n\n\n\n```python\nsigma_pic_lin\n```\n\n\n```python\nplt.scatter(eps_v,sigm_theo, label = \"drifting Maxwellian\")\nplt.scatter(eps_v, sigma_pic_lin , label = \"non-drifting Maxw\")\nplt.legend()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "9d3cbc9822f0e7a2621e978982de045d7913856b", "size": 503962, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/Chapitre1/scripts_figure/Te_profile_17-04-2018.ipynb", "max_stars_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_stars_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Chapitre1/scripts_figure/Te_profile_17-04-2018.ipynb", "max_issues_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_issues_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Chapitre1/scripts_figure/Te_profile_17-04-2018.ipynb", "max_forks_repo_name": "antoinetavant/PhD_thesis_manuscript", "max_forks_repo_head_hexsha": "1fdaf99356f75abc488edf1f30b5dd65f22bcdca", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 564.3471444569, "max_line_length": 263596, "alphanum_fraction": 0.930476901, "converted": true, "num_tokens": 3257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.34226220626413734}} {"text": "   \n\n# Tutorial 2: Modern RNNs and their variants\n\n**Week 2, Day 3: Modern RNNs**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Bhargav Srinivasa Desikan, Anis Zahedifard, James Evans\n\n__Content reviewers:__ Lily Cheng, Melvin Selim Atay, Ezekiel Williams, Kelson Shilling-Scrivo\n\n__Content editors:__ Gagana B, Spiros Chavlis\n\n__Production editors:__ Roberto Guidotti, Spiros Chavlis\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n---\n# Tutorial objectives\n\nIn this tutorial you will learn about:\n1. Modern Recurrent Neural Networks and their use\n2. Long Short-Term Memory (LSTM), Gated Recurrent Unit (GRU) and the memory cell\n3. Sequence to Sequence and Encoder-Decoder Networks\n4. Models of attention for text classification\n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorials\n\n# @markdown If you want to locally download the slides, click [here](https://osf.io/n23hy/download)\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/n23hy/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n# Setup\n\nWe will use the IMDB dataset, which consists of a set of 25,000 highly polar movie reviews for training, and 25,000 for testing. We will use torchtext to download the dataset and prepare it for training, validation and testing. Our goal is to build a model that performs binary classification between positive and negative movie reviews.\n\nWe use `fix_length` argument to pad sentences of length less than `sentence_length` or truncate sentences of length greater than `sentence_length`. \n\n\n```python\n# @title Install dependecies\n\n# @markdown There may be `Errors`/`Warnings` reported during the installation. However, they are to be ignored.\n!pip install --upgrade gensim --quiet\n!pip install torchtext==0.4.0 --quiet\n!pip install unidecode --quiet\n!pip install d2l --quiet\n!pip install nltk --quiet\n\n!pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet\nfrom evaltools.airtable import AirtableForm\n\natform = AirtableForm('appn7VdPRseSoMXEG','W2D3_T2','https://portal.neuromatchacademy.org/api/redirect/to/3412a777-eb0e-4312-9254-eec266f0bee4')\n```\n\n\n```python\n# Imports\nimport math\nimport time\nimport nltk\nimport random\nimport collections\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom torchtext import data, datasets\n\nfrom d2l import torch as d2l\n```\n\n\n```python\n# @title Figure Settings\nimport ipywidgets as widgets\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")\n```\n\n\n```python\n# @title Download the dataset\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\nnltk.download('brown')\nnltk.download('webtext')\n```\n\n\n```python\n# @title Helper functions\n\ndef plot_train_val(x, train, val, train_label,\n val_label, title, y_label,\n color):\n\n plt.plot(x, train, label=train_label, color=color)\n plt.plot(x, val, label=val_label, color=color, linestyle='--')\n plt.legend(loc='lower right')\n plt.xlabel('epoch')\n plt.ylabel(y_label)\n plt.title(title)\n\n\ndef count_parameters(model):\n parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n return parameters\n\n\ndef init_weights(m):\n if type(m) in (nn.Linear, nn.Conv1d):\n nn.init.xavier_uniform_(m.weight)\n\n\n# Dataset Loader\ndef load_dataset(sentence_length=50, batch_size=32, seed=522):\n\n TEXT = data.Field(sequential=True,\n tokenize=nltk.word_tokenize,\n lower=True,\n include_lengths=True,\n batch_first=True,\n fix_length=sentence_length)\n LABEL = data.LabelField(dtype=torch.float)\n\n train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)\n\n # If no specific vector embeddings are specified,\n # Torchtext initializes random vector embeddings\n # which would get updated during training through backpropagation.\n TEXT.build_vocab(train_data)\n LABEL.build_vocab(train_data)\n\n train_data, valid_data = train_data.split(split_ratio=0.7,\n random_state=random.seed(seed))\n train_iter, valid_iter, test_iter = data.BucketIterator.splits((train_data, valid_data, test_data),\n batch_size=batch_size, sort_key=lambda x: len(x.text),\n repeat=False, shuffle=True)\n vocab_size = len(TEXT.vocab)\n\n print(f\"Data loading is completed. Sentence length: {sentence_length}, \"\n f\"Batch size: {batch_size}, and seed: {seed}\")\n\n return TEXT, vocab_size, train_iter, valid_iter, test_iter\n\n\ndef text_from_dict(arr, dictionary):\n text = []\n for element in arr:\n text.append(dictionary[element])\n return text\n\n\ndef view_data(TEXT, train_iter):\n for idx, batch in enumerate(train_iter):\n text = batch.text[0]\n target = batch.label\n\n for itr in range(25, 30):\n print('Review: ', ' '.join(text_from_dict(text[itr], TEXT.vocab.itos)))\n print('Label: ', int(target[itr].item()), '\\n')\n\n print('[0: Negative Review, 1: Positive Review]')\n if idx==0:\n break\n\n\n# Training function\ndef train(model, device, train_iter, valid_iter, epochs, learning_rate):\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n train_loss, validation_loss = [], []\n train_acc, validation_acc = [], []\n\n for epoch in range(epochs):\n #train\n model.train()\n running_loss = 0.\n correct, total = 0, 0\n steps = 0\n\n for idx, batch in enumerate(train_iter):\n text = batch.text[0]\n # print(type(text), text.shape)\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n # add micro for coding training loop\n optimizer.zero_grad()\n output = model(text)\n\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n steps += 1\n running_loss += loss.item()\n\n # get accuracy\n _, predicted = torch.max(output, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n train_loss.append(running_loss/len(train_iter))\n train_acc.append(correct/total)\n\n print(f'Epoch: {epoch + 1}, '\n f'Training Loss: {running_loss/len(train_iter):.4f}, '\n f'Training Accuracy: {100*correct/total: .2f}%')\n\n # evaluate on validation data\n model.eval()\n running_loss = 0.\n correct, total = 0, 0\n\n with torch.no_grad():\n for idx, batch in enumerate(valid_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n optimizer.zero_grad()\n output = model(text)\n\n loss = criterion(output, target)\n running_loss += loss.item()\n\n # get accuracy\n _, predicted = torch.max(output, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n validation_loss.append(running_loss/len(valid_iter))\n validation_acc.append(correct/total)\n\n print (f'Validation Loss: {running_loss/len(valid_iter):.4f}, '\n f'Validation Accuracy: {100*correct/total: .2f}%')\n\n return train_loss, train_acc, validation_loss, validation_acc\n\n\n# Testing function\ndef test(model, device, test_iter):\n model.eval()\n correct = 0\n total = 0\n with torch.no_grad():\n for idx, batch in enumerate(test_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n outputs = model(text)\n _, predicted = torch.max(outputs, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n acc = 100 * correct / total\n return acc\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nDEVICE = set_device()\nSEED = 2021\nset_seed(seed=SEED)\n```\n\n---\n# Section 1: Recurrent Neural Networks (RNNs)\n\n*Time estimate: ~27mins*\n\n\n```python\n# @title Video 1: Recurrent Neural Networks\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Ng41177az\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"hIHocwdyY7M\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 1: Recurrent Neural Networks')\n\ndisplay(out)\n```\n\nRecurrent neural networks, or RNNs , are a family of neural networks for processing sequential data. Just as a convolutional network is specialized for processing a grid of values X such as an image, a recurrent neural network is specialized for processing a sequence of values. RNNs prove useful in many scenarios where other deep learning models are not effective.\n\n* Not all problems can be converted into one with fixed length inputs and outputs.\n\n\n* The deep learning models we have seen so far pick samples randomly. This might not be the best strategy for a task of understanding meaning from a piece of text. Words in a text occur in a sequence and therefore cannot be permuted randomly to get the meaning.\n\nThe following provides more data than the video (but can be skipped for now). For more detail, see the sources, the [deep learning book](https://www.deeplearningbook.org/contents/rnn.html), and [d2l.ai](https://d2l.ai/chapter_recurrent-neural-networks/rnn.html)\n\nWhen the recurrent network is trained to perform a task that requires predicting the future from the past, the network typically learns to use a hidden state at time step $t$, $H_t$ as a kind of lossy summary of the task-relevant aspects of the past sequence of inputs up to $t$. This summary is in general necessarily lossy, since it maps an arbitrary length sequence $(X_t, X_{t-1}, X_{t-2}, . . . , X_{2}, X_{1})$ to a fixed length vector $H_t$.\n\nWe can represent the unfolded recurrence after $t$ steps with a function $G_t$:\n\n\\begin{align}\nH_t &= G_t(X_t, X_{t-1}, X_{t-2}, \\dots, X_{2}, X_{1}) \\\\\n&= f(H_{t−1}, X_{t}; \\theta)\n\\end{align}\n\nwhere $\\theta$ denotes the model parameters, i.e., weights and biases.\n\n
\n \n
\n Source blog.floydhub.com\n
\n
\n\nThe function $g_t$ takes the whole past sequence $(X_t, X_{t-1}, X_{t-2}, . . . , X_{2}, X_{1})$ as input and produces the current state, but the unfolded recurrent structure allows us to factorize $g_t$ into repeated application of a function f. The unfolding process thus introduces two major advantages:\n\n* Regardless of the sequence length, the learned model always has the same input size, because it is specified in terms of transition from one state to another state, rather than specified in terms of a variable-length history of states.\n\n* It is possible to use the same transition function $f$ with the same parameters at every time step.\n\n\nWe will now formally write down the equations of a recurrent unit.\n\n\nAssume that we have a minibatch of inputs $X_t \\in R^{nxd}$ at time step $t$ . In other words, for a minibatch of $n$ sequence examples, each row of $X_t$ corresponds to one example at time step $t$ from the sequence. Next, we denote by $H_t \\in R^{nxh}$ the hidden variable of time step $t$. Unlike the MLP, here we save the hidden variable $H_{t-1}$ from the previous time step and introduce a new weight parameter $W_{hh} \\in R^{hxh}$ to describe how to use the hidden variable of the previous time step in the current time step. Specifically, the calculation of the hidden variable of the current time step is determined by the input of the current time step together with the hidden variable of the previous time step:\n\n\\begin{equation}\nH_t = \\phi(X_t W_{xh} + H_{t-1}W_{hh} + b_h)\n\\end{equation}\n\nFor time step $t$, the output of the output layer is similar to the computation in the MLP:\n\n\\begin{equation}\nO_t = H_t W_{hq} + b_q\n\\end{equation}\n \nParameters of the RNN include the weights $W_{xh} \\in R^{d \\times h}, W_{hh} \\in R^{h \\times h}$ , and the bias $b_h \\in R^{1 \\times h}$ of the hidden layer, together with the weights $W_{hq} \\in R^{h \\times q}$ and the bias $b_q \\in R^{1 \\times q}$ of the output layer. It is worth mentioning that even at different time steps, RNNs always use these model parameters. Therefore, the parameterization cost of an RNN does not grow as the number of time steps increases.\n\n
\n \n
\n Source d2l.ai\n
\n
\n\n## Section 1.1: Load and View of the dataset\n\nLet us first load the dataset using the helper function `load_data`, which takes three arguments; the `sentence_length`, `batch_size`, and the `seed`. The default values are 50, 32, and 522, respectively. Execute the cell below to load the data.\n\n\n```python\n# @markdown Dataset Loading with default params\nTEXT, vocab_size, train_iter, valid_iter, test_iter = load_dataset(seed=SEED)\n```\n\nNow, let's view the data!\n\n\n```python\n# @markdown Visualize dataset\nview_data(TEXT, train_iter)\n```\n\n### Coding Exercise 1.1: Vanilla RNN\n\nNow it's your turn to write a Vanilla RNN using PyTorch.\n\n* Once again we will use `nn.Embedding`. You are given the `vocab_size` which is the size of the dictionary of embeddings, and the `embed_size` which is the size of each embedding vector. \n\n* Add 2 [RNN](https://pytorch.org/docs/stable/generated/torch.nn.RNN.html) layers. This would mean stacking two RNNs together to form a stacked RNN, with the second RNN taking in outputs of the first RNN and computing the final results.\n\n* Determine the size of inputs and outputs to the fully-connected layer.\n\n\n```python\nclass VanillaRNN(nn.Module):\n def __init__(self, layers, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(VanillaRNN, self).__init__()\n self.n_layers= layers\n self.hidden_size = hidden_size\n self.device = device\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Define the Vanilla RNN components\")\n ####################################################################\n # Define the embedding\n self.embeddings = ...\n # Define the RNN layer\n self.rnn = ...\n # Define the fully connected layer\n self.fc = ...\n\n def forward(self, inputs):\n input = self.embeddings(inputs)\n input = input.permute(1, 0, 2)\n h_0 = torch.zeros(2, input.size()[1], self.hidden_size).to(self.device)\n output, h_n = self.rnn(input, h_0)\n h_n = h_n.permute(1, 0, 2)\n h_n = h_n.contiguous().reshape(h_n.size()[0], h_n.size()[1]*h_n.size()[2])\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 1.1: Vanilla RNN')\n\n## Uncomment to test VanillaRNN class\n# sampleRNN = VanillaRNN(2, 10, 50, 1000, 300, DEVICE)\n# print(sampleRNN)\n```\n\n\n```python\n# to_remove solution\nclass VanillaRNN(nn.Module):\n def __init__(self, layers, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(VanillaRNN, self).__init__()\n self.n_layers= layers\n self.hidden_size = hidden_size\n self.device = device\n # Define the embedding\n self.embeddings = nn.Embedding(vocab_size, embed_size)\n # Define the RNN layer\n self.rnn = nn.RNN(embed_size, hidden_size, self.n_layers)\n # Define the fully connected layer\n self.fc = nn.Linear(self.n_layers *hidden_size, output_size)\n\n def forward(self, inputs):\n input = self.embeddings(inputs)\n input = input.permute(1, 0, 2)\n h_0 = torch.zeros(2, input.size()[1], self.hidden_size).to(self.device)\n output, h_n = self.rnn(input, h_0)\n h_n = h_n.permute(1, 0, 2)\n h_n = h_n.contiguous().reshape(h_n.size()[0], h_n.size()[1]*h_n.size()[2])\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 1.1: Vanilla RNN')\n\n## Uncomment to test VanillaRNN class\nsampleRNN = VanillaRNN(2, 10, 50, 1000, 300, DEVICE)\nprint(sampleRNN)\n```\n\n```\nVanillaRNN(\n (embeddings): Embedding(1000, 300)\n (rnn): RNN(300, 50, num_layers=2)\n (fc): Linear(in_features=100, out_features=10, bias=True)\n)\n```\n\n## Section 1.2: Train and test the network\n\n\n```python\n# Model hyperparamters\nlearning_rate = 0.0002\nlayers = 2\noutput_size = 2\nhidden_size = 50 # 100\nembedding_length = 100\nepochs = 10\n\n\n# Initialize model, training and testing\nset_seed(SEED)\nvanilla_rnn_model = VanillaRNN(layers, output_size, hidden_size, vocab_size,\n embedding_length, DEVICE)\nvanilla_rnn_model.to(DEVICE)\nvanilla_rnn_start_time = time.time()\nvanilla_train_loss, vanilla_train_acc, vanilla_validation_loss, vanilla_validation_acc = train(vanilla_rnn_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\nprint(\"--- Time taken to train = %s seconds ---\" % (time.time() - vanilla_rnn_start_time))\ntest_accuracy = test(vanilla_rnn_model, DEVICE, test_iter)\nprint(f'Test Accuracy: {test_accuracy} with len=50\\n')\n\n# Number of model parameters\nprint(f'Number of parameters = {count_parameters(vanilla_rnn_model)}')\n\n\n# Plot accuracy curves\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), vanilla_train_acc, vanilla_validation_acc,\n 'train accuracy', 'val accuracy',\n 'Vanilla RNN on IMDB text classification', 'accuracy',\n color='C0')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), vanilla_train_loss,\n vanilla_validation_loss,\n 'train loss', 'val loss',\n 'Vanilla RNN on IMDB text classification',\n 'loss [a.u.]',\n color='C0')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n### Change the input length\n\nNow let's increase the `sentence_length` to see how RNN performs when long reviews are allowed..\n\n\n\n```python\n# @markdown Load dataset with `sentence_length=200`\nTEXT_long, vocab_size_long, train_iter_long, valid_iter_long, test_iter_long = load_dataset(sentence_length=200)\n```\n\n### Re-run the network\n\n\n```python\n# Model hyperparamters\nlearning_rate = 0.0002\nlayers = 2\noutput_size = 2\nhidden_size = 50 # 100\nembedding_length = 100\nepochs = 10\n\n# Initialize model, training, testing\nset_seed(SEED)\nvanilla_rnn_model_long = VanillaRNN(layers, output_size, hidden_size,\n vocab_size_long, embedding_length, DEVICE)\nvanilla_rnn_model_long.to(DEVICE)\nvanilla_rnn_start_time_long = time.time()\nvanilla_train_loss_long, vanilla_train_acc_long, vanilla_validation_loss_long, vanilla_validation_acc_long = train(vanilla_rnn_model_long,\n DEVICE,\n train_iter_long,\n valid_iter_long,\n epochs,\n learning_rate)\nprint(\"--- Time taken to train = %s seconds ---\" % (time.time() - vanilla_rnn_start_time_long))\ntest_accuracy = test(vanilla_rnn_model_long, DEVICE, test_iter_long)\nprint(f'Test Accuracy: {test_accuracy} with len=200\\n')\n\n# Number of parameters\nprint(f'\\nNumber of parameters = {count_parameters(vanilla_rnn_model_long)}')\n```\n\n\n```python\n# Compare accuracies of model trained on different sentence lengths\nplot_train_val(np.arange(0, epochs), vanilla_train_acc,\n vanilla_validation_acc,\n 'train accuracy, len=50', 'val accuracy, len=50',\n '', 'accuracy',\n color='C0')\nplot_train_val(np.arange(0, epochs), vanilla_train_acc_long,\n vanilla_validation_acc_long,\n 'train accuracy, len=200', 'val accuracy, len=200',\n 'Training and Validation Accuracy for Sentence Lengths 50 and 200',\n 'accuracy',\n color='C1')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n## Section 1.3: Architectures\n\n\n```python\n# @title Video 2: Bidirectional RNNs\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1X64y1x7BA\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"TpgJwqB4i1c\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 2: Bidirectional RNNs')\n\ndisplay(out)\n```\n\nRNN models are mostly used in the fields of natural language processing and speech recognition. Below are types of RNNs. Depending on which outputs we use, RNN can be used for variety of tasks. The text classification problem we solved was an instance of the many to one architecture. Write down the applications of other architectures. \n\n\n
\n \n
\n Source blog.floydhub.com\n
\n
\n\n## Section 1.4: Vanishing and Exploding Gradients\n\nFor an RNN to learn via backprop through time on a loss calculated at time $T$, $\\mathcal{L}_T$, with respect to an input $t$ time steps in the past, the RNN weights must be updated based on how they contributed to the hidden state at this past time step. This contribution is learned through the term $\\frac{\\partial h_{-t}}{\\partial W}$, in the gradient of the loss, $\\frac{\\partial\\mathcal{L}_T}{\\partial W}$.\n\nHowever, because one has to backpropagate error through $t-1$ hidden states, $\\frac{\\partial h_{-t}}{\\partial W}$ is multiplied by $\\prod_{i=0}^{t-1} \\frac{\\partial{h_i}}{\\partial{h_{i-1}}}$ in the expression for $\\frac{\\partial\\mathcal{L}_T}{\\partial W}$, which are summarized mathematically:\n\n\\begin{equation}\n\\frac{\\partial{\\mathcal{L}_T}}{\\partial{W}} \\propto \\frac{\\partial h_t }{ \\partial W} + \\sum_{k=0}^{t-1} \\left( \\prod_{i=k+1}^{t} \\frac{\\partial{h_i}}{\\partial{h_{i-1}}} \\right) \\frac{\\partial{h_k}}{\\partial{W}}\n\\end{equation}\n\nThe product term leads to two common problems during the backpropagation of time-series data:\n\n* *Vanishing gradients*, *if* $ \\left| \\left| \\frac{\\partial{h_i}}{\\partial{h_{i-1}}} \\right| \\right|_2 < 1$\n\n\n* *Exploding gradients*, *if* $ \\left| \\left| \\frac{\\partial{h_i}}{\\partial{h_{i-1}}} \\right| \\right|_2 > 1$\n\nGiven a sufficiently long sequence, the gradients get multiplied by the weight matrix at every time step. If the weight matrix contains very small values, then the norm of gradients will become smaller and smaller exponentially, the so-called **vanishing gradient** problem. On the other hand, if we have a weight matrix with very large values, the gradients will increase exponentially, leading to the **exploding gradients** problem: where the weights diverge at the update step.\n\nAn example that has the vanishing gradient problem:\n\nThe input is the characters from a *C* Program. The system will tell whether it is a syntactically correct program. A syntactically correct program should have a valid number of braces and parentheses. Thus, the network should remember how many open parentheses and braces there are to check, and whether we have closed them all. The network has to store such information in hidden states like a counter. However, because of vanishing gradients, it will fail to preserve such information in a long program.\n\n---\n# Section 2: LSTM, GRU and Memory Cell\n\n*Time estimate: ~28mins*\n\n\n```python\n# @title Video 3: LSTM, GRU & The Memory Cells\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Zq4y1X7kj\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"qC7O-2sXLAU\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 3: LSTM, GRU & The Memory Cells')\n\ndisplay(out)\n```\n\n## Section 2.1: Architecture\n\nThe core idea behind an LSTM is the cell state $C_t$ that runs along all the LSTM units in a layer, and gets updated along the way. These updates are possible through \"gates\". Gates are made out of a sigmoid neural net layer and a pointwise multiplication operation. \n\nEach LSTM unit performs the following distinct steps using the input $X_t$, current cell state $C_t$ and previous hidden state $H_{t-1}$:\n\n* Forget Gate: *Should I throw away information from this cell?*\n\n\\begin{equation}\nF_t = \\sigma (W_f \\cdot [H_{t-1}, X_t] + b_f)\n\\end{equation}\n\n* Input Gate:\n * *Should I add new values to this cell?*\n \\begin{equation}\n I_t = \\sigma (W_i \\cdot [H_{t-1}, X_t] + b_i)\n \\end{equation}\n * *What new candidate values should I store?*\n \\begin{equation}\n \\tilde{C}_t = tanh (W_C \\cdot [H_{t-1}, X_t] + b_C)\n \\end{equation}\n\n* Update cell state: *Forget things from the past and add new things from the candidates*\n \\begin{equation}\n C_t = (F_t \\cdot C_{t-1}) + (I_t \\cdot \\tilde{C}_t)\n \\end{equation}\n\n* Output Gate: \n * *What information should I output?*\n \\begin{equation}\n O_t = \\sigma (W_o \\cdot [H_{t-1}, X_t] + b_o)\n \\end{equation}\n * *How much of the cell state should I store in the hidden state?*\n \\begin{equation}\n H_t = O_t \\cdot tanh(C_t)\n \\end{equation}\n\nThe architecture can be summarized by the diagram below:\n\n
\n
\n \n
\n Source d2l.ai\n
\n
\n
\n\n### Coding Exercise 2.1: Implementing LSTM\n\nIt is now your turn to build an LSTM network in PyTorch. Feel free to refer to the documentation here: https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#torch.nn.LSTM . \n\n* Once again we will use `nn.Embedding`. You are given the `vocab_size` and the `embed_size`.\n* Add the [`LSTM`](https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#torch.nn.LSTM) layers. \n* Define a dropout layer of 0.5. \n* Determine the size of inputs and outputs to the fully-connected layer.\n* Pay special attention to the shapes of your inputs and outputs as you write the forward function.\n\n\n\n\n```python\nclass LSTM(nn.Module):\n def __init__(self, layers, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(LSTM, self).__init__()\n self.n_layers = layers\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.device = device\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"LSTM Init\")\n ####################################################################\n # Define the word embeddings\n self.word_embeddings = ...\n # Define the dropout layer\n self.dropout = ...\n # Define the lstm layer\n self.lstm = ...\n # Define the fully-connected layer\n self.fc = ...\n\n\n def forward(self, input_sentences):\n \"\"\"Hint: Make sure the shapes of your tensors match the requirement\"\"\"\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"LSTM Forward\")\n ####################################################################\n # Embeddings\n # `input` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n input = ...\n\n hidden = (torch.randn(self.n_layers, input.shape[1],\n self.hidden_size).to(self.device),\n torch.randn(self.n_layers, input.shape[1],\n self.hidden_size).to(self.device))\n # Dropout for regularization\n input = self.dropout(input)\n # LSTM\n output, hidden = ...\n\n h_n = hidden[0].permute(1, 0, 2)\n h_n = h_n.contiguous().view(h_n.shape[0], -1)\n\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 2.1: Implementing LSTM')\n\n## Uncomment to run\n# sampleLSTM = LSTM(3, 10, 100, 1000, 300, DEVICE)\n# print(sampleLSTM)\n```\n\n\n```python\n# to_remove solution\nclass LSTM(nn.Module):\n def __init__(self, layers, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(LSTM, self).__init__()\n self.n_layers = layers\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.device = device\n # Define the word embeddings\n self.word_embeddings = nn.Embedding(vocab_size, embed_size)\n # Define the dropout layer\n self.dropout = nn.Dropout(0.5)\n # Define the lstm layer\n self.lstm = nn.LSTM(embed_size, hidden_size, num_layers=self.n_layers)\n # Define the fully-connected layer\n self.fc = nn.Linear(self.n_layers*self.hidden_size, output_size)\n\n\n def forward(self, input_sentences):\n # Embeddings\n # `input` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n input = self.word_embeddings(input_sentences).permute(1, 0, 2)\n\n hidden = (torch.randn(self.n_layers, input.shape[1],\n self.hidden_size).to(self.device),\n torch.randn(self.n_layers, input.shape[1],\n self.hidden_size).to(self.device))\n # Dropout for regularization\n input = self.dropout(input)\n # LSTM\n output, hidden = self.lstm(input, hidden)\n\n h_n = hidden[0].permute(1, 0, 2)\n h_n = h_n.contiguous().view(h_n.shape[0], -1)\n\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 2.1: Implementing LSTM')\n\n## Uncomment to run\nsampleLSTM = LSTM(3, 10, 100, 1000, 300, DEVICE)\nprint(sampleLSTM)\n```\n\n```\nLSTM(\n (word_embeddings): Embedding(1000, 300)\n (dropout): Dropout(p=0.5, inplace=False)\n (lstm): LSTM(300, 100, num_layers=3)\n (fc): Linear(in_features=300, out_features=10, bias=True)\n)\n```\n\n\n```python\n# Hyperparameters\nlearning_rate = 0.0003\nlayers = 2\noutput_size = 2\nhidden_size = 16\nembedding_length = 100\nepochs = 10\n\n# Model, training, testing\nset_seed(SEED)\nlstm_model = LSTM(layers, output_size, hidden_size, vocab_size,\n embedding_length, DEVICE)\nlstm_model.to(DEVICE)\nlstm_train_loss, lstm_train_acc, lstm_validation_loss, lstm_validation_acc = train(lstm_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\ntest_accuracy = test(lstm_model, DEVICE, test_iter)\nprint(f'\\n\\nTest Accuracy: {test_accuracy} of the LSTM model\\n')\n\n# Plotting accuracy curve\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), lstm_train_acc, lstm_validation_acc,\n 'train accuracy',\n 'val accuracy',\n 'LSTM on IMDB text classification',\n 'accuracy',\n color='C0')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), lstm_train_loss, lstm_validation_loss,\n 'train loss',\n 'val loss',\n '',\n 'loss',\n color='C0')\nplt.legend(loc='upper left')\nplt.tight_layout()\nplt.show()\n```\n\n## Section 2.2: Gated Recurrent Units (GRU)\n\nThe GRU architecture looks very similar to the LSTM, and is often used as an alternative to the traditional LSTM. It also contains some variations that reduce it's complexity. For example, it combines the forget and input gates into a single “update gate”; it contains a \"hidden state\" but not a \"cell state\". In the next section we will be using GRUs as the choice of recurrent unit in our models, but you can always swap out the GRU for an LSTM later on (make sure that you take care of input and output dimensions in this case). Here is a description of the parts of the GRU:\n\n* Reset Gate: *How much of the previous hidden state should I remember?*\n \\begin{equation}\n R_t = \\sigma (W_r \\cdot [H_{t-1}, X_t])\n \\end{equation}\n\n* Update Gate: \n * *How much of the new state is different from the old state?*\n \\begin{equation}\n Z_t = \\sigma (W_z \\cdot [H_{t-1}, X_t])\n \\end{equation}\n * *What new candidate values should I store?*\n \\begin{equation}\n \\tilde{H}_t = tanh (W \\cdot [R_t \\cdot H_{t-1}, X_t])\n \\end{equation}\n\n* Update hidden state: *Deciding how much of the old hidden state to keep and discard*\n \\begin{equation}\n H_t = ((1-Z_t) \\cdot H_{t-1} ) + (Z_t \\cdot \\tilde{H}_t)\n \\end{equation}\n\nHere is what the architecture looks like:\n\n
\n
\n \n
\n Source d2l.ai\n
\n
\n
\n\n### Coding Exercise 2.2: BiLSTM\n\nLet's apply the knowledge to write a bi-LSTM using PyTorch.\n\n* Use an Embedding layer\n* Dropout of 0.5\n* Add 2 LSTM layers\n* Linear layer \n\n\n```python\nclass biLSTM(nn.Module):\n def __init__(self, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(biLSTM, self).__init__()\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.device = device\n ####################################################################\n # Fill in missing code below (...)\n raise NotImplementedError(\"biLSTM\")\n ####################################################################\n # Define the word embeddings\n self.word_embeddings = ...\n # Define the dropout layer\n self.dropout = ...\n # Define the bilstm layer\n self.bilstm = ...\n # Define the fully-connected layer\n self.fc = ...\n\n def forward(self, input_sentences):\n input = self.word_embeddings(input_sentences).permute(1, 0, 2)\n hidden = (torch.randn(4, input.shape[1], self.hidden_size).to(self.device),\n torch.randn(4, input.shape[1], self.hidden_size).to(self.device))\n input = self.dropout(input)\n\n output, hidden = self.bilstm(input, hidden)\n\n h_n = hidden[0].permute(1, 0, 2)\n h_n = h_n.contiguous().view(h_n.shape[0], -1)\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 2.2: BiLSTM')\n\n## Uncomment to run\n# sampleBiLSTM = biLSTM(10, 100, 1000, 300, DEVICE)\n# print(sampleBiLSTM)\n```\n\n\n```python\n# to_remove solution\nclass biLSTM(nn.Module):\n def __init__(self, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(biLSTM, self).__init__()\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.device = device\n # Define the word embeddings\n self.word_embeddings = nn.Embedding(vocab_size, embed_size)\n # Define the dropout layer\n self.dropout = nn.Dropout(0.5)\n # Define the bilstm layer\n self.bilstm = nn.LSTM(embed_size, hidden_size, num_layers=2, bidirectional=True)\n # Define the fully-connected layer\n self.fc = nn.Linear(4*hidden_size, output_size)\n\n\n def forward(self, input_sentences):\n input = self.word_embeddings(input_sentences).permute(1, 0, 2)\n hidden = (torch.randn(4, input.shape[1], self.hidden_size).to(self.device),\n torch.randn(4, input.shape[1], self.hidden_size).to(self.device))\n input = self.dropout(input)\n\n output, hidden = self.bilstm(input, hidden)\n\n h_n = hidden[0].permute(1, 0, 2)\n h_n = h_n.contiguous().view(h_n.shape[0], -1)\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 2.2: BiLSTM')\n\n## Uncomment to run\nsampleBiLSTM = biLSTM(10, 100, 1000, 300, DEVICE)\nprint(sampleBiLSTM)\n```\n\n```\nbiLSTM(\n (word_embeddings): Embedding(1000, 300)\n (dropout): Dropout(p=0.5, inplace=False)\n (bilstm): LSTM(300, 100, num_layers=2, bidirectional=True)\n (fc): Linear(in_features=400, out_features=10, bias=True)\n)\n```\n\n\n```python\n# Hyperparameters\nlearning_rate = 0.0003\noutput_size = 2\nhidden_size = 16\nembedding_length = 100\nepochs = 10\n\n# Model, training, testing\nset_seed(SEED)\nbilstm_model = biLSTM(output_size, hidden_size, vocab_size,\n embedding_length, DEVICE)\nbilstm_model.to(DEVICE)\nbilstm_train_loss, bilstm_train_acc, bilstm_validation_loss, bilstm_validation_acc = train(bilstm_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\ntest_accuracy = test(bilstm_model, DEVICE, test_iter)\nprint(f'Test Accuracy: {test_accuracy} of the biLSTM model\\n')\n\n# Plotting accuracy curve\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), bilstm_train_acc, bilstm_validation_acc,\n 'train accuracy',\n 'val accuracy',\n 'biLSTM on IMDB text classification',\n 'accuracy',\n color='C1')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), bilstm_train_loss, bilstm_validation_loss,\n 'train loss',\n 'val loss',\n '',\n 'loss',\n color='C1')\nplt.legend(loc='upper left')\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# Compare accuracies of LSTM and biLSTM\nplot_train_val(np.arange(0, epochs), lstm_train_acc,\n lstm_validation_acc,\n 'train accuracy LSTM', 'val accuracy LSTM',\n '', 'accuracy',\n color='C0')\nplot_train_val(np.arange(0, epochs), bilstm_train_acc,\n bilstm_validation_acc,\n 'train accuracy biLSTM', 'val accuracy biLSTM',\n 'Training and Validation Accuracy for LSTM and biLSTM models',\n 'accuracy',\n color='C1')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n---\n# Section 3: Sequence to Sequence (Seq2Seq) & Encoder/ Decoder Networks\n\n*Time estimate: ~15mins*\n\n\n```python\n# @title Video 4: Seq2Seq & Encoder-Decoder Nets\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1WM4y1N7P7\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"q-hf7mnZsXo\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 4: Seq2Seq & Encoder-Decoder Nets')\n\ndisplay(out)\n```\n\nSources: [d2l.ai on encoders](https://d2l.ai/chapter_recurrent-modern/encoder-decoder.html) ; [d2l.ai on seq2seq](https://d2l.ai/chapter_recurrent-modern/seq2seq.html) ; [Jalammar's blog](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/ )\n\nSequence-to-sequence models take in a sequence of items (words, characters, etc) as input and produces another sequence of items as output. The most \nsimple seq2seq models are composed of two parts: the encoder, the context (\"state\" in the figure) and the decoder. The encoder and decoder usually consist of recurrent units that we've seen before (RNNs, GRUs or LSTMs). A high-level schematic of the architecture is as follows:\n\n
\n
\n \n
\n Source d2l.ai\n
\n
\n
\n\nThe encoder's recurrent unit processes the input one item at a time. Once the entire sequence is processed, the final hidden state vector produced is known as a context vector. The size of the context vector is defined while setting up the model, and is equal to the number of hidden states used in the encoder RNN. The encoder then passes the context to the decoder. The decoder's recurrent unit uses the context to produce the items for the output sequence one by one. \n\n\nOne of the most popular applications of seq2seq models is \"machine translation\": the task of taking in a sentence in one language (the source) and producing its translation in another language (the target); with words in both lanugages being the sequence units. This is a supervised learning task, and requires the dataset to have \"parallel sentences\"; i.e., each sentence in the source language must be labelled with its translation in the target language. \n\n[Here is an intuitive visualization for understanding seq2seq models for machine translation from English to French](https://i.imgur.com/HJ6t8up.mp4)\n\nSince the vocabulary of an entire language is very large, training such models to give meaningful performance requires significant time and resources. In this section, we will train a seq2seq model to perform machine translation from English to [Pig-Latin](https://en.wikipedia.org/wiki/Pig_Latin). We will modify the task to perform character-level machine translation, so that vocabulary size does not grow exponentially. \n\n\n## Coding Exercise 3: Encoder\n\nLet us consider a sequence example (`batch_size=1`). Suppose that the input sequence is $x_1, \\ldots, x_T$, such that $x_t$ is the $t^{\\mathrm{th}}$ token in the input text sequence. At time step $t$, the RNN transforms the input feature vector $\\mathbf{x}_t$ for $x_t$ and the hidden state $\\mathbf{h} _{t-1}$ from the previous time step into the current hidden state $\\mathbf{h}_t$.\n\nWe can use a function $f$ to express the transformation of the RNN's recurrent layer:\n\n\\begin{equation}\n\\mathbf{h}_t = f(\\mathbf{x}_t, \\mathbf{h}_{t-1})\n\\end{equation}\n\nIn general, the encoder transforms the hidden states at all the time steps into the context variable through a customized function $q$:\n\n\\begin{equation}\n\\mathbf{c} = q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T)\n\\end{equation}\n\nFor example, when choosing $q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T) = \\mathbf{h}_T$ the context variable is just the hidden state $\\mathbf{h}_T$ of the input sequence at the final time step.\n\nSo far we have used a unidirectional RNN to design the encoder, where a hidden state only depends on the input subsequence at and before the time step of the hidden state. We can also construct encoders using bidirectional RNNs. In this case, a hidden state depends on the subsequence before and after the time step (including the input at the current time step), which encodes the information of the entire sequence.\n\nNow let us implement the RNN encoder. Note that we use an *embedding layer*\nto obtain the feature vector for each token in the input sequence. The weight of an embedding layer is a matrix whose number of rows is equal to the size of the input vocabulary (`vocab_size`) and the number of columns equals to the feature vector's dimension (`embed_size`). For any input token index $i$,\nthe embedding layer fetches the $i^{\\mathrm{th}}$ row (starting from 0) of the weight matrix to return its feature vector. ere we choose a multilayer GRU to implement the encoder.\n\nThe returned variables of recurrent layers have been completely explained at [this link](https://www.d2l.ai/chapter_recurrent-neural-networks/rnn-concise.html#sec-rnn-concise). Let us still use a concrete example to illustrate the above encoder implementation. Below we instantiate a two-layer GRU encoder whose number of hidden units is 16. Given a minibatch of sequence inputs $X$ (`batch_size=4`, `number_of_time_steps=7`), the hidden states of the last layer at all the time steps (`output` returned by the encoder's recurrent layers) are a tensor of shape (number of time steps, batch size, number of hidden units).\n\n\n\n```python\nclass Seq2SeqEncoder(d2l.Encoder):\n \"\"\"The RNN encoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqEncoder, self).__init__(**kwargs)\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Encoder Unit\")\n ####################################################################\n # Embedding layer\n self.embedding = ...\n # Here you're going to implement a GRU as the RNN unit\n self.rnn = ...\n\n def forward(self, X, *args):\n # The output `X` shape: (`batch_size`, `num_steps`, `embed_size`)\n X = self.embedding(X)\n # In RNN models, the first axis corresponds to time steps\n X = X.permute(1, 0, 2)\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Forward pass\")\n ####################################################################\n # When state is not mentioned, it defaults to zeros, the output should be a RNN function of X!\n output, state = ...\n # `output` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n # `state` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n\n return output, state\n\n\n# add event to airtable\natform.add_event('Coding Exercise 3: Encoder')\n\nX = torch.zeros((4, 7), dtype=torch.long)\n## uncomment the lines below.\n# encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)\n# encoder.eval()\n# output, state = encoder(X)\n# print(output.shape)\n# print(state.shape)\n```\n\n\n```python\n# to_remove solution\nclass Seq2SeqEncoder(d2l.Encoder):\n \"\"\"The RNN encoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqEncoder, self).__init__(**kwargs)\n\n # Embedding layer\n self.embedding = nn.Embedding(vocab_size, embed_size)\n # Here you're going to implement a GRU as the RNN unit\n self.rnn = nn.GRU(embed_size, num_hiddens, num_layers,\n dropout=dropout)\n\n def forward(self, X, *args):\n # The output `X` shape: (`batch_size`, `num_steps`, `embed_size`)\n X = self.embedding(X)\n # In RNN models, the first axis corresponds to time steps\n X = X.permute(1, 0, 2)\n # When state is not mentioned, it defaults to zeros, the output should be a RNN function of X!\n output, state = self.rnn(X)\n # `output` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n # `state` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n return output, state\n\n\n# add event to airtable\natform.add_event('Coding Exercise 3: Encoder')\n\nX = torch.zeros((4, 7), dtype=torch.long)\n## uncomment the lines below.\nencoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)\nencoder.eval()\noutput, state = encoder(X)\nprint(output.shape)\nprint(state.shape)\n```\n\n```\ntorch.Size([7, 4, 16])\ntorch.Size([2, 4, 16])\n```\n\n## Section 3.1: Decoder\n\nAs we just mentioned, the context variable $\\mathbf{c}$ of the encoder's output encodes the entire input sequence $x_1, \\ldots, x_T$. Given the output sequence $y_1, y_2, \\ldots, y_{T'}$ from the training dataset, for each time step $t'$\n(the symbol differs from the time step $t$ of input sequences or encoders),\nthe probability of the decoder output $y_{t'}$ is conditional on the previous output subsequence $y_1, \\ldots, y_{t'-1}$ and the context variable $\\mathbf{c}$, i.e., $P(y_{t'} \\mid y_1, \\ldots, y_{t'-1}, \\mathbf{c})$.\n\n\nTo model this conditional probability on sequences, we can use another RNN as the decoder. At any time step $t^\\prime$ on the output sequence, the RNN takes the output $y_{t^\\prime-1}$ from the previous time step and the context variable $\\mathbf{c}$ as its input, then transforms them and the previous hidden state $\\mathbf{s}_{t^\\prime-1}$ into the hidden state $\\mathbf{s}_{t^\\prime}$ at the current time step.\n\nAs a result, we can use a function $g$ to express the transformation of the decoder's hidden layer:\n\n\\begin{equation}\n\\mathbf{s}_{t^\\prime} = g(y_{t^\\prime-1}, \\mathbf{c}, \\mathbf{s}_{t^\\prime-1})\n\\end{equation}\n\nAfter obtaining the hidden state of the decoder, we can use an output layer and the softmax operation to compute the conditional probability distribution\n$P(y_{t^\\prime} \\mid y_1, \\ldots, y_{t^\\prime-1}, \\mathbf{c})$ for the output at time step $t^\\prime$.\n\nFollowing `fig_seq2seq`, when implementing the decoder as follows, we directly use the hidden state at the final time step of the encoder to initialize the hidden state of the decoder.\n\nThis requires that the RNN encoder and the RNN decoder have the same number of layers and hidden units. To further incorporate the encoded input sequence information, the context variable is concatenated with the decoder input at all the time steps. To predict the probability distribution of the output token,\na fully-connected layer is used to transform the hidden state at the final layer of the RNN decoder.\n\n\n```python\nclass Seq2SeqDecoder(d2l.Decoder):\n \"\"\"The RNN decoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqDecoder, self).__init__(**kwargs)\n self.embedding = nn.Embedding(vocab_size, embed_size)\n self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers,\n dropout=dropout)\n self.dense = nn.Linear(num_hiddens, vocab_size)\n\n def init_state(self, enc_outputs, *args):\n return enc_outputs[1]\n\n def forward(self, X, state):\n # The output `X` shape: (`num_steps`, `batch_size`, `embed_size`)\n X = self.embedding(X).permute(1, 0, 2)\n # Broadcast `context` so it has the same `num_steps` as `X`\n context = state[-1].repeat(X.shape[0], 1, 1)\n X_and_context = torch.cat((X, context), 2)\n output, state = self.rnn(X_and_context, state)\n output = self.dense(output).permute(1, 0, 2)\n # `output` shape: (`batch_size`, `num_steps`, `vocab_size`)\n # `state` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n return output, state\n```\n\nTo illustrate the implemented decoder,\nbelow we instantiate it with the same hyperparameters from the aforementioned encoder.\nAs we can see, the output shape of the decoder becomes (batch size, number of time steps, vocabulary size),\nwhere the last dimension of the tensor stores the predicted token distribution.\n\n\n\n```python\ndecoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16,\n num_layers=2)\n# decoder.initialize()\nstate = decoder.init_state(encoder(X))\noutput, state = decoder(X, state)\noutput.shape, len(state), state[0].shape\n```\n\n## Section 3.2: Loss Function\n\nAt each time step, the decoder predicts a probability distribution for the output tokens. Similar to language modeling, we can apply softmax to obtain the distribution and calculate the cross-entropy loss for optimization. Recall that the special padding tokens are appended to the end of sequences so sequences of varying lengths can be efficiently loaded in minibatches of the same shape.\nHowever, prediction of padding tokens should be excluded from loss calculations.\n\nTo this end, we can use the following `sequence_mask` function to mask irrelevant entries with zero values so later multiplication of any irrelevant prediction with zero equals to zero. For example, if the valid length of two sequences excluding padding tokens (i.e., pads each sequence to the same length usually matching the longest sequence) are one and two, respectively, the remaining entries after the first one and the first two entries are cleared to zeros.\n\n\n\n```python\ndef sequence_mask(X, valid_len, value=0):\n \"\"\"Mask irrelevant entries in sequences.\"\"\"\n maxlen = X.size(1)\n mask = torch.arange((maxlen), dtype=torch.float32,\n device=X.device)[None, :] < valid_len[:, None]\n X[~mask] = value\n return X\n\n\nX = torch.tensor([[1, 2, 3], [4, 5, 6]])\nprint(sequence_mask(X, torch.tensor([1, 2])))\nX = torch.ones(2, 3, 4)\nprint(sequence_mask(X, torch.tensor([1, 2]), value=-1))\n```\n\nNow we can extend the softmax cross-entropy loss\nto allow the masking of irrelevant predictions.\nInitially,\nmasks for all the predicted tokens are set to one.\nOnce the valid length is given,\nthe mask corresponding to any padding token\nwill be cleared to zero.\nIn the end,\nthe loss for all the tokens\nwill be multipled by the mask to filter out\nirrelevant predictions of padding tokens in the loss.\n\n\n\n```python\nclass MaskedSoftmaxCELoss(nn.CrossEntropyLoss):\n \"\"\"The softmax cross-entropy loss with masks.\"\"\"\n\n # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)\n # `label` shape: (`batch_size`, `num_steps`)\n # `valid_len` shape: (`batch_size`,)\n\n def forward(self, pred, label, valid_len):\n weights = torch.ones_like(label)\n weights = sequence_mask(weights, valid_len)\n self.reduction = 'none'\n unweighted_loss = super(MaskedSoftmaxCELoss,\n self).forward(pred.permute(0, 2, 1), label)\n weighted_loss = (unweighted_loss * weights).mean(dim=1)\n\n return weighted_loss\n\n\nloss = MaskedSoftmaxCELoss()\nloss(torch.ones(3, 4, 10),\n torch.ones((3, 4), dtype=torch.long),\n torch.tensor([4, 2, 0]))\n```\n\nIn the following training loop,\nwe concatenate the special beginning-of-sequence token\nand the original output sequence excluding the final token as\nthe input to the decoder.\nThis is called *teacher forcing* because\nthe original output sequence (token labels) is fed into the decoder.\nAlternatively,\nwe could also feed the *predicted* token\nfrom the previous time step\nas the current input to the decoder.\n\n\n```python\n#@title Training\ndef train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):\n \"\"\"Train a model for sequence to sequence.\"\"\"\n def xavier_init_weights(m):\n if type(m) == nn.Linear:\n nn.init.xavier_uniform_(m.weight)\n if type(m) == nn.GRU:\n for param in m._flat_weights_names:\n if \"weight\" in param:\n nn.init.xavier_uniform_(m._parameters[param])\n\n\n net.apply(xavier_init_weights)\n net.to(device)\n optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n loss = MaskedSoftmaxCELoss()\n net.train()\n animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n xlim=[10, num_epochs])\n for epoch in range(num_epochs):\n timer = d2l.Timer()\n metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens\n for batch in data_iter:\n optimizer.zero_grad()\n X, X_valid_len, Y, Y_valid_len = [x.to(device) for x in batch]\n bos = torch.tensor([tgt_vocab['']] * Y.shape[0],\n device=device).reshape(-1, 1)\n dec_input = torch.cat([bos, Y[:, :-1]], 1) # Teacher forcing\n Y_hat, _ = net(X, dec_input, X_valid_len)\n l = loss(Y_hat, Y, Y_valid_len)\n l.sum().backward() # Make the loss scalar for `backward`\n d2l.grad_clipping(net, 1)\n num_tokens = Y_valid_len.sum()\n optimizer.step()\n with torch.no_grad():\n metric.add(l.sum(), num_tokens)\n if (epoch + 1) % 10 == 0:\n animator.add(epoch + 1, (metric[0] / metric[1],))\n print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n f'tokens/sec on {str(device)}')\n```\n\nNow we can create and train an RNN encoder-decoder model\nfor sequence to sequence learning on the machine translation dataset.\n\n\n\n```python\nembed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1\nbatch_size, num_steps = 64, 10\nlr, num_epochs = 0.005, 300\n\ntrain_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\nencoder = Seq2SeqEncoder(len(src_vocab), embed_size, num_hiddens, num_layers,\n dropout)\ndecoder = Seq2SeqDecoder(len(tgt_vocab), embed_size, num_hiddens, num_layers,\n dropout)\nnet = d2l.EncoderDecoder(encoder, decoder)\ntrain_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, DEVICE)\n```\n\nTo predict the output sequence token by token, at each decoder time step\nthe predicted token from the previous time step is fed into the decoder as an input.\n\nSimilar to training, at the initial time step the beginning-of-sequence (<bos>\") token is fed into the decoder. This prediction process is illustrated in `seq2seq` figure. When the end-of-sequence (\"<eos>\") token is predicted, the prediction of the output sequence is complete.\n\n\n
\n \n
\n Source d2l.ai\n
\n
\n\n\n```python\n# @title Prediction\ndef predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,\n device, save_attention_weights=False):\n \"\"\"Predict for sequence to sequence.\"\"\"\n # Set `net` to eval mode for inference\n net.eval()\n src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n src_vocab['']]\n enc_valid_len = torch.tensor([len(src_tokens)], device=device)\n src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab[''])\n # Add the batch axis\n enc_X = torch.unsqueeze(\n torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0)\n enc_outputs = net.encoder(enc_X, enc_valid_len)\n dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n # Add the batch axis\n dec_X = torch.unsqueeze(\n torch.tensor([tgt_vocab['']], dtype=torch.long, device=device),\n dim=0)\n output_seq, attention_weight_seq = [], []\n for _ in range(num_steps):\n Y, dec_state = net.decoder(dec_X, dec_state)\n # We use the token with the highest prediction likelihood as the input\n # of the decoder at the next time step\n dec_X = Y.argmax(dim=2)\n pred = dec_X.squeeze(dim=0).type(torch.int32).item()\n # Save attention weights (to be covered later)\n if save_attention_weights:\n attention_weight_seq.append(net.decoder.attention_weights)\n # Once the end-of-sequence token is predicted, the generation of the\n # output sequence is complete\n if pred == tgt_vocab['']:\n break\n output_seq.append(pred)\n return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq\n```\n\nWe can evaluate a predicted sequence by comparing it with the label sequence (the ground-truth). BLEU (Bilingual Evaluation Understudy), though originally proposed for evaluating machine translation results in [Papieni et al., 2002](https://dl.acm.org/doi/10.3115/1073083.1073135), has been extensively used in measuring the quality of output sequences for different applications.\n\nIn principle, for any $n$-grams in the predicted sequence, BLEU evaluates whether this $n$-grams appears in the label sequence.\n\nDenote by $p_n$ the precision of $n$-grams, which is the ratio of the number of matched $n$-grams in the predicted and label sequences to the number of $n$-grams in the predicted sequence.\nTo explain, given a label sequence $A$, $B$, $C$, $D$, $E$, $F$, and a predicted sequence $A$, $B$, $B$, $C$, $D$, we have $p_1 = 4/5$, $p_2 = 3/4$, $p_3 = 1/3$, and $p_4 = 0$.\n\nBesides, let $\\mathrm{len}_{\\text{label}}$ and $\\mathrm{len}_{\\text{pred}}$\nbe the numbers of tokens in the label sequence and the predicted sequence, respectively.\n\nThen, BLEU is defined as\n\n\\begin{equation}\n\\exp\\left(\\min\\left(0, 1 - \\frac{\\mathrm{len}_{\\text{label}}}{\\mathrm{len}_{\\text{pred}}}\\right)\\right) \\prod_{n=1}^k p_n^{1/2^n},\n\\end{equation}\n\nwhere $k$ is the longest $n$-grams for matching.\n\nBased on the definition of BLEU in the above equation, whenever the predicted sequence is the same as the label sequence, BLEU is 1.\n\nMoreover, since matching longer $n$-grams is more difficult, BLEU assigns a greater weight to a longer $n$-gram precision. Specifically, when $p_n$ is fixed, $p_n^{1/2^n}$ increases as $n$ grows (the original paper uses $p_n^{1/n}$).\n\nFurthermore, since predicting shorter sequences tends to obtain a higher $p_n$ value, the coefficient before the multiplication term in the above equation\npenalizes shorter predicted sequences.\n\nFor example, when $k=2$, given the label sequence $A$, $B$, $C$, $D$, $E$, $F$ and the predicted sequence $A$, $B$, although $p_1 = p_2 = 1$, the penalty factor $\\exp(1-6/2) \\approx 0.14$ lowers the BLEU.\n\nWe implement the BLEU measure as follows.\n\n\n\n```python\n#@title Evaluation of Predicted Sequences\ndef bleu(pred_seq, label_seq, k):\n \"\"\"Compute the BLEU.\"\"\"\n pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n len_pred, len_label = len(pred_tokens), len(label_tokens)\n score = math.exp(min(0, 1 - len_label / len_pred))\n for n in range(1, k + 1):\n num_matches, label_subs = 0, collections.defaultdict(int)\n for i in range(len_label - n + 1):\n label_subs[''.join(label_tokens[i:i + n])] += 1\n for i in range(len_pred - n + 1):\n if label_subs[''.join(pred_tokens[i:i + n])] > 0:\n num_matches += 1\n label_subs[''.join(pred_tokens[i:i + n])] -= 1\n score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n return score\n```\n\nIn the end,\nwe use the trained RNN encoder-decoder\nto translate a few English sentences into French\nand compute the BLEU of the results.\n\n\n\n```python\nengs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\n# fras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\nfras = [ 'je suis chez moi .', 'j\\'ai perdu .','va !', 'il est calme .']\nfor eng, fra in zip(engs, fras):\n translation, attention_weight_seq = predict_seq2seq(net,\n eng,\n src_vocab,\n tgt_vocab,\n num_steps,\n DEVICE)\n print(f'{eng} => {translation}, bleu {bleu(translation, fra, k=2):.3f}')\n```\n\n---\n# Section 4: Ethical aspects\n\n*Time estimate: ~7mins*\n\n\n```python\n# @title Video 5: Ethics of Representation and Generation\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1v54y1J7SC\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"2ULMWtaGQrQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 5: Ethics of Representation and Generation')\n\ndisplay(out)\n```\n\n---\n# Summary\n\nDuring this day, we have learned about modern RNNs and their variants. Now let's see some ethical aspects of representation and Generation, and then we will close the tutorials with an overview.\n\n\n```python\n# @title Video 6: Beyond Sequence\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1864y1x7Ek\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"lVcpMSJileA\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 6: Beyond Sequence')\n\ndisplay(out)\n```\n\n\n```python\n# @title Airtable Submission Link\nfrom IPython import display as IPydisplay\nIPydisplay.HTML(\n f\"\"\"\n
\n \n \n
\"\"\" )\n```\n\n---\n# Bonus: Attention\n\n\n```python\n# @title Video 7: Attention mechanisms\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Mo4y1S7oK\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"Vt9GhJKcEiM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 7: Attention mechanisms')\n\ndisplay(out)\n```\n\nPreviously, we designed an encoder-decoder architecture based on two RNNs for sequence to sequence learning. Specifically, the RNN encoder transforms a variable-length sequence into a fixed-shape context variable, then the RNN decoder generates the output (target) sequence token by token based on the generated tokens and the context variable. However, even though not all the input (source) tokens are useful for decoding a certain token, the same context variable that encodes the entire input sequence is still used at each decoding step. It is challenging for the models to deal with long sentences. \n\nIn [Bahdanau et al., 2014](https://arxiv.org/abs/1409.0473), the authors proposed a technique called attention. When predicting a token, if not all the input tokens are relevant, the model aligns (or attends) only to parts of the input sequence that are relevant to the current prediction. \n\n\nIn contrast to seq2seq model, the encoder passes a lot more data to the decoder. Instead of passing the last hidden state of the encoding stage, the encoder passes all the hidden states to the decoder. \n\nIn order to focus on the parts of input relevant to the decoder, look at the set of encoder hidden states it received. Each encoder hidden state is at most associated with a certain word in the input sentence. We can assign each hidden state a score and multiply it with the softmaxed score, thus amplifying hidden states with high scores, and drowning out hidden states with low scores.\n\n\nReference Links: \\\\\n https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/ \\\\\n\n https://d2l.ai/chapter_attention-mechanisms/attention-cues.html\n\n\n```python\n# @markdown Media 1: Sequence to Sequence model with Attention\n\nurl = \"https://jalammar.github.io/images/seq2seq_7.mp4\"\nfrom IPython.display import HTML\nHTML(f\"\"\"
\n\n\n\n\n```python\n# get me rows 10 to 13 (python slicing style : exclusive of end) \ncast.iloc[10:13] #not inclusive of 13, iloc is zero based\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
titleyearnametypecharactern
10When the Man Went South2014Taipaleti 'Atu'akeactorTwo Palms - Ua'i Paame8.0
11Little Angel (Angelita)2015Michael 'babeepower' VieraactorChico9.0
12Mixing Nia1998Michael 'babeepower' VieraactorRapperNaN
\n
\n\n\n\n\n```python\n# get me columns 0 to 2 but all rows - use head()\ncast.iloc[:, 0:2].head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
titleyear
0Closet Monster2015
1Suuri illusioni1985
2Battle of the Sexes2017
3Secret in Their Eyes2015
4Steve Jobs2015
\n
\n\n\n\n\n```python\n# get me rows 10 to 13 AND only columns 0 to 2\ncast.iloc[10:13, 0:2]\ncasnew = cast.iloc[10:13, 0:2]\ncasnew\ncast.head()\n\n#use .copy() to make a copy of the data frame so that original is not messed up by any changes\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
titleyear
10When the Man Went South2014
11Little Angel (Angelita)2015
12Mixing Nia1998
\n
\n\n\n\n\n```python\n# COMPARE: get me rows 10 to 13 (pandas slicing style : inclusive of end)\ncast.loc[10:13]\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
titleyearnametypecharactern
10When the Man Went South2014Taipaleti 'Atu'akeactorTwo Palms - Ua'i Paame8.0
11Little Angel (Angelita)2015Michael 'babeepower' VieraactorChico9.0
12Mixing Nia1998Michael 'babeepower' VieraactorRapperNaN
13The Replacements2000Steven 'Bear'BoydactorDefensive Tackle - Washington SentinelsNaN
\n
\n\n\n\n\n```python\n# give me columns 'year' and 'type' by label but only for rows 5 to 10\ncast.loc[5:10,['year','type']] #can't do slicing on columns using loc\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
yeartype
52015actor
62015actor
72009actor
82014actor
92014actor
102014actor
\n
\n\n\n\n\n```python\n\n```\n\n\n## 2 - Plotting with matplotlib and beyond\n
\n \n\n`matplotlib` is a very powerful `python` library for making scientific plots. \n\nWe will not focus too much on the internal aspects of `matplotlib` in today's lab. There are many excellent tutorials out there for `matplotlib`. For example,\n* [`matplotlib` homepage](https://matplotlib.org/)\n* [`matplotlib` tutorial](https://github.com/matplotlib/AnatomyOfMatplotlib)\n\nConveying your findings convincingly is an absolutely crucial part of any analysis. Therefore, you must be able to write well and make compelling visuals. Creating informative visuals is an involved process and we won't cover that in this lab. However, part of creating informative data visualizations means generating *readable* figures. If people can't read your figures or have a difficult time interpreting them, they won't understand the results of your work. Here are some non-negotiable commandments for any plot:\n* Label $x$ and $y$ axes\n* Axes labels should be informative\n* Axes labels should be large enough to read\n* Make tick labels large enough\n* Include a legend if necessary\n* Include a title if necessary\n* Use appropriate line widths\n* Use different line styles for different lines on the plot\n* Use different markers for different lines\n\nThere are other important elements, but that list should get you started on your way.\n\nWe will work with `matplotlib` and `seaborn` for plotting in this class. `matplotlib` is a very powerful `python` library for making scientific plots. `seaborn` is a little more specialized in that it was developed for statistical data visualization. We will cover some `seaborn` later in class. In the meantime you can look at the [seaborn documentation](https://seaborn.pydata.org)\n\nFirst, let's generate some data.\n\n#### Let's plot some functions\n\nWe will use the following three functions to make some plots:\n\n* Logistic function:\n \\begin{align*}\n f\\left(z\\right) = \\dfrac{1}{1 + be^{-az}}\n \\end{align*}\n where $a$ and $b$ are parameters.\n* Hyperbolic tangent:\n \\begin{align*}\n g\\left(z\\right) = b\\tanh\\left(az\\right) + c\n \\end{align*}\n where $a$, $b$, and $c$ are parameters.\n* Rectified Linear Unit:\n \\begin{align*}\n h\\left(z\\right) = \n \\left\\{\n \\begin{array}{lr}\n z, \\quad z > 0 \\\\\n \\epsilon z, \\quad z\\leq 0\n \\end{array}\n \\right.\n \\end{align*}\n where $\\epsilon < 0$ is a small, positive parameter.\n\nYou are given the code for the first two functions. Notice that $z$ is passed in as a `numpy` array and that the functions are returned as `numpy` arrays. Parameters are passed in as floats.\n\nYou should write a function to compute the rectified linear unit. The input should be a `numpy` array for $z$ and a positive float for $\\epsilon$.\n\n\n```python\nimport numpy as np\n\ndef logistic(z: np.ndarray, a: float, b: float) -> np.ndarray:\n \"\"\" Compute logistic function\n Inputs:\n a: exponential parameter\n b: exponential prefactor\n z: numpy array; domain\n Outputs:\n f: numpy array of floats, logistic function\n \"\"\"\n \n den = 1.0 + b * np.exp(-a * z)\n return 1.0 / den\n\ndef stretch_tanh(z: np.ndarray, a: float, b: float, c: float) -> np.ndarray:\n \"\"\" Compute stretched hyperbolic tangent\n Inputs:\n a: horizontal stretch parameter (a>1 implies a horizontal squish)\n b: vertical stretch parameter\n c: vertical shift parameter\n z: numpy array; domain\n Outputs:\n g: numpy array of floats, stretched tanh\n \"\"\"\n return b * np.tanh(a * z) + c\n\ndef relu(z: np.ndarray, eps: float = 0.01) -> np.ndarray:\n \"\"\" Compute rectificed linear unit\n Inputs:\n eps: small positive parameter\n z: numpy array; domain\n Outputs:\n h: numpy array; relu\n \"\"\"\n return np.fmax(z, eps * z)\n```\n\nNow let's make some plots. First, let's just warm up and plot the logistic function.\n\n\n```python\nx = np.linspace(-5.0, 5.0, 100) # Equally spaced grid of 100 pts between -5 and 5\n\nf = logistic(x, 1.0, 1.0) # Generate data\n```\n\n\n```python\nplt.plot(x, f)\nplt.xlabel('x')\nplt.ylabel('f')\nplt.title('Logistic Function')\nplt.grid(True)\n```\n\n#### Figures with subplots\n\nLet's start thinking about the plots as objects. We have the `figure` object which is like a matrix of smaller plots named `axes`. You can use array notation when handling it. \n\n\n```python\nfig, ax = plt.subplots(1,1) # Get figure and axes objects\n#figure is an array with N amount of ax (axis) objects, arranged as a 1D or 2D array\n#ax[0,0] to get the first element in the 2D figure array or ax[0] for 1D array\n\nax.plot(x, f) # Make a plot\n\n# Create some labels\nax.set_xlabel('x')\nax.set_ylabel('f')\nax.set_title('Logistic Function')\n\n# Grid\nax.grid(True)\n```\n\nWow, it's *exactly* the same plot! Notice, however, the use of `ax.set_xlabel()` instead of `plt.xlabel()`. The difference is tiny, but you should be aware of it. I will use this plotting syntax from now on.\n\nWhat else do we need to do to make this figure better? Here are some options:\n* Make labels bigger!\n* Make line fatter\n* Make tick mark labels bigger\n* Make the grid less pronounced\n* Make figure bigger\n\nLet's get to it.\n\n\n```python\nfig, ax = plt.subplots(1,1, figsize=(10,6)) # Make figure bigger\n\n# Make line plot\nax.plot(x, f, lw=4)\n\n# Update ticklabel size\nax.tick_params(labelsize=24)\n\n# Make labels\nax.set_xlabel(r'$x$', fontsize=24) # Use TeX for mathematical rendering\nax.set_ylabel(r'$f(x)$', fontsize=24) # Use TeX for mathematical rendering\nax.set_title('Logistic Function', fontsize=24)\n\nax.grid(True, lw=1.5, ls='--', alpha=0.75)\n```\n\nNotice:\n* `lw` stands for `linewidth`. We could also write `ax.plot(x, f, linewidth=4)`\n* `ls` stands for `linestyle`.\n* `alpha` stands for transparency.\n\nThe only thing remaining to do is to change the $x$ limits. Clearly these should go from $-5$ to $5$.\n\n\n```python\n#fig.savefig('logistic.png')\n\n# Put this in a markdown cell and uncomment this to check what you saved.\n# \n```\n\n#### Resources\nIf you want to see all the styles available, please take a look at the documentation.\n* [Line styles](https://matplotlib.org/2.0.1/api/lines_api.html#matplotlib.lines.Line2D.set_linestyle)\n* [Marker styles](https://matplotlib.org/2.0.1/api/markers_api.html#module-matplotlib.markers)\n* [Everything you could ever want](https://matplotlib.org/2.0.1/api/lines_api.html#matplotlib.lines.Line2D.set_marker)\n\nWe haven't discussed it yet, but you can also put a legend on a figure. You'll do that in the next exercise. Here are some additional resources:\n* [Legend](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html)\n* [Grid](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.grid.html)\n\n`ax.legend(loc='best', fontsize=24);`\n\n
Exercise
\n\nDo the following:\n* Make a figure with the logistic function, hyperbolic tangent, and rectified linear unit.\n* Use different line styles for each plot\n* Put a legend on your figure\n\nHere's an example of a figure:\n\n\n\n```python\n# your code here\n\n# First get the data\nf = logistic(x, 2.0, 1.0)\ng = stretch_tanh(x, 2.0, 0.5, 0.5)\nh = relu(x)\n\nfig, ax = plt.subplots(1,1, figsize=(10,6)) # Create figure object\n\n# Make actual plots\n# (Notice the label argument!)\nax.plot(x, f, lw=4, ls='-', label=r'$L(x;1)$')\nax.plot(x, g, lw=4, ls='--', label=r'$\\tanh(2x)$')\nax.plot(x, h, lw=4, ls='-.', label=r'$relu(x; 0.01)$')\n\n# Make the tick labels readable\nax.tick_params(labelsize=24)\n\n# Set axes limits to make the scale nice\nax.set_xlim(x.min(), x.max())\nax.set_ylim(h.min(), 1.1)\n\n# Make readable labels\nax.set_xlabel(r'$x$', fontsize=24)\nax.set_ylabel(r'$h(x)$', fontsize=24)\nax.set_title('Activation Functions', fontsize=24)\n\n# Set up grid\nax.grid(True, lw=1.75, ls='--', alpha=0.75)\n\n# Put legend on figure\nax.legend(loc='best', fontsize=24);\n\nfig.savefig('../images/nice_plots.png')\n```\n\n
Exercise
\n\nThese figures look nice in the plot and it makes sense for comparison. Now let's put the 3 different figures in separate plots.\n\n* Make a separate plot for each figure and line them up on the same row.\n\n\n```python\n# your code here\nfig, ax = plt.subplots(1,3, figsize=(30,8)) # Create figure object (1d array)\n\n# Make actual plots\n# (Notice the label argument!)\nax[0].plot(x, f, lw=4, ls='-', label=r'$L(x;1)$')\nax[1].plot(x, g, lw=4, ls='--', label=r'$\\tanh(2x)$')\nax[2].plot(x, h, lw=4, ls='-.', label=r'$relu(x; 0.01)$')\n\nfor i in range(0,3):\n # Make the tick labels readable\n ax[i].tick_params(labelsize=24)\n\n # Set axes limits to make the scale nice\n ax[i].set_xlim(x.min(), x.max())\n ax[i].set_ylim(h.min(), 1.1)\n\n # Make readable labels\n ax[i].set_xlabel(r'$x$', fontsize=24)\n ax[i].set_ylabel(r'$h(x)$', fontsize=24)\n ax[i].set_title('Activation Functions', fontsize=24)\n\n # Set up grid\n ax[i].grid(True, lw=1.75, ls='--', alpha=0.75)\n\n```\n\n\n```python\n# %load solutions/three_subplots.py\n```\n\n
Exercise
\n\n* Make a grid of 2 x 3 separate plots, 3 will be empty. Just plot the functions and do not worry about cosmetics. We just want you ro see the functionality.\n\n\n```python\n# your code here\nfig, ax = plt.subplots(2,3, figsize=(20,8)) # Create figure object (2d array)\n# Make actual plots\n# (Notice the label argument!)\nax[0,0].plot(x, f, lw=4, ls='-', label=r'$L(x;1)$')\nax[1,1].plot(x, g, lw=4, ls='--', label=r'$\\tanh(2x)$')\nax[1,2].plot(x, h, lw=4, ls='-.', label=r'$relu(x; 0.01)$')\n\n```\n\n\n```python\n# %load solutions/six_subplots.py\n```\n\n\n## 3 - Simple Linear Regression\n\nLinear regression and its many extensions are a workhorse of the statistics and data science community, both in application and as a reference point for other models. Most of the major concepts in machine learning can be and often are discussed in terms of various linear regression models. Thus, this section will introduce you to building and fitting linear regression models and some of the process behind it, so that you can 1) fit models to data you encounter 2) experiment with different kinds of linear regression and observe their effects 3) see some of the technology that makes regression models work.\n\n\n### Linear regression with a toy dataset\nWe first examine a toy problem, focusing our efforts on fitting a linear model to a small dataset with three observations. Each observation consists of one predictor $x_i$ and one response $y_i$ for $i = 1, 2, 3$,\n\n\\begin{align*}\n(x , y) = \\{(x_1, y_1), (x_2, y_2), (x_3, y_3)\\}.\n\\end{align*}\n\nTo be very concrete, let's set the values of the predictors and responses.\n\n\\begin{equation*}\n(x , y) = \\{(1, 2), (2, 2), (3, 4)\\}\n\\end{equation*}\n\nThere is no line of the form $\\beta_0 + \\beta_1 x = y$ that passes through all three observations, since the data are not collinear. Thus our aim is to find the line that best fits these observations in the *least-squares sense*, as discussed in lecture.\n\n
Exercise (for home)
\n\n* Make two numpy arrays out of this data, x_train and y_train\n* Check the dimentions of these arrays\n* Try to reshape them into a different shape\n* Make points into a very simple scatterplot\n* Make a better scatterplot\n\n\n```python\n# your code here\n```\n\n\n```python\n# solution\nx_train = np.array([1,2,3])\ny_train = np.array([2,3,6])\ntype(x_train)\n```\n\n\n\n\n numpy.ndarray\n\n\n\n\n```python\nx_train.shape\n```\n\n\n\n\n (3,)\n\n\n\n\n```python\nx_train = x_train.reshape(3,1) #3 rows because linear regression methods do not like 1D arrays! \nx_train.shape\n```\n\n\n\n\n (3, 1)\n\n\n\n\n```python\nxx = np.array([[1,3,5],[6,2,1]])\nxx.shape\n```\n\n\n\n\n (2, 3)\n\n\n\n\n```python\nxx = xx.reshape(3,-1)\nxx\n```\n\n\n\n\n array([[1, 3],\n [5, 6],\n [2, 1]])\n\n\n\n\n```python\n# %load solutions/simple_scatterplot.py\n# Make a simple scatterplot\nplt.scatter(x_train,y_train)\n\n# check dimensions \nprint(x_train.shape,y_train.shape)\n\n```\n\n\n```python\n# %load solutions/nice_scatterplot.py\ndef nice_scatterplot(x, y, title):\n # font size\n f_size = 18\n \n # make the figure\n fig, ax = plt.subplots(1,1, figsize=(8,5)) # Create figure object\n\n # set axes limits to make the scale nice\n ax.set_xlim(np.min(x)-1, np.max(x) + 1)\n ax.set_ylim(np.min(y)-1, np.max(y) + 1)\n\n # adjust size of tickmarks in axes\n ax.tick_params(labelsize = f_size)\n \n # remove tick labels\n ax.tick_params(labelbottom=False, bottom=False)\n \n # adjust size of axis label\n ax.set_xlabel(r'$x$', fontsize = f_size)\n ax.set_ylabel(r'$y$', fontsize = f_size)\n \n # set figure title label\n ax.set_title(title, fontsize = f_size)\n\n # you may set up grid with this \n ax.grid(True, lw=1.75, ls='--', alpha=0.15)\n\n # make actual plot (Notice the label argument!)\n #ax.scatter(x, y, label=r'$my points$')\n #ax.scatter(x, y, label='$my points$')\n ax.scatter(x, y, label=r'$my\\,points$')\n ax.legend(loc='best', fontsize = f_size);\n \n return ax\n\nnice_scatterplot(x_train, y_train, 'hello nice plot')\n\n```\n\n\n#### Formulae\nLinear regression is special among the models we study because it can be solved explicitly. While most other models (and even some advanced versions of linear regression) must be solved itteratively, linear regression has a formula where you can simply plug in the data.\n\nFor the single predictor case it is:\n \\begin{align}\n \\beta_1 &= \\frac{\\sum_{i=1}^n{(x_i-\\bar{x})(y_i-\\bar{y})}}{\\sum_{i=1}^n{(x_i-\\bar{x})^2}}\\\\\n \\beta_0 &= \\bar{y} - \\beta_1\\bar{x}\\\n \\end{align}\n \nWhere $\\bar{y}$ and $\\bar{x}$ are the mean of the y values and the mean of the x values, respectively.\n\nFrom the re-aranged second equation we can see that the best-fit line passes through $(\\bar{x},\\bar{y})$, the center of mass of the data\n\nFrom any of the first equations, we can see that the slope of the line has to do with whether or not an x value that is above/below the center of mass is typically paired with a y value that is likewise above/below, or typically paired with one that is opposite.\n\n### Building a model from scratch\nIn this part, we will solve the equations for simple linear regression and find the best fit solution to our toy problem.\n\nThe snippets of code below implement the linear regression equations on the observed predictors and responses, which we'll call the training data set. Let's walk through the code.\n\nWe have to reshape our arrrays to 2D. We will see later why.\n\n
Exercise
\n\n* make an array with shape (2,3)\n* reshape it to a size that you want\n\n\n```python\n# your code here\nxx = np.array([[1,2,3],[4,6,8]])\nxxx = xx.reshape(-1,2)\nprint(xxx)\n\nprint(xxx.shape)\n\n```\n\n [[1 2]\n [3 4]\n [6 8]]\n (3, 2)\n\n\n\n```python\n# Reshape to be a proper 2D array\nx_train = x_train.reshape(x_train.shape[0], 1)\ny_train = y_train.reshape(y_train.shape[0], 1)\n\nprint(x_train.shape)\nprint(x_train)\n```\n\n (3, 1)\n [[1]\n [2]\n [3]]\n\n\n\n```python\n# first, compute means\ny_bar = np.mean(y_train)\nx_bar = np.mean(x_train)\n\n# build the two terms\nnumerator = np.sum( (x_train - x_bar)*(y_train - y_bar) )\ndenominator = np.sum((x_train - x_bar)**2)\n\nprint(numerator.shape, denominator.shape) #check shapes\n```\n\n () ()\n\n\n* Why the empty brackets? (The numerator and denominator are scalars, as expected.)\n\n\n```python\n#slope beta1\nbeta_1 = numerator/denominator\n\n#intercept beta0\nbeta_0 = y_bar - beta_1*x_bar\n\nprint(\"The best-fit line is {0:3.2f} + {1:3.2f} * x\".format(beta_0, beta_1))\nprint(f'The best fit is {beta_0}')\n```\n\n The best-fit line is -0.33 + 2.00 * x\n The best fit is -0.3333333333333335\n\n\n
Exercise
\n\nTurn the code from the above cells into a function called `simple_linear_regression_fit`, that inputs the training data and returns `beta0` and `beta1`.\n\nTo do this, copy and paste the code from the above cells below and adjust the code as needed, so that the training data becomes the input and the betas become the output.\n\n```python\ndef simple_linear_regression_fit(x_train: np.ndarray, y_train: np.ndarray) -> np.ndarray:\n \n return\n```\n\nCheck your function by calling it with the training data from above and printing out the beta values.\n\n\n```python\n# Your code here\n```\n\n\n```python\n# %load solutions/simple_linear_regression_fit.py\ndef simple_linear_regression_fit(x_train: np.ndarray, y_train: np.ndarray) -> np.ndarray:\n \"\"\"\n Inputs:\n x_train: a (num observations by 1) array holding the values of the predictor variable\n y_train: a (num observations by 1) array holding the values of the response variable\n\n Returns:\n beta_vals: a (num_features by 1) array holding the intercept and slope coeficients\n \"\"\"\n \n # Check input array sizes\n if len(x_train.shape) < 2:\n print(\"Reshaping features array.\")\n x_train = x_train.reshape(x_train.shape[0], 1)\n\n if len(y_train.shape) < 2:\n print(\"Reshaping observations array.\")\n y_train = y_train.reshape(y_train.shape[0], 1)\n\n # first, compute means\n y_bar = np.mean(y_train)\n x_bar = np.mean(x_train)\n\n # build the two terms\n numerator = np.sum( (x_train - x_bar)*(y_train - y_bar) )\n denominator = np.sum((x_train - x_bar)**2)\n \n #slope beta1\n beta_1 = numerator/denominator\n\n #intercept beta0\n beta_0 = y_bar - beta_1*x_bar\n\n return np.array([beta_0,beta_1])\n\n```\n\n* Let's run this function and see the coefficients\n\n\n```python\nx_train = np.array([1 ,2, 3])\ny_train = np.array([2, 2, 4])\n\nbetas = simple_linear_regression_fit(x_train, y_train)\n\nbeta_0 = betas[0]\nbeta_1 = betas[1]\n\nprint(\"The best-fit line is {0:8.6f} + {1:8.6f} * x\".format(beta_0, beta_1))\n```\n\n Reshaping features array.\n Reshaping observations array.\n The best-fit line is 0.666667 + 1.000000 * x\n\n\n
Exercise
\n\n* Do the values of `beta0` and `beta1` seem reasonable?\n* Plot the training data using a scatter plot.\n* Plot the best fit line with `beta0` and `beta1` together with the training data.\n\n\n```python\n# Your code here\n```\n\n\n```python\n# %load solutions/best_fit_scatterplot.py\nfig_scat, ax_scat = plt.subplots(1,1, figsize=(10,6))\n\n# Plot best-fit line\nx_train = np.array([[1, 2, 3]]).T #transpose? equivalent to xtrain.reshape(xtrain.shape[0],1)\n\nbest_fit = beta_0 + beta_1 * x_train #(B0 * 1 + B1 * X = Y)\n\nax_scat.scatter(x_train, y_train, s=300, label='Training Data')\nax_scat.plot(x_train, best_fit, ls='--', label='Best Fit Line')\n\nax_scat.set_xlabel(r'$x_{train}$', fontsize = 24)\nax_scat.set_ylabel(r'$y$',fontsize = 24);\n\n```\n\nThe values of `beta0` and `beta1` seem roughly reasonable. They capture the positive correlation. The line does appear to be trying to get as close as possible to all the points.\n\n\n## 4 - Building a model with `statsmodels` and `sklearn`\n\nNow that we can concretely fit the training data from scratch, let's learn two `python` packages to do it all for us:\n* [statsmodels](http://www.statsmodels.org/stable/regression.html) and \n* [scikit-learn (sklearn)](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html).\n\nOur goal is to show how to implement simple linear regression with these packages. For an important sanity check, we compare the $\\beta$ values from `statsmodels` and `sklearn` to the $\\beta$ values that we found from above with our own implementation.\n\nFor the purposes of this lab, `statsmodels` and `sklearn` do the same thing. More generally though, `statsmodels` tends to be easier for inference \\[finding the values of the slope and intercept and dicussing uncertainty in those values\\], whereas `sklearn` has machine-learning algorithms and is better for prediction \\[guessing y values for a given x value\\]. (Note that both packages make the same guesses, it's just a question of which activity they provide more support for.\n\n**Note:** `statsmodels` and `sklearn` are different packages! Unless we specify otherwise, you can use either one.\n\nBelow is the code for `statsmodels`. `Statsmodels` does not by default include the column of ones in the $X$ matrix, so we include it manually with `sm.add_constant`.\n\n\n```python\nimport statsmodels.api as sm\n```\n\n\n```python\n# create the X matrix by appending a column of ones to x_train (B0 * 1 + B1 * X = Y)\nX = sm.add_constant(x_train)\n\n# this is the same matrix as in our scratch problem!\nprint(X)\n\n# build the OLS model (ordinary least squares) from the training data\ntoyregr_sm = sm.OLS(y_train, X)\n\n# do the fit and save regression info (parameters, etc) in results_sm\nresults_sm = toyregr_sm.fit()\n\n# pull the beta parameters out from results_sm\nbeta0_sm = results_sm.params[0]\nbeta1_sm = results_sm.params[1]\n\nprint(f'The regression coef from statsmodels are: beta_0 = {beta0_sm:8.6f} and beta_1 = {beta1_sm:8.6f}')\n```\n\n [[1. 1.]\n [1. 2.]\n [1. 3.]]\n The regression coef from statsmodels are: beta_0 = 0.666667 and beta_1 = 1.000000\n\n\nBesides the beta parameters, `results_sm` contains a ton of other potentially useful information.\n\n\n```python\nimport warnings\nwarnings.filterwarnings('ignore')\nprint(results_sm.summary())\n```\n\n OLS Regression Results \n ==============================================================================\n Dep. Variable: y R-squared: 0.750\n Model: OLS Adj. R-squared: 0.500\n Method: Least Squares F-statistic: 3.000\n Date: Thu, 19 Sep 2019 Prob (F-statistic): 0.333\n Time: 21:42:53 Log-Likelihood: -2.0007\n No. Observations: 3 AIC: 8.001\n Df Residuals: 1 BIC: 6.199\n Df Model: 1 \n Covariance Type: nonrobust \n ==============================================================================\n coef std err t P>|t| [0.025 0.975]\n ------------------------------------------------------------------------------\n const 0.6667 1.247 0.535 0.687 -15.181 16.514\n x1 1.0000 0.577 1.732 0.333 -6.336 8.336\n ==============================================================================\n Omnibus: nan Durbin-Watson: 3.000\n Prob(Omnibus): nan Jarque-Bera (JB): 0.531\n Skew: -0.707 Prob(JB): 0.767\n Kurtosis: 1.500 Cond. No. 6.79\n ==============================================================================\n \n Warnings:\n [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n\n\nNow let's turn our attention to the `sklearn` library.\n\n\n```python\nfrom sklearn import linear_model\n```\n\n\n```python\n# build the least squares model\ntoyregr = linear_model.LinearRegression()\n\n# save regression info (parameters, etc) in results_skl\nresults = toyregr.fit(x_train, y_train)\n\n# pull the beta parameters out from results_skl\nbeta0_sk = toyregr.intercept_\nbeta1_sk = toyregr.coef_[0]\n\nprint(f'The regression coef from sklearn are: beta_0 = {beta0_sk} and beta_1 = {beta1_sk}')\n#print(\"The regression coefficients from the sklearn package are: beta_0 = {0:8.6f} and beta_1 = {1:8.6f}\".format(beta0_sk, beta1_sk))\n```\n\nWe should feel pretty good about ourselves now, and we're ready to move on to a real problem!\n\n### The `scikit-learn` library and the shape of things\n\nBefore diving into a \"real\" problem, let's discuss more of the details of `sklearn`.\n\n`Scikit-learn` is the main `Python` machine learning library. It consists of many learners which can learn models from data, as well as a lot of utility functions such as `train_test_split()`. \n\nUse the following to add the library into your code:\n\n```python\nimport sklearn \n```\n\nIn `scikit-learn`, an **estimator** is a Python object that implements the methods `fit(X, y)` and `predict(T)`\n\nLet's see the structure of `scikit-learn` needed to make these fits. `fit()` always takes two arguments:\n```python\nestimator.fit(Xtrain, ytrain)\n```\nWe will consider two estimators in this lab: `LinearRegression` and `KNeighborsRegressor`.\n\nIt is very important to understand that `Xtrain` must be in the form of a **2x2 array** with each row corresponding to one sample, and each column corresponding to the feature values for that sample.\n\n`ytrain` on the other hand is a simple array of responses. These are continuous for regression problems.\n\n\n\n\n\n### Practice with `sklearn` and a real dataset\nWe begin by loading up the `mtcars` dataset. This data was extracted from the 1974 Motor Trend US magazine, and comprises of fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). We will load this data to a dataframe with 32 observations on 11 (numeric) variables. Here is an explanation of the features:\n\n- `mpg` is Miles/(US) gallon \n- `cyl` is Number of cylinders, \n- `disp` is\tDisplacement (cu.in.), \n- `hp` is\tGross horsepower, \n- `drat` is\tRear axle ratio, \n- `wt` is the Weight (1000 lbs), \n- `qsec` is 1/4 mile time,\n- `vs` is Engine (0 = V-shaped, 1 = straight), \n- `am` is Transmission (0 = automatic, 1 = manual), \n- `gear` is the Number of forward gears, \n- `carb` is\tNumber of carburetors.\n\n\n```python\nimport pandas as pd\n\n#load mtcars\ndfcars = pd.read_csv(\"../data/mtcars.csv\")\ndfcars.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Unnamed: 0mpgcyldisphpdratwtqsecvsamgearcarb
0Mazda RX421.06160.01103.902.62016.460144
1Mazda RX4 Wag21.06160.01103.902.87517.020144
2Datsun 71022.84108.0933.852.32018.611141
3Hornet 4 Drive21.46258.01103.083.21519.441031
4Hornet Sportabout18.78360.01753.153.44017.020032
\n
\n\n\n\n\n```python\n# Fix the column title \ndfcars = dfcars.rename(columns={\"Unnamed: 0\":\"car name\"})\ndfcars.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
car namempgcyldisphpdratwtqsecvsamgearcarb
0Mazda RX421.06160.01103.902.62016.460144
1Mazda RX4 Wag21.06160.01103.902.87517.020144
2Datsun 71022.84108.0933.852.32018.611141
3Hornet 4 Drive21.46258.01103.083.21519.441031
4Hornet Sportabout18.78360.01753.153.44017.020032
\n
\n\n\n\n\n```python\ndfcars.shape\n```\n\n\n\n\n (32, 12)\n\n\n\n#### Searching for values: how many cars have 4 gears?\n\n\n```python\nlen(dfcars[dfcars.gear == 4].drop_duplicates(subset='car name', keep='first'))\n```\n\n\n\n\n 12\n\n\n\nNext, let's split the dataset into a training set and test set.\n\n\n```python\n# split into training set and testing set\nfrom sklearn.model_selection import train_test_split\n\n#set random_state to get the same split every time\ntraindf, testdf = train_test_split(dfcars, test_size=0.2, random_state=42)\n```\n\n\n```python\n# testing set is around 20% of the total data; training set is around 80%\nprint(\"Shape of full dataset is: {0}\".format(dfcars.shape))\nprint(\"Shape of training dataset is: {0}\".format(traindf.shape))\nprint(\"Shape of test dataset is: {0}\".format(testdf.shape))\n```\n\n Shape of full dataset is: (32, 12)\n Shape of training dataset is: (25, 12)\n Shape of test dataset is: (7, 12)\n\n\nNow we have training and test data. We still need to select a predictor and a response from this dataset. Keep in mind that we need to choose the predictor and response from both the training and test set. You will do this in the exercises below. However, we provide some starter code for you to get things going.\n\n\n```python\ntraindf.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
car namempgcyldisphpdratwtqsecvsamgearcarb
25Fiat X1-927.3479.0664.081.93518.901141
12Merc 450SL17.38275.81803.073.73017.600033
0Mazda RX421.06160.01103.902.62016.460144
4Hornet Sportabout18.78360.01753.153.44017.020032
16Chrysler Imperial14.78440.02303.235.34517.420034
\n
\n\n\n\n\n```python\n# Extract the response variable that we're interested in\ny_train = traindf.mpg\n#y_train = traindf.iloc[:,1] #with slicing\ny_train\n```\n\n\n\n\n 25 27.3\n 12 17.3\n 0 21.0\n 4 18.7\n 16 14.7\n 5 18.1\n 13 15.2\n 11 16.4\n 23 13.3\n 1 21.0\n 2 22.8\n 26 26.0\n 3 21.4\n 21 15.5\n 27 30.4\n 22 15.2\n 18 30.4\n 31 21.4\n 20 21.5\n 7 24.4\n 10 17.8\n 14 10.4\n 28 15.8\n 19 33.9\n 6 14.3\n Name: mpg, dtype: float64\n\n\n\n
Exercise
\n\nUse slicing to get the same vector `y_train`\n\n----\n\nNow, notice the shape of `y_train`.\n\n\n```python\ny_train.shape, type(y_train) #vector with 25 elements, 1D\n```\n\n\n\n\n ((25,), pandas.core.series.Series)\n\n\n\n### Array reshape\nThis is a 1D array as should be the case with the **Y** array. Remember, `sklearn` requires a 2D array only for the predictor array. You will have to pay close attention to this in the exercises later. `Sklearn` doesn't care too much about the shape of `y_train`.\n\nThe whole reason we went through that whole process was to show you how to reshape your data into the correct format.\n\n**IMPORTANT:** Remember that your response variable `ytrain` can be a vector but your predictor variable `xtrain` ***must*** be an array!\n\n\n## 5 - Example: Simple linear regression with automobile data\nWe will now use `sklearn` to predict automobile mileage per gallon (mpg) and evaluate these predictions. We already loaded the data and split them into a training set and a test set.\n\nWe need to choose the variables that we think will be good predictors for the dependent variable `mpg`. \n\n
Exercise in pairs
\n\n* Pick one variable to use as a predictor for simple linear regression. Discuss your reasons with the person next to you. \n* Justify your choice with some visualizations. \n* Is there a second variable you'd like to use? For example, we're not doing multiple linear regression here, but if we were, is there another variable you'd like to include if we were using two predictors?\n\n\n```python\nx_wt = dfcars.wt\nx_wt.shape\n```\n\n\n\n\n (32,)\n\n\n\n\n```python\n# Your code here\nx_hp = dfcars['hp']\nx_hp.shape\n\nfig, ax = plt.subplots(1,2, figsize=(10,5)) # Create figure object\n\nax[0].scatter(dfcars['hp'], dfcars['mpg'])\nax[0].set_xlabel('hp')\nax[0].set_ylabel('mpg')\n\nax[1].scatter(dfcars['wt'], dfcars['mpg'])\nax[1].set_xlabel('wt')\n```\n\n\n```python\n# %load solutions/cars_simple_EDA.py\ny_mpg = dfcars.mpg\nx_wt = dfcars.wt\nx_hp = dfcars.hp\n\nfig_wt, ax_wt = plt.subplots(1,1, figsize=(10,6))\nax_wt.scatter(x_wt, y_mpg)\nax_wt.set_xlabel(r'Car Weight')\nax_wt.set_ylabel(r'Car MPG')\n\nfig_hp, ax_hp = plt.subplots(1,1, figsize=(10,6))\nax_hp.scatter(x_hp, y_mpg)\nax_hp.set_xlabel(r'Car HP')\nax_hp.set_ylabel(r'Car MPG')\n\n```\n\n
Exercise
\n\n* Use `sklearn` to fit the training data using simple linear regression.\n* Use the model to make mpg predictions on the test set. \n* Plot the data and the prediction. \n* Print out the mean squared error for the training set and the test set and compare.\n\n\n```python\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\ndfcars = pd.read_csv(\"../data/mtcars.csv\")\ndfcars = dfcars.rename(columns={\"Unnamed: 0\":\"name\"})\n\ndfcars.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
namempgcyldisphpdratwtqsecvsamgearcarb
0Mazda RX421.06160.01103.902.62016.460144
1Mazda RX4 Wag21.06160.01103.902.87517.020144
2Datsun 71022.84108.0933.852.32018.611141
3Hornet 4 Drive21.46258.01103.083.21519.441031
4Hornet Sportabout18.78360.01753.153.44017.020032
\n
\n\n\n\n\n```python\ntraindf, testdf = train_test_split(dfcars, test_size=0.2, random_state=42)\n\ny_train = np.array(traindf.mpg) #pick your response\nX_train = np.array(traindf.wt) #pick your predictor \nX_train = X_train.reshape(X_train.shape[0], 1) #reshape into 25,1 from 25, your predictor only\n```\n\n\n```python\n#same as above for the test\ny_test = np.array(testdf.mpg)\nX_test = np.array(testdf.wt)\nX_test = X_test.reshape(X_test.shape[0], 1) #reshape into 7,1 from 7,\n```\n\n\n```python\n# Let's take another look at our data\ndfcars.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
namempgcyldisphpdratwtqsecvsamgearcarb
0Mazda RX421.06160.01103.902.62016.460144
1Mazda RX4 Wag21.06160.01103.902.87517.020144
2Datsun 71022.84108.0933.852.32018.611141
3Hornet 4 Drive21.46258.01103.083.21519.441031
4Hornet Sportabout18.78360.01753.153.44017.020032
\n
\n\n\n\n\n```python\n# And out train and test sets \ny_train.shape, X_train.shape\n```\n\n\n\n\n ((25,), (25, 1))\n\n\n\n\n```python\ny_test.shape, X_test.shape\n```\n\n\n\n\n ((7,), (7, 1))\n\n\n\n\n```python\n#create linear model\nregression = LinearRegression()\n\n#fit linear model\nregression.fit(X_train, y_train) #fit with training data \n\npredicted_y = regression.predict(X_test) #run on test data\n\nr2 = regression.score(X_test, y_test) #use test data to calculate r2\nprint(f'R^2 = {r2:.5}') #specify decimal place with .X\n```\n\n R^2 = 0.68798\n\n\n\n```python\nprint(f'R^2 on training data is {regression.score(X_train, y_train)}')\n\nprint(f'MSE for test data is {mean_squared_error(predicted_y, y_test)}') #compare test data y with predicted y\nprint(f'MSE for training data is {mean_squared_error(regression.predict(X_train),y_train)}') #compare train data y with predicted y\n\nprint('Coefficients: \\n', regression.coef_[0], regression.intercept_)\n```\n\n R^2 on training data is 0.7701379909791617\n MSE for test data is 12.475985659918837\n MSE for training data is 7.773697766387512\n Coefficients: \n -5.336941400557081 36.93731031351841\n\n\n\n```python\nfig, ax = plt.subplots(1,1, figsize=(10,6))\nax.plot(y_test, predicted_y, 'o') #plot observed y in test data vs predicted y using x from test data\ngrid = np.linspace(np.min(dfcars.mpg), np.max(dfcars.mpg), 100)\nax.plot(grid, grid, color=\"black\") # 45 degree line\nax.set_xlabel(\"actual y\")\nax.set_ylabel(\"predicted y\")\n\nfig1, ax1 = plt.subplots(1,1, figsize=(10,6))\nax1.plot(dfcars.wt, dfcars.mpg, 'o') #plot all observed data: wt of car vs mpg of car\nxgrid = np.linspace(np.min(dfcars.wt), np.max(dfcars.wt), 100) #give x-values for regression fit \nax1.plot(xgrid, regression.predict(xgrid.reshape(100, 1))) #plot fitted regression line over all the data \n```\n\n\n## 6 - $k$-nearest neighbors\n\nNow that you're familiar with `sklearn`, you're ready to do a KNN regression. \n\nSklearn's regressor is called `sklearn.neighbors.KNeighborsRegressor`. Its main parameter is the `number of nearest neighbors`. There are other parameters such as the distance metric (default for 2 order is the Euclidean distance). For a list of all the parameters see the [Sklearn kNN Regressor Documentation](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsRegressor.html).\n\nLet's use $5$ nearest neighbors.\n\n\n```python\n# Import the library\nfrom sklearn.neighbors import KNeighborsRegressor\n```\n\n\n```python\n# Set number of neighbors\nk = 5\nknnreg = KNeighborsRegressor(n_neighbors=k)\n```\n\n\n```python\n# Fit the regressor - make sure your numpy arrays are the right shape\nknnreg.fit(X_train, y_train)\nprint(X_train.shape, y_train.shape)\n\n# Evaluate the outcome on the train set using R^2\nr2_train = knnreg.score(X_train, y_train)\n\n# Print results\nprint(f'kNN model with {k} neighbors gives R^2 on the train set: {r2_train:.5}')\n```\n\n (25, 1) (25,)\n kNN model with 5 neighbors gives R^2 on the train set: 0.87181\n\n\n\n```python\nknnreg.predict(X_test) #X_test has 7 values and you are predicted 7 y values using kNN with 5 neighbors\n```\n\n\n\n\n array([20.14, 14. , 15.3 , 26.3 , 19.56, 17.06, 16.88])\n\n\n\n
Exercise
\n\nCalculate and print the $R^{2}$ score on the test set\n\n\n```python\n# Your code here\n# Evaluate the outcome on the train set using R^2\nr2_test = knnreg.score(X_test, y_test)\n\n# Print results\nprint(f'kNN model with {k} neighbors gives R^2 on the train set: {r2_test:.5}')\n```\n\n kNN model with 5 neighbors gives R^2 on the train set: 0.69922\n\n\nNot so good? Lets vary the number of neighbors and see what we get.\n\n\n```python\n# Make our lives easy by storing the different regressors in a dictionary\nregdict = {}\n\n# Make our lives easier by entering the k values from a list\nk_list = [1, 2, 4, 15]\n\n# Do a bunch of KNN regressions\nfor k in k_list:\n knnreg = KNeighborsRegressor(n_neighbors=k)\n knnreg.fit(X_train, y_train)\n # Store the regressors in a dictionary\n regdict[k] = knnreg \n\n# Print the dictionary to see what we have\nregdict\n```\n\n\n\n\n {1: KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=None, n_neighbors=1, p=2,\n weights='uniform'),\n 2: KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=None, n_neighbors=2, p=2,\n weights='uniform'),\n 4: KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=None, n_neighbors=4, p=2,\n weights='uniform'),\n 15: KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',\n metric_params=None, n_jobs=None, n_neighbors=15, p=2,\n weights='uniform')}\n\n\n\nNow let's plot all the k values in same plot.\n\n\n```python\nfig, ax = plt.subplots(1,1, figsize=(10,6))\n\nax.plot(dfcars.wt, dfcars.mpg, 'o', label=\"data\")\n\nxgrid = np.linspace(np.min(dfcars.wt), np.max(dfcars.wt), 100)\n\n# let's unpack the dictionary to its elements (items) which is the k and Regressor\nfor k, regressor in regdict.items():\n predictions = regressor.predict(xgrid.reshape(-1,1)) \n ax.plot(xgrid, predictions, label=\"{}-NN\".format(k), alpha =0.5)\n\nax.legend();\n```\n\n
Exercise
\n\nExplain what you see in the graph. **Hint** Notice how the $1$-NN goes through every point on the training set but utterly fails elsewhere. \n\nLets look at the scores on the training set.\n\n\n```python\nks = range(1, 15) # Grid of k's\nscores_train = [] # R2 scores\nfor k in ks:\n # Create KNN model\n knnreg = KNeighborsRegressor(n_neighbors=k) \n \n # Fit the model to training data\n knnreg.fit(X_train, y_train) \n \n # Calculate R^2 score for training data \n score_train = knnreg.score(X_train, y_train) \n scores_train.append(score_train)\n\n# Plot\nfig, ax = plt.subplots(1,1, figsize=(12,8))\nax.plot(ks, scores_train,'o-')\nax.set_xlabel(r'$k$')\nax.set_ylabel(r'$R^{2}$')\n```\n\n
Exercise
\n\n* Why do we get a perfect $R^2$ at k=1 for the training set?\n* Make the same plot as above on the *test* set.\n* What is the best $k$?\n\n\n```python\n# Your code here\nks = range(1, 8) # Grid of k's\nscores_test = [] # R2 scores\n\nfor k in ks:\n # Create KNN model\n knnreg = KNeighborsRegressor(n_neighbors=k) \n \n # Fit the model to training data\n knnreg.fit(X_train, y_train) \n \n # Calculate R^2 score using test data\n score_test = knnreg.score(X_test, y_test) \n scores_test.append(score_test)\n\n# Plot\nfig, ax = plt.subplots(1,1, figsize=(12,8))\nax.plot(ks, scores_test,'o-')\nax.set_xlabel(r'$k$')\nax.set_ylabel(r'$R^{2}$')\n\n```\n\n\n```python\n# %load solutions/knn_regression.py\nks = range(1, 7) # Grid of k's\nscores_test = [] # R2 scores\nfor k in ks:\n knnreg = KNeighborsRegressor(n_neighbors=k) # Create KNN model\n knnreg.fit(X_train, y_train) # Fit the model to training data\n score_test = knnreg.score(X_test, y_test) # Calculate R^2 score\n scores_test.append(score_test)\n\n# Plot\nfig, ax = plt.subplots(1,1, figsize=(12,8))\nax.plot(ks, scores_test,'o-', ms=12)\nax.set_xlabel(r'$k$')\nax.set_ylabel(r'$R^{2}$')\n\n```\n\n\n```python\n# solution to previous exercise\nr2_test = knnreg.score(X_test, y_test)\nprint(f'kNN model with {k} neighbors gives R^2 on the test set: {r2_test:.5}')\n```\n\n kNN model with 6 neighbors gives R^2 on the test set: 0.63189\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "5ac6d3c73d0febf961893a91c78e1ac372e539ee", "size": 568220, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "content/labs/lab03/notebook/cs109a_lab3_kNN_SLR_matplot_JAZ.ipynb", "max_stars_repo_name": "jamilla-az/2019-CS109A", "max_stars_repo_head_hexsha": "e5414f574841350b7ec0604e6d0ec288ea0e8f6d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "content/labs/lab03/notebook/cs109a_lab3_kNN_SLR_matplot_JAZ.ipynb", "max_issues_repo_name": "jamilla-az/2019-CS109A", "max_issues_repo_head_hexsha": "e5414f574841350b7ec0604e6d0ec288ea0e8f6d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "content/labs/lab03/notebook/cs109a_lab3_kNN_SLR_matplot_JAZ.ipynb", "max_forks_repo_name": "jamilla-az/2019-CS109A", "max_forks_repo_head_hexsha": "e5414f574841350b7ec0604e6d0ec288ea0e8f6d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 145.4363962119, "max_line_length": 71596, "alphanum_fraction": 0.8653180106, "converted": true, "num_tokens": 19399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6548947223065755, "lm_q1q2_score": 0.34023177187216097}} {"text": "# LSTM for Part-of-Speech Tagging\n\nIn this section, we will use an LSTM to predict part-of-speech tags for words. What exactly is part-of-speech tagging?\n\nPart of speech tagging is the process of determining the *category* of a word from the words in its surrounding context. You can think of part of speech tagging as a way to go from words to their [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs#Format) categories. Mad Libs are incomplete short stories that have many words replaced by blanks. Each blank has a specified word-category, such as `\"noun\"`, `\"verb\"`, `\"adjective\"`, and so on. One player asks another to fill in these blanks (prompted only by the word-category) until they have created a complete, silly story of their own. Here is an example of such categories:\n\n```text\nToday, you'll be learning how to [verb]. It may be a [adjective] process, but I think it will be rewarding! \nIf you want to take a break you should [verb] and treat yourself to some [plural noun].\n```\n... and a set of possible words that fall into those categories:\n```text\nToday, you'll be learning how to code. It may be a challenging process, but I think it will be rewarding! \nIf you want to take a break you should stretch and treat yourself to some puppies.\n```\n\n\n### Why Tag Speech?\n\nTagging parts of speech is often used to help disambiguate natural language phrases because it can be done quickly and with high accuracy. It can help answer: what subject is someone talking about? Tagging can be used for many NLP tasks like creating new sentences using a sequence of tags that make sense together, filling in a Mad Libs style game, and determining correct pronunciation during speech synthesis. It is also used in information retrieval, and for word disambiguation (ex. determining when someone says *right* like the direction versus *right* like \"that's right!\").\n\n---\n\n\n### Preparing the Data\n\nNow, we know that neural networks do not do well with words as input and so our first step will be to prepare our training data and map each word to a numerical value. \n\nWe start by creating a small set of training data, you can see that this is a few simple sentences broken down into a list of words and their corresponding word-tags. Note that the sentences are turned into lowercase words using `lower()` and then split into separate words using `split()`, which splits the sentence by whitespace characters.\n\n#### Words to indices\n\nThen, from this training data, we create a dictionary that maps each unique word in our vocabulary to a numerical value; a unique index `idx`. We do the same for each word-tag, for example: a noun will be represented by the number `1`.\n\n\n```python\n# import resources\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n```\n\n\n```python\n# training sentences and their corresponding word-tags\ntraining_data = [\n (\"The cat ate the cheese\".lower().split(), [\"DET\", \"NN\", \"V\", \"DET\", \"NN\"]),\n (\"She read that book\".lower().split(), [\"NN\", \"V\", \"DET\", \"NN\"]),\n (\"The dog loves art\".lower().split(), [\"DET\", \"NN\", \"V\", \"NN\"]),\n (\"The elephant answers the phone\".lower().split(), [\"DET\", \"NN\", \"V\", \"DET\", \"NN\"])\n]\n\n# create a dictionary that maps words to indices\nword2idx = {}\nfor sent, tags in training_data:\n for word in sent:\n if word not in word2idx:\n word2idx[word] = len(word2idx)\n\n# create a dictionary that maps tags to indices\ntag2idx = {\"DET\": 0, \"NN\": 1, \"V\": 2}\n```\n\nNext, print out the created dictionary to see the words and their numerical values! \n\nYou should see every word in our training set and its index value. Note that the word \"the\" only appears once because our vocabulary only includes *unique* words.\n\n\n```python\n# print out the created dictionary\nprint(word2idx)\n```\n\n {'the': 0, 'cat': 1, 'ate': 2, 'cheese': 3, 'she': 4, 'read': 5, 'that': 6, 'book': 7, 'dog': 8, 'loves': 9, 'art': 10, 'elephant': 11, 'answers': 12, 'phone': 13}\n\n\n\n```python\nimport numpy as np\n\n# a helper function for converting a sequence of words to a Tensor of numerical values\n# will be used later in training\ndef prepare_sequence(seq, to_idx):\n '''This function takes in a sequence of words and returns a \n corresponding Tensor of numerical values (indices for each word).'''\n idxs = [to_idx[w] for w in seq]\n idxs = np.array(idxs)\n return torch.from_numpy(idxs).long()\n\n```\n\n\n```python\n# check out what prepare_sequence does for one of our training sentences:\nexample_input = prepare_sequence(\"The dog answers the phone\".lower().split(), word2idx)\nprint(example_input)\n```\n\n tensor([ 0, 8, 12, 0, 13], dtype=torch.int32)\n\n\n---\n## Creating the Model\n\nOur model will assume a few things:\n1. Our input is broken down into a sequence of words, so a sentence will be [w1, w2, ...]\n2. These words come from a larger list of words that we already know (a vocabulary)\n3. We have a limited set of tags, `[NN, V, DET]`, which mean: a noun, a verb, and a determinant (words like \"the\" or \"that\"), respectively\n4. We want to predict\\* a tag for each input word\n\n\\* To do the prediction, we will pass an LSTM over a test sentence and apply a softmax function to the hidden state of the LSTM; the result is a vector of tag scores from which we can get the predicted tag for a word based on the *maximum* value in this distribution of tag scores. \n\nMathematically, we can represent any tag prediction $\\hat{y}_i$ as: \n\n\\begin{align}\\hat{y}_i = \\text{argmax}_j \\ (\\log \\text{Softmax}(Ah_i + b))_j\\end{align}\n\nWhere $A$ is a learned weight and $b$, a learned bias term, and the hidden state at timestep $i$ is $h_i$. \n\n\n### Word embeddings\n\nWe know that an LSTM takes in an expected input size and hidden_dim, but sentences are rarely of a consistent size, so how can we define the input of our LSTM?\n\nWell, at the very start of this net, we'll create an `Embedding` layer that takes in the size of our vocabulary and returns a vector of a specified size, `embedding_dim`, for each word in an input sequence of words. It's important that this be the first layer in this net. You can read more about this embedding layer in [the PyTorch documentation](https://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html#word-embeddings-in-pytorch).\n\nPictured below is the expected architecture for this tagger model.\n\n\n\n\n\n```python\nclass LSTMTagger(nn.Module):\n\n def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):\n ''' Initialize the layers of this model.'''\n super(LSTMTagger, self).__init__()\n \n self.hidden_dim = hidden_dim\n\n # embedding layer that turns words into a vector of a specified size\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n\n # the LSTM takes embedded word vectors (of a specified size) as inputs \n # and outputs hidden states of size hidden_dim\n self.lstm = nn.LSTM(embedding_dim, hidden_dim)\n\n # the linear layer that maps the hidden state output dimension \n # to the number of tags we want as output, tagset_size (in this case this is 3 tags)\n self.hidden2tag = nn.Linear(hidden_dim, tagset_size)\n \n # initialize the hidden state (see code below)\n self.hidden = self.init_hidden()\n\n \n def init_hidden(self):\n ''' At the start of training, we need to initialize a hidden state;\n there will be none because the hidden state is formed based on perviously seen data.\n So, this function defines a hidden state with all zeroes and of a specified size.'''\n # The axes dimensions are (n_layers, batch_size, hidden_dim)\n return (torch.zeros(1, 1, self.hidden_dim),\n torch.zeros(1, 1, self.hidden_dim))\n\n def forward(self, sentence):\n ''' Define the feedforward behavior of the model.'''\n # create embedded word vectors for each word in a sentence\n embeds = self.word_embeddings(sentence)\n \n # get the output and hidden state by passing the lstm over our word embeddings\n # the lstm takes in our embeddings and hiddent state\n lstm_out, self.hidden = self.lstm(\n embeds.view(len(sentence), 1, -1), self.hidden)\n \n # get the scores for the most likely tag for a word\n tag_outputs = self.hidden2tag(lstm_out.view(len(sentence), -1))\n tag_scores = F.log_softmax(tag_outputs, dim=1)\n \n return tag_scores\n\n```\n\n## Define how the model trains\n\nTo train the model, we have to instantiate it and define the loss and optimizers that we want to use.\n\nFirst, we define the size of our word embeddings. The `EMBEDDING_DIM` defines the size of our word vectors for our simple vocabulary and training set; we will keep them small so we can see how the weights change as we train.\n\n**Note: the embedding dimension for a complex dataset will usually be much larger, around 64, 128, or 256 dimensional.**\n\n\n#### Loss and Optimization\n\nSince our LSTM outputs a series of tag scores with a softmax layer, we will use `NLLLoss`. In tandem with a softmax layer, NLL Loss creates the kind of cross entropy loss that we typically use for analyzing a distribution of class scores. We'll use standard gradient descent optimization, but you are encouraged to play around with other optimizers!\n\n\n```python\n# the embedding dimension defines the size of our word vectors\n# for our simple vocabulary and training set, we will keep these small\nEMBEDDING_DIM = 6\nHIDDEN_DIM = 6\n\n# instantiate our model\nmodel = LSTMTagger(EMBEDDING_DIM, HIDDEN_DIM, len(word2idx), len(tag2idx))\n\n# define our loss and optimizer\nloss_function = nn.NLLLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.1)\n\n```\n\nJust to check that our model has learned something, let's first look at the scores for a sample test sentence *before* our model is trained. Note that the test sentence *must* be made of words from our vocabulary otherwise its words cannot be turned into indices.\n\nThe scores should be Tensors of length 3 (tagsize) and there should be scores for each word in the input sentence.\n\nFor the test sentence, \"The cheese loves the elephant\", we know that this has the tags (DET, NN, V, DET, NN) or `[0, 1, 2, 0, 1]`, but our network does not yet know this. In fact, in this case, our model starts out with a hidden state of all zeroes and so all the scores and the predicted tags should be low, random, and about what you'd expect for a network that is not yet trained!\n\n\n```python\ntest_sentence = \"The cheese loves the elephant\".lower().split()\n\n# see what the scores are before training\n# element [i,j] of the output is the *score* for tag j for word i.\n# to check the initial accuracy of our model, we don't need to train, so we use model.eval()\ninputs = prepare_sequence(test_sentence, word2idx)\ninputs = inputs\ntag_scores = model(inputs)\nprint(tag_scores)\n\n# tag_scores outputs a vector of tag scores for each word in an inpit sentence\n# to get the most likely tag index, we grab the index with the maximum score!\n# recall that these numbers correspond to tag2idx = {\"DET\": 0, \"NN\": 1, \"V\": 2}\n_, predicted_tags = torch.max(tag_scores, 1)\nprint('\\n')\nprint('Predicted tags: \\n',predicted_tags)\n```\n\n tensor([[-1.3213, -1.1293, -0.8917],\n [-1.3644, -1.0807, -0.9036],\n [-1.3718, -1.0844, -0.8959],\n [-1.3461, -1.1323, -0.8735],\n [-1.3043, -1.1061, -0.9218]], grad_fn=)\n \n \n Predicted tags: \n tensor([2, 2, 2, 2, 2])\n\n\n---\n## Train the Model\n\nLoop through all our training data for multiple epochs (again we are using a small epoch value for this simple training data). This loop:\n\n1. Prepares our model for training by zero-ing the gradients\n2. Initializes the hidden state of our LSTM\n3. Prepares our data for training\n4. Runs a forward pass on our inputs to get tag_scores\n5. Calculates the loss between tag_scores and the true tag\n6. Updates the weights of our model using backpropagation\n\nIn this example, we are printing out the average epoch loss, every 20 epochs; you should see it decrease over time.\n\n\n```python\n# normally these epochs take a lot longer \n# but with our toy data (only 3 sentences), we can do many epochs in a short time\nn_epochs = 300\n\nfor epoch in range(n_epochs):\n \n epoch_loss = 0.0\n \n # get all sentences and corresponding tags in the training data\n for sentence, tags in training_data:\n \n # zero the gradients\n model.zero_grad()\n\n # zero the hidden state of the LSTM, this detaches it from its history\n model.hidden = model.init_hidden()\n\n # prepare the inputs for processing by out network, \n # turn all sentences and targets into Tensors of numerical indices\n sentence_in = prepare_sequence(sentence, word2idx)\n targets = prepare_sequence(tags, tag2idx)\n\n # forward pass to get tag scores\n tag_scores = model(sentence_in)\n\n # compute the loss, and gradients \n loss = loss_function(tag_scores, targets)\n epoch_loss += loss.item()\n loss.backward()\n \n # update the model parameters with optimizer.step()\n optimizer.step()\n \n # print out avg loss per 20 epochs\n if(epoch%20 == 19):\n print(\"Epoch: %d, loss: %1.5f\" % (epoch+1, epoch_loss/len(training_data)))\n\n```\n\n Epoch: 20, loss: 0.96322\n Epoch: 40, loss: 0.73978\n Epoch: 60, loss: 0.46417\n Epoch: 80, loss: 0.29618\n Epoch: 100, loss: 0.18528\n Epoch: 120, loss: 0.11216\n Epoch: 140, loss: 0.07267\n Epoch: 160, loss: 0.05161\n Epoch: 180, loss: 0.03928\n Epoch: 200, loss: 0.03138\n Epoch: 220, loss: 0.02593\n Epoch: 240, loss: 0.02196\n Epoch: 260, loss: 0.01896\n Epoch: 280, loss: 0.01662\n Epoch: 300, loss: 0.01475\n\n\n## Testing\n\nSee how your model performs *after* training. Compare this output with the scores from before training, above.\n\nAgain, for the test sentence, \"The cheese loves the elephant\", we know that this has the tags (DET, NN, V, DET, NN) or `[0, 1, 2, 0, 1]`. Let's see if our model has learned to find these tags!\n\n\n```python\ntest_sentence = \"The cheese loves the elephant\".lower().split()\n\n# see what the scores are after training\ninputs = prepare_sequence(test_sentence, word2idx)\ninputs = inputs\ntag_scores = model(inputs)\nprint(tag_scores)\n\n# print the most likely tag index, by grabbing the index with the maximum score!\n# recall that these numbers correspond to tag2idx = {\"DET\": 0, \"NN\": 1, \"V\": 2}\n_, predicted_tags = torch.max(tag_scores, 1)\nprint('\\n')\nprint('Predicted tags: \\n',predicted_tags)\n```\n\n tensor([[-0.0554, -2.9240, -8.5549],\n [-6.7675, -0.0037, -5.9878],\n [-7.8418, -4.1628, -0.0161],\n [-0.0619, -2.8249, -7.2885],\n [-5.9885, -0.0079, -5.2284]], grad_fn=)\n \n \n Predicted tags: \n tensor([0, 1, 2, 0, 1])\n\n\n## Great job!\n\nTo improve this model, see if you can add sentences to this model and create a more robust speech tagger. Try to initialize the hidden state in a different way or play around with the optimizers and see if you can decrease model loss even faster.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6d674aa687bb90009aa0dc06256e2d3bf11c3247", "size": 20589, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "2_4_LSTMs/2. LSTM Training, Part of Speech Tagging.ipynb", "max_stars_repo_name": "roachsinai/CVND_Exercises", "max_stars_repo_head_hexsha": "3e44093cd881516c614d7e5771414af4a73a82d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2_4_LSTMs/2. LSTM Training, Part of Speech Tagging.ipynb", "max_issues_repo_name": "roachsinai/CVND_Exercises", "max_issues_repo_head_hexsha": "3e44093cd881516c614d7e5771414af4a73a82d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2_4_LSTMs/2. LSTM Training, Part of Speech Tagging.ipynb", "max_forks_repo_name": "roachsinai/CVND_Exercises", "max_forks_repo_head_hexsha": "3e44093cd881516c614d7e5771414af4a73a82d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.343373494, "max_line_length": 641, "alphanum_fraction": 0.5929865462, "converted": true, "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.340231768372898}} {"text": "   \n\n# Tutorial 2: Modern RNNs and their variants\n\n**Week 2, Day 3: Modern RNNs**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Bhargav Srinivasa Desikan, Anis Zahedifard, James Evans\n\n__Content reviewers:__ Lily Cheng, Melvin Selim Atay, Ezekiel Williams, Kelson Shilling-Scrivo\n\n__Content editors:__ Gagana B, Spiros Chavlis\n\n__Production editors:__ Roberto Guidotti, Spiros Chavlis\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n---\n# Tutorial objectives\n\nIn this tutorial you will learn about:\n1. Modern Recurrent Neural Networks and their use\n2. Long Short-Term Memory (LSTM), Gated Recurrent Unit (GRU) and the memory cell\n3. Sequence to Sequence and Encoder-Decoder Networks\n4. Models of attention for text classification\n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorials\n\n# @markdown If you want to locally download the slides, click [here](https://osf.io/n23hy/download)\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/n23hy/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n# Setup\n\nWe will use the IMDB dataset, which consists of a set of 25,000 highly polar movie reviews for training, and 25,000 for testing. We will use torchtext to download the dataset and prepare it for training, validation and testing. Our goal is to build a model that performs binary classification between positive and negative movie reviews.\n\nWe use `fix_length` argument to pad sentences of length less than `sentence_length` or truncate sentences of length greater than `sentence_length`. \n\n\n```python\n# @title Install dependecies\n\n# @markdown There may be `Errors`/`Warnings` reported during the installation. However, they are to be ignored.\n!pip install --upgrade gensim --quiet\n!pip install torchtext==0.4.0 --quiet\n!pip install unidecode --quiet\n!pip install d2l --quiet\n!pip install nltk --quiet\n\n!pip install git+https://github.com/NeuromatchAcademy/evaltools --quiet\nfrom evaltools.airtable import AirtableForm\n\natform = AirtableForm('appn7VdPRseSoMXEG','W2D3_T2','https://portal.neuromatchacademy.org/api/redirect/to/3412a777-eb0e-4312-9254-eec266f0bee4')\n```\n\n\n```python\n# Imports\nimport math\nimport time\nimport nltk\nimport random\nimport collections\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom torchtext import data, datasets\n\nfrom d2l import torch as d2l\n```\n\n\n```python\n# @title Figure Settings\nimport ipywidgets as widgets\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")\n```\n\n\n```python\n# @title Download the dataset\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\nnltk.download('brown')\nnltk.download('webtext')\n```\n\n [nltk_data] Downloading package punkt to\n [nltk_data] /home/dinize@acct.upmchs.net/nltk_data...\n [nltk_data] Package punkt is already up-to-date!\n [nltk_data] Downloading package averaged_perceptron_tagger to\n [nltk_data] /home/dinize@acct.upmchs.net/nltk_data...\n [nltk_data] Package averaged_perceptron_tagger is already up-to-\n [nltk_data] date!\n [nltk_data] Downloading package brown to\n [nltk_data] /home/dinize@acct.upmchs.net/nltk_data...\n [nltk_data] Package brown is already up-to-date!\n [nltk_data] Downloading package webtext to\n [nltk_data] /home/dinize@acct.upmchs.net/nltk_data...\n [nltk_data] Package webtext is already up-to-date!\n\n\n\n\n\n True\n\n\n\n\n```python\n# @title Helper functions\n\ndef plot_train_val(x, train, val, train_label,\n val_label, title, y_label,\n color):\n\n plt.plot(x, train, label=train_label, color=color)\n plt.plot(x, val, label=val_label, color=color, linestyle='--')\n plt.legend(loc='lower right')\n plt.xlabel('epoch')\n plt.ylabel(y_label)\n plt.title(title)\n\n\ndef count_parameters(model):\n parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)\n return parameters\n\n\ndef init_weights(m):\n if type(m) in (nn.Linear, nn.Conv1d):\n nn.init.xavier_uniform_(m.weight)\n\n\n# Dataset Loader\ndef load_dataset(sentence_length=50, batch_size=32, seed=522):\n\n TEXT = data.Field(sequential=True,\n tokenize=nltk.word_tokenize,\n lower=True,\n include_lengths=True,\n batch_first=True,\n fix_length=sentence_length)\n LABEL = data.LabelField(dtype=torch.float)\n\n train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)\n\n # If no specific vector embeddings are specified,\n # Torchtext initializes random vector embeddings\n # which would get updated during training through backpropagation.\n TEXT.build_vocab(train_data)\n LABEL.build_vocab(train_data)\n\n train_data, valid_data = train_data.split(split_ratio=0.7,\n random_state=random.seed(seed))\n train_iter, valid_iter, test_iter = data.BucketIterator.splits((train_data, valid_data, test_data),\n batch_size=batch_size, sort_key=lambda x: len(x.text),\n repeat=False, shuffle=True)\n vocab_size = len(TEXT.vocab)\n\n print(f\"Data loading is completed. Sentence length: {sentence_length}, \"\n f\"Batch size: {batch_size}, and seed: {seed}\")\n\n return TEXT, vocab_size, train_iter, valid_iter, test_iter\n\n\ndef text_from_dict(arr, dictionary):\n text = []\n for element in arr:\n text.append(dictionary[element])\n return text\n\n\ndef view_data(TEXT, train_iter):\n for idx, batch in enumerate(train_iter):\n text = batch.text[0]\n target = batch.label\n\n for itr in range(25, 30):\n print('Review: ', ' '.join(text_from_dict(text[itr], TEXT.vocab.itos)))\n print('Label: ', int(target[itr].item()), '\\n')\n\n print('[0: Negative Review, 1: Positive Review]')\n if idx==0:\n break\n\n\n# Training function\ndef train(model, device, train_iter, valid_iter, epochs, learning_rate):\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n train_loss, validation_loss = [], []\n train_acc, validation_acc = [], []\n\n for epoch in range(epochs):\n #train\n model.train()\n running_loss = 0.\n correct, total = 0, 0\n steps = 0\n\n for idx, batch in enumerate(train_iter):\n text = batch.text[0]\n # print(type(text), text.shape)\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n # add micro for coding training loop\n optimizer.zero_grad()\n output = model(text)\n\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n steps += 1\n running_loss += loss.item()\n\n # get accuracy\n _, predicted = torch.max(output, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n train_loss.append(running_loss/len(train_iter))\n train_acc.append(correct/total)\n\n print(f'Epoch: {epoch + 1}, '\n f'Training Loss: {running_loss/len(train_iter):.4f}, '\n f'Training Accuracy: {100*correct/total: .2f}%')\n\n # evaluate on validation data\n model.eval()\n running_loss = 0.\n correct, total = 0, 0\n\n with torch.no_grad():\n for idx, batch in enumerate(valid_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n optimizer.zero_grad()\n output = model(text)\n\n loss = criterion(output, target)\n running_loss += loss.item()\n\n # get accuracy\n _, predicted = torch.max(output, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n validation_loss.append(running_loss/len(valid_iter))\n validation_acc.append(correct/total)\n\n print (f'Validation Loss: {running_loss/len(valid_iter):.4f}, '\n f'Validation Accuracy: {100*correct/total: .2f}%')\n\n return train_loss, train_acc, validation_loss, validation_acc\n\n\n# Testing function\ndef test(model, device, test_iter):\n model.eval()\n correct = 0\n total = 0\n with torch.no_grad():\n for idx, batch in enumerate(test_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n outputs = model(text)\n _, predicted = torch.max(outputs, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n acc = 100 * correct / total\n return acc\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nDEVICE = set_device()\nSEED = 2021\nset_seed(seed=SEED)\n```\n\n GPU is enabled in this notebook.\n Random seed 2021 has been set.\n\n\n---\n# Section 1: Recurrent Neural Networks (RNNs)\n\n*Time estimate: ~27mins*\n\n\n```python\n# @title Video 1: Recurrent Neural Networks\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Ng41177az\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"hIHocwdyY7M\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 1: Recurrent Neural Networks')\n\ndisplay(out)\n```\n\n\n Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})\n\n\nRecurrent neural networks, or RNNs , are a family of neural networks for processing sequential data. Just as a convolutional network is specialized for processing a grid of values X such as an image, a recurrent neural network is specialized for processing a sequence of values. RNNs prove useful in many scenarios where other deep learning models are not effective.\n\n* Not all problems can be converted into one with fixed length inputs and outputs.\n\n\n* The deep learning models we have seen so far pick samples randomly. This might not be the best strategy for a task of understanding meaning from a piece of text. Words in a text occur in a sequence and therefore cannot be permuted randomly to get the meaning.\n\nThe following provides more data than the video (but can be skipped for now). For more detail, see the sources, the [deep learning book](https://www.deeplearningbook.org/contents/rnn.html), and [d2l.ai](https://d2l.ai/chapter_recurrent-neural-networks/rnn.html)\n\nWhen the recurrent network is trained to perform a task that requires predicting the future from the past, the network typically learns to use a hidden state at time step $t$, $H_t$ as a kind of lossy summary of the task-relevant aspects of the past sequence of inputs up to $t$. This summary is in general necessarily lossy, since it maps an arbitrary length sequence $(X_t, X_{t-1}, X_{t-2}, . . . , X_{2}, X_{1})$ to a fixed length vector $H_t$.\n\nWe can represent the unfolded recurrence after $t$ steps with a function $G_t$:\n\n\\begin{align}\nH_t &= G_t(X_t, X_{t-1}, X_{t-2}, \\dots, X_{2}, X_{1}) \\\\\n&= f(H_{t−1}, X_{t}; \\theta)\n\\end{align}\n\nwhere $\\theta$ denotes the model parameters, i.e., weights and biases.\n\n
\n \n
\n Source blog.floydhub.com\n
\n
\n\nThe function $g_t$ takes the whole past sequence $(X_t, X_{t-1}, X_{t-2}, . . . , X_{2}, X_{1})$ as input and produces the current state, but the unfolded recurrent structure allows us to factorize $g_t$ into repeated application of a function f. The unfolding process thus introduces two major advantages:\n\n* Regardless of the sequence length, the learned model always has the same input size, because it is specified in terms of transition from one state to another state, rather than specified in terms of a variable-length history of states.\n\n* It is possible to use the same transition function $f$ with the same parameters at every time step.\n\n\nWe will now formally write down the equations of a recurrent unit.\n\n\nAssume that we have a minibatch of inputs $X_t \\in R^{nxd}$ at time step $t$ . In other words, for a minibatch of $n$ sequence examples, each row of $X_t$ corresponds to one example at time step $t$ from the sequence. Next, we denote by $H_t \\in R^{nxh}$ the hidden variable of time step $t$. Unlike the MLP, here we save the hidden variable $H_{t-1}$ from the previous time step and introduce a new weight parameter $W_{hh} \\in R^{hxh}$ to describe how to use the hidden variable of the previous time step in the current time step. Specifically, the calculation of the hidden variable of the current time step is determined by the input of the current time step together with the hidden variable of the previous time step:\n\n\\begin{equation}\nH_t = \\phi(X_t W_{xh} + H_{t-1}W_{hh} + b_h)\n\\end{equation}\n\nFor time step $t$, the output of the output layer is similar to the computation in the MLP:\n\n\\begin{equation}\nO_t = H_t W_{hq} + b_q\n\\end{equation}\n \nParameters of the RNN include the weights $W_{xh} \\in R^{d \\times h}, W_{hh} \\in R^{h \\times h}$ , and the bias $b_h \\in R^{1 \\times h}$ of the hidden layer, together with the weights $W_{hq} \\in R^{h \\times q}$ and the bias $b_q \\in R^{1 \\times q}$ of the output layer. It is worth mentioning that even at different time steps, RNNs always use these model parameters. Therefore, the parameterization cost of an RNN does not grow as the number of time steps increases.\n\n
\n \n
\n Source d2l.ai\n
\n
\n\n## Section 1.1: Load and View of the dataset\n\nLet us first load the dataset using the helper function `load_data`, which takes three arguments; the `sentence_length`, `batch_size`, and the `seed`. The default values are 50, 32, and 522, respectively. Execute the cell below to load the data.\n\n\n```python\n# @markdown Dataset Loading with default params\nTEXT, vocab_size, train_iter, valid_iter, test_iter = load_dataset(seed=SEED)\n```\n\n Data loading is completed. Sentence length: 50, Batch size: 32, and seed: 2021\n\n\nNow, let's view the data!\n\n\n```python\n# @markdown Visualize dataset\nview_data(TEXT, train_iter)\n```\n\n Review: my 2 year old likes the doodlebops show , it seems to keep his attention for awhile . the characters are interesting , vibrant with primary colours and all . there 's not much educational content that the intended target audience could benefit from , but they do seem to\n Label: 1 \n \n Review: released just before the production code crackdown in july , 1934 , mitch leisen 's all-star paramount musical is leeringly suggestive -some even claim misogynistic- and highly entertaining . two murders occur on the opening night of `` earl carroll 's vanities '' ( one on-stage ! ) , but\n Label: 1 \n \n Review: this film caught me off guard when it started out in a cafe located in arizona and a richard grieco , ( rex ) , '' dead easy '' , '04 , decides to have something to eat and gets all hot and bothered over a very hot , sexy\n Label: 1 \n \n Review: billy crystal normally brings the crowd to laughter , but in this movie he and all the rest of them can not bring any smile on my face .... or perhaps just one . they call it comedy , i say it 's a waste of my time . \n Label: 0 \n \n Review: birthday girl does n't know what it wants to be - is it a comedy , , is it a drama ... it just does n't know . what could have been a very funny or touching film ends up in no-man 's land . the premise is original enough\n Label: 0 \n \n [0: Negative Review, 1: Positive Review]\n\n\n### Coding Exercise 1.1: Vanilla RNN\n\nNow it's your turn to write a Vanilla RNN using PyTorch.\n\n* Once again we will use `nn.Embedding`. You are given the `vocab_size` which is the size of the dictionary of embeddings, and the `embed_size` which is the size of each embedding vector. \n\n* Add 2 [RNN](https://pytorch.org/docs/stable/generated/torch.nn.RNN.html) layers. This would mean stacking two RNNs together to form a stacked RNN, with the second RNN taking in outputs of the first RNN and computing the final results.\n\n* Determine the size of inputs and outputs to the fully-connected layer.\n\n\n```python\nclass VanillaRNN(nn.Module):\n def __init__(self, layers, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(VanillaRNN, self).__init__()\n self.n_layers= layers\n self.hidden_size = hidden_size\n self.device = device\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n #raise NotImplementedError(\"Define the Vanilla RNN components\")\n ####################################################################\n # Define the embedding\n self.embeddings = nn.Embedding(vocab_size, embed_size)\n # Define the RNN layer\n self.rnn = nn.RNN(embed_size, hidden_size, num_layers=layers)\n # Define the fully connected layer\n self.fc = nn.Linear(layers * hidden_size, output_size)\n\n def forward(self, inputs):\n input = self.embeddings(inputs)\n input = input.permute(1, 0, 2)\n h_0 = torch.zeros(2, input.size()[1], self.hidden_size).to(self.device)\n output, h_n = self.rnn(input, h_0)\n h_n = h_n.permute(1, 0, 2)\n h_n = h_n.contiguous().reshape(h_n.size()[0], h_n.size()[1]*h_n.size()[2])\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 1.1: Vanilla RNN')\n\n## Uncomment to test VanillaRNN class\nsampleRNN = VanillaRNN(2, 10, 50, 1000, 300, DEVICE)\nprint(sampleRNN)\n```\n\n VanillaRNN(\n (embeddings): Embedding(1000, 300)\n (rnn): RNN(300, 50, num_layers=2)\n (fc): Linear(in_features=100, out_features=10, bias=True)\n )\n\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D3_ModernRecurrentNeuralNetworks/solutions/W2D3_Tutorial2_Solution_ae4fdee1.py)\n\n\n\n```\nVanillaRNN(\n (embeddings): Embedding(1000, 300)\n (rnn): RNN(300, 50, num_layers=2)\n (fc): Linear(in_features=100, out_features=10, bias=True)\n)\n```\n\n## Section 1.2: Train and test the network\n\n\n```python\n# Model hyperparamters\nlearning_rate = 0.0002\nlayers = 2\noutput_size = 2\nhidden_size = 50 # 100\nembedding_length = 100\nepochs = 10\n\n\n# Initialize model, training and testing\nset_seed(SEED)\nvanilla_rnn_model = VanillaRNN(layers, output_size, hidden_size, vocab_size,\n embedding_length, DEVICE)\nvanilla_rnn_model.to(DEVICE)\nvanilla_rnn_start_time = time.time()\nvanilla_train_loss, vanilla_train_acc, vanilla_validation_loss, vanilla_validation_acc = train(vanilla_rnn_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\nprint(\"--- Time taken to train = %s seconds ---\" % (time.time() - vanilla_rnn_start_time))\ntest_accuracy = test(vanilla_rnn_model, DEVICE, test_iter)\nprint(f'Test Accuracy: {test_accuracy} with len=50\\n')\n\n# Number of model parameters\nprint(f'Number of parameters = {count_parameters(vanilla_rnn_model)}')\n\n\n# Plot accuracy curves\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), vanilla_train_acc, vanilla_validation_acc,\n 'train accuracy', 'val accuracy',\n 'Vanilla RNN on IMDB text classification', 'accuracy',\n color='C0')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), vanilla_train_loss,\n vanilla_validation_loss,\n 'train loss', 'val loss',\n 'Vanilla RNN on IMDB text classification',\n 'loss [a.u.]',\n color='C0')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n### Change the input length\n\nNow let's increase the `sentence_length` to see how RNN performs when long reviews are allowed..\n\n\n\n```python\n# @markdown Load dataset with `sentence_length=200`\nTEXT_long, vocab_size_long, train_iter_long, valid_iter_long, test_iter_long = load_dataset(sentence_length=200)\n```\n\n Data loading is completed. Sentence length: 200, Batch size: 32, and seed: 522\n\n\n### Re-run the network\n\n\n```python\n# Model hyperparamters\nlearning_rate = 0.0002\nlayers = 2\noutput_size = 2\nhidden_size = 50 # 100\nembedding_length = 100\nepochs = 10\n\n# Initialize model, training, testing\nset_seed(SEED)\nvanilla_rnn_model_long = VanillaRNN(layers, output_size, hidden_size,\n vocab_size_long, embedding_length, DEVICE)\nvanilla_rnn_model_long.to(DEVICE)\nvanilla_rnn_start_time_long = time.time()\nvanilla_train_loss_long, vanilla_train_acc_long, vanilla_validation_loss_long, vanilla_validation_acc_long = train(vanilla_rnn_model_long,\n DEVICE,\n train_iter_long,\n valid_iter_long,\n epochs,\n learning_rate)\nprint(\"--- Time taken to train = %s seconds ---\" % (time.time() - vanilla_rnn_start_time_long))\ntest_accuracy = test(vanilla_rnn_model_long, DEVICE, test_iter_long)\nprint(f'Test Accuracy: {test_accuracy} with len=200\\n')\n\n# Number of parameters\nprint(f'\\nNumber of parameters = {count_parameters(vanilla_rnn_model_long)}')\n```\n\n Random seed 2021 has been set.\n Epoch: 1, Training Loss: 0.6996, Training Accuracy: 49.21%\n Validation Loss: 0.6948, Validation Accuracy: 50.16%\n Epoch: 2, Training Loss: 0.6923, Training Accuracy: 51.50%\n Validation Loss: 0.6946, Validation Accuracy: 50.89%\n Epoch: 3, Training Loss: 0.6890, Training Accuracy: 52.89%\n Validation Loss: 0.6974, Validation Accuracy: 50.07%\n Epoch: 4, Training Loss: 0.6843, Training Accuracy: 54.32%\n Validation Loss: 0.6975, Validation Accuracy: 51.56%\n Epoch: 5, Training Loss: 0.6761, Training Accuracy: 56.02%\n Validation Loss: 0.6989, Validation Accuracy: 52.91%\n Epoch: 6, Training Loss: 0.6711, Training Accuracy: 56.62%\n Validation Loss: 0.7007, Validation Accuracy: 50.97%\n Epoch: 7, Training Loss: 0.6653, Training Accuracy: 57.17%\n Validation Loss: 0.7043, Validation Accuracy: 51.24%\n Epoch: 8, Training Loss: 0.6461, Training Accuracy: 59.59%\n Validation Loss: 0.6996, Validation Accuracy: 55.12%\n Epoch: 9, Training Loss: 0.6430, Training Accuracy: 60.05%\n Validation Loss: 0.7073, Validation Accuracy: 52.16%\n Epoch: 10, Training Loss: 0.6436, Training Accuracy: 60.37%\n Validation Loss: 0.7146, Validation Accuracy: 52.07%\n --- Time taken to train = 81.33106875419617 seconds ---\n Test Accuracy: 52.24 with len=200\n \n \n Number of parameters = 11186002\n\n\n\n```python\n# Compare accuracies of model trained on different sentence lengths\nplot_train_val(np.arange(0, epochs), vanilla_train_acc,\n vanilla_validation_acc,\n 'train accuracy, len=50', 'val accuracy, len=50',\n '', 'accuracy',\n color='C0')\nplot_train_val(np.arange(0, epochs), vanilla_train_acc_long,\n vanilla_validation_acc_long,\n 'train accuracy, len=200', 'val accuracy, len=200',\n 'Training and Validation Accuracy for Sentence Lengths 50 and 200',\n 'accuracy',\n color='C1')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n## Section 1.3: Architectures\n\n\n```python\n# @title Video 2: Bidirectional RNNs\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1X64y1x7BA\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"TpgJwqB4i1c\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 2: Bidirectional RNNs')\n\ndisplay(out)\n```\n\n\n Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})\n\n\nRNN models are mostly used in the fields of natural language processing and speech recognition. Below are types of RNNs. Depending on which outputs we use, RNN can be used for variety of tasks. The text classification problem we solved was an instance of the many to one architecture. Write down the applications of other architectures. \n\n\n
\n \n
\n Source blog.floydhub.com\n
\n
\n\n## Section 1.4: Vanishing and Exploding Gradients\n\nFor an RNN to learn via backprop through time on a loss calculated at time $T$, $\\mathcal{L}_T$, with respect to an input $t$ time steps in the past, the RNN weights must be updated based on how they contributed to the hidden state at this past time step. This contribution is learned through the term $\\frac{\\partial h_{-t}}{\\partial W}$, in the gradient of the loss, $\\frac{\\partial\\mathcal{L}_T}{\\partial W}$.\n\nHowever, because one has to backpropagate error through $t-1$ hidden states, $\\frac{\\partial h_{-t}}{\\partial W}$ is multiplied by $\\prod_{i=0}^{t-1} \\frac{\\partial{h_i}}{\\partial{h_{i-1}}}$ in the expression for $\\frac{\\partial\\mathcal{L}_T}{\\partial W}$, which are summarized mathematically:\n\n\\begin{equation}\n\\frac{\\partial{\\mathcal{L}_T}}{\\partial{W}} \\propto \\frac{\\partial h_t }{ \\partial W} + \\sum_{k=0}^{t-1} \\left( \\prod_{i=k+1}^{t} \\frac{\\partial{h_i}}{\\partial{h_{i-1}}} \\right) \\frac{\\partial{h_k}}{\\partial{W}}\n\\end{equation}\n\nThe product term leads to two common problems during the backpropagation of time-series data:\n\n* *Vanishing gradients*, *if* $ \\left| \\left| \\frac{\\partial{h_i}}{\\partial{h_{i-1}}} \\right| \\right|_2 < 1$\n\n\n* *Exploding gradients*, *if* $ \\left| \\left| \\frac{\\partial{h_i}}{\\partial{h_{i-1}}} \\right| \\right|_2 > 1$\n\nGiven a sufficiently long sequence, the gradients get multiplied by the weight matrix at every time step. If the weight matrix contains very small values, then the norm of gradients will become smaller and smaller exponentially, the so-called **vanishing gradient** problem. On the other hand, if we have a weight matrix with very large values, the gradients will increase exponentially, leading to the **exploding gradients** problem: where the weights diverge at the update step.\n\nAn example that has the vanishing gradient problem:\n\nThe input is the characters from a *C* Program. The system will tell whether it is a syntactically correct program. A syntactically correct program should have a valid number of braces and parentheses. Thus, the network should remember how many open parentheses and braces there are to check, and whether we have closed them all. The network has to store such information in hidden states like a counter. However, because of vanishing gradients, it will fail to preserve such information in a long program.\n\n---\n# Section 2: LSTM, GRU and Memory Cell\n\n*Time estimate: ~28mins*\n\n\n```python\n# @title Video 3: LSTM, GRU & The Memory Cells\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Zq4y1X7kj\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"qC7O-2sXLAU\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 3: LSTM, GRU & The Memory Cells')\n\ndisplay(out)\n```\n\n\n Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})\n\n\n## Section 2.1: Architecture\n\nThe core idea behind an LSTM is the cell state $C_t$ that runs along all the LSTM units in a layer, and gets updated along the way. These updates are possible through \"gates\". Gates are made out of a sigmoid neural net layer and a pointwise multiplication operation. \n\nEach LSTM unit performs the following distinct steps using the input $X_t$, current cell state $C_t$ and previous hidden state $H_{t-1}$:\n\n* Forget Gate: *Should I throw away information from this cell?*\n\n\\begin{equation}\nF_t = \\sigma (W_f \\cdot [H_{t-1}, X_t] + b_f)\n\\end{equation}\n\n* Input Gate:\n * *Should I add new values to this cell?*\n \\begin{equation}\n I_t = \\sigma (W_i \\cdot [H_{t-1}, X_t] + b_i)\n \\end{equation}\n * *What new candidate values should I store?*\n \\begin{equation}\n \\tilde{C}_t = tanh (W_C \\cdot [H_{t-1}, X_t] + b_C)\n \\end{equation}\n\n* Update cell state: *Forget things from the past and add new things from the candidates*\n \\begin{equation}\n C_t = (F_t \\cdot C_{t-1}) + (I_t \\cdot \\tilde{C}_t)\n \\end{equation}\n\n* Output Gate: \n * *What information should I output?*\n \\begin{equation}\n O_t = \\sigma (W_o \\cdot [H_{t-1}, X_t] + b_o)\n \\end{equation}\n * *How much of the cell state should I store in the hidden state?*\n \\begin{equation}\n H_t = O_t \\cdot tanh(C_t)\n \\end{equation}\n\nThe architecture can be summarized by the diagram below:\n\n
\n
\n \n
\n Source d2l.ai\n
\n
\n
\n\n### Coding Exercise 2.1: Implementing LSTM\n\nIt is now your turn to build an LSTM network in PyTorch. Feel free to refer to the documentation here: https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#torch.nn.LSTM . \n\n* Once again we will use `nn.Embedding`. You are given the `vocab_size` and the `embed_size`.\n* Add the [`LSTM`](https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html#torch.nn.LSTM) layers. \n* Define a dropout layer of 0.5. \n* Determine the size of inputs and outputs to the fully-connected layer.\n* Pay special attention to the shapes of your inputs and outputs as you write the forward function.\n\n\n\n\n```python\nclass LSTM(nn.Module):\n def __init__(self, layers, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(LSTM, self).__init__()\n self.n_layers = layers\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.device = device\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n #raise NotImplementedError(\"LSTM Init\")\n ####################################################################\n # Define the word embeddings\n self.word_embeddings = nn.Embedding(vocab_size, embed_size)\n # Define the dropout layer\n self.dropout = nn.Dropout(0.5)\n # Define the lstm layer\n self.lstm = nn.LSTM(embed_size, hidden_size, num_layers=layers)\n # Define the fully-connected layer\n self.fc = nn.Linear(layers * embed_size, output_size)\n\n\n def forward(self, input_sentences):\n \"\"\"Hint: Make sure the shapes of your tensors match the requirement\"\"\"\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n #raise NotImplementedError(\"LSTM Forward\")\n ####################################################################\n # Embeddings\n # `input` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n input = self.word_embeddings(input_sentences)\n\n hidden = (torch.randn(self.n_layers, input.shape[1],\n self.hidden_size).to(self.device),\n torch.randn(self.n_layers, input.shape[1],\n self.hidden_size).to(self.device))\n # Dropout for regularization\n input = self.dropout(input)\n # LSTM\n output, hidden = ...\n\n h_n = hidden[0].permute(1, 0, 2)\n h_n = h_n.contiguous().view(h_n.shape[0], -1)\n\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 2.1: Implementing LSTM')\n\n## Uncomment to run\n# sampleLSTM = LSTM(3, 10, 100, 1000, 300, DEVICE)\n# print(sampleLSTM)\n```\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D3_ModernRecurrentNeuralNetworks/solutions/W2D3_Tutorial2_Solution_2e49ddad.py)\n\n\n\n```\nLSTM(\n (word_embeddings): Embedding(1000, 300)\n (dropout): Dropout(p=0.5, inplace=False)\n (lstm): LSTM(300, 100, num_layers=3)\n (fc): Linear(in_features=300, out_features=10, bias=True)\n)\n```\n\n\n```python\n# Hyperparameters\nlearning_rate = 0.0003\nlayers = 2\noutput_size = 2\nhidden_size = 16\nembedding_length = 100\nepochs = 10\n\n# Model, training, testing\nset_seed(SEED)\nlstm_model = LSTM(layers, output_size, hidden_size, vocab_size,\n embedding_length, DEVICE)\nlstm_model.to(DEVICE)\nlstm_train_loss, lstm_train_acc, lstm_validation_loss, lstm_validation_acc = train(lstm_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\ntest_accuracy = test(lstm_model, DEVICE, test_iter)\nprint(f'\\n\\nTest Accuracy: {test_accuracy} of the LSTM model\\n')\n\n# Plotting accuracy curve\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), lstm_train_acc, lstm_validation_acc,\n 'train accuracy',\n 'val accuracy',\n 'LSTM on IMDB text classification',\n 'accuracy',\n color='C0')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), lstm_train_loss, lstm_validation_loss,\n 'train loss',\n 'val loss',\n '',\n 'loss',\n color='C0')\nplt.legend(loc='upper left')\nplt.tight_layout()\nplt.show()\n```\n\n## Section 2.2: Gated Recurrent Units (GRU)\n\nThe GRU architecture looks very similar to the LSTM, and is often used as an alternative to the traditional LSTM. It also contains some variations that reduce it's complexity. For example, it combines the forget and input gates into a single “update gate”; it contains a \"hidden state\" but not a \"cell state\". In the next section we will be using GRUs as the choice of recurrent unit in our models, but you can always swap out the GRU for an LSTM later on (make sure that you take care of input and output dimensions in this case). Here is a description of the parts of the GRU:\n\n* Reset Gate: *How much of the previous hidden state should I remember?*\n \\begin{equation}\n R_t = \\sigma (W_r \\cdot [H_{t-1}, X_t])\n \\end{equation}\n\n* Update Gate: \n * *How much of the new state is different from the old state?*\n \\begin{equation}\n Z_t = \\sigma (W_z \\cdot [H_{t-1}, X_t])\n \\end{equation}\n * *What new candidate values should I store?*\n \\begin{equation}\n \\tilde{H}_t = tanh (W \\cdot [R_t \\cdot H_{t-1}, X_t])\n \\end{equation}\n\n* Update hidden state: *Deciding how much of the old hidden state to keep and discard*\n \\begin{equation}\n H_t = ((1-Z_t) \\cdot H_{t-1} ) + (Z_t \\cdot \\tilde{H}_t)\n \\end{equation}\n\nHere is what the architecture looks like:\n\n
\n
\n \n
\n Source d2l.ai\n
\n
\n
\n\n### Coding Exercise 2.2: BiLSTM\n\nLet's apply the knowledge to write a bi-LSTM using PyTorch.\n\n* Use an Embedding layer\n* Dropout of 0.5\n* Add 2 LSTM layers\n* Linear layer \n\n\n```python\nclass biLSTM(nn.Module):\n def __init__(self, output_size, hidden_size, vocab_size, embed_size,\n device):\n super(biLSTM, self).__init__()\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.device = device\n ####################################################################\n # Fill in missing code below (...)\n raise NotImplementedError(\"biLSTM\")\n ####################################################################\n # Define the word embeddings\n self.word_embeddings = ...\n # Define the dropout layer\n self.dropout = ...\n # Define the bilstm layer\n self.bilstm = ...\n # Define the fully-connected layer\n self.fc = ...\n\n def forward(self, input_sentences):\n input = self.word_embeddings(input_sentences).permute(1, 0, 2)\n hidden = (torch.randn(4, input.shape[1], self.hidden_size).to(self.device),\n torch.randn(4, input.shape[1], self.hidden_size).to(self.device))\n input = self.dropout(input)\n\n output, hidden = self.bilstm(input, hidden)\n\n h_n = hidden[0].permute(1, 0, 2)\n h_n = h_n.contiguous().view(h_n.shape[0], -1)\n logits = self.fc(h_n)\n\n return logits\n\n\n# add event to airtable\natform.add_event('Coding Exercise 2.2: BiLSTM')\n\n## Uncomment to run\n# sampleBiLSTM = biLSTM(10, 100, 1000, 300, DEVICE)\n# print(sampleBiLSTM)\n```\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D3_ModernRecurrentNeuralNetworks/solutions/W2D3_Tutorial2_Solution_ee3eea5f.py)\n\n\n\n```\nbiLSTM(\n (word_embeddings): Embedding(1000, 300)\n (dropout): Dropout(p=0.5, inplace=False)\n (bilstm): LSTM(300, 100, num_layers=2, bidirectional=True)\n (fc): Linear(in_features=400, out_features=10, bias=True)\n)\n```\n\n\n```python\n# Hyperparameters\nlearning_rate = 0.0003\noutput_size = 2\nhidden_size = 16\nembedding_length = 100\nepochs = 10\n\n# Model, training, testing\nset_seed(SEED)\nbilstm_model = biLSTM(output_size, hidden_size, vocab_size,\n embedding_length, DEVICE)\nbilstm_model.to(DEVICE)\nbilstm_train_loss, bilstm_train_acc, bilstm_validation_loss, bilstm_validation_acc = train(bilstm_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\ntest_accuracy = test(bilstm_model, DEVICE, test_iter)\nprint(f'Test Accuracy: {test_accuracy} of the biLSTM model\\n')\n\n# Plotting accuracy curve\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), bilstm_train_acc, bilstm_validation_acc,\n 'train accuracy',\n 'val accuracy',\n 'biLSTM on IMDB text classification',\n 'accuracy',\n color='C1')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), bilstm_train_loss, bilstm_validation_loss,\n 'train loss',\n 'val loss',\n '',\n 'loss',\n color='C1')\nplt.legend(loc='upper left')\nplt.tight_layout()\nplt.show()\n```\n\n\n```python\n# Compare accuracies of LSTM and biLSTM\nplot_train_val(np.arange(0, epochs), lstm_train_acc,\n lstm_validation_acc,\n 'train accuracy LSTM', 'val accuracy LSTM',\n '', 'accuracy',\n color='C0')\nplot_train_val(np.arange(0, epochs), bilstm_train_acc,\n bilstm_validation_acc,\n 'train accuracy biLSTM', 'val accuracy biLSTM',\n 'Training and Validation Accuracy for LSTM and biLSTM models',\n 'accuracy',\n color='C1')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n---\n# Section 3: Sequence to Sequence (Seq2Seq) & Encoder/ Decoder Networks\n\n*Time estimate: ~15mins*\n\n\n```python\n# @title Video 4: Seq2Seq & Encoder-Decoder Nets\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1WM4y1N7P7\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"q-hf7mnZsXo\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 4: Seq2Seq & Encoder-Decoder Nets')\n\ndisplay(out)\n```\n\nSources: [d2l.ai on encoders](https://d2l.ai/chapter_recurrent-modern/encoder-decoder.html) ; [d2l.ai on seq2seq](https://d2l.ai/chapter_recurrent-modern/seq2seq.html) ; [Jalammar's blog](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/ )\n\nSequence-to-sequence models take in a sequence of items (words, characters, etc) as input and produces another sequence of items as output. The most \nsimple seq2seq models are composed of two parts: the encoder, the context (\"state\" in the figure) and the decoder. The encoder and decoder usually consist of recurrent units that we've seen before (RNNs, GRUs or LSTMs). A high-level schematic of the architecture is as follows:\n\n
\n
\n \n
\n Source d2l.ai\n
\n
\n
\n\nThe encoder's recurrent unit processes the input one item at a time. Once the entire sequence is processed, the final hidden state vector produced is known as a context vector. The size of the context vector is defined while setting up the model, and is equal to the number of hidden states used in the encoder RNN. The encoder then passes the context to the decoder. The decoder's recurrent unit uses the context to produce the items for the output sequence one by one. \n\n\nOne of the most popular applications of seq2seq models is \"machine translation\": the task of taking in a sentence in one language (the source) and producing its translation in another language (the target); with words in both lanugages being the sequence units. This is a supervised learning task, and requires the dataset to have \"parallel sentences\"; i.e., each sentence in the source language must be labelled with its translation in the target language. \n\n[Here is an intuitive visualization for understanding seq2seq models for machine translation from English to French](https://i.imgur.com/HJ6t8up.mp4)\n\nSince the vocabulary of an entire language is very large, training such models to give meaningful performance requires significant time and resources. In this section, we will train a seq2seq model to perform machine translation from English to [Pig-Latin](https://en.wikipedia.org/wiki/Pig_Latin). We will modify the task to perform character-level machine translation, so that vocabulary size does not grow exponentially. \n\n\n## Coding Exercise 3: Encoder\n\nLet us consider a sequence example (`batch_size=1`). Suppose that the input sequence is $x_1, \\ldots, x_T$, such that $x_t$ is the $t^{\\mathrm{th}}$ token in the input text sequence. At time step $t$, the RNN transforms the input feature vector $\\mathbf{x}_t$ for $x_t$ and the hidden state $\\mathbf{h} _{t-1}$ from the previous time step into the current hidden state $\\mathbf{h}_t$.\n\nWe can use a function $f$ to express the transformation of the RNN's recurrent layer:\n\n\\begin{equation}\n\\mathbf{h}_t = f(\\mathbf{x}_t, \\mathbf{h}_{t-1})\n\\end{equation}\n\nIn general, the encoder transforms the hidden states at all the time steps into the context variable through a customized function $q$:\n\n\\begin{equation}\n\\mathbf{c} = q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T)\n\\end{equation}\n\nFor example, when choosing $q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T) = \\mathbf{h}_T$ the context variable is just the hidden state $\\mathbf{h}_T$ of the input sequence at the final time step.\n\nSo far we have used a unidirectional RNN to design the encoder, where a hidden state only depends on the input subsequence at and before the time step of the hidden state. We can also construct encoders using bidirectional RNNs. In this case, a hidden state depends on the subsequence before and after the time step (including the input at the current time step), which encodes the information of the entire sequence.\n\nNow let us implement the RNN encoder. Note that we use an *embedding layer*\nto obtain the feature vector for each token in the input sequence. The weight of an embedding layer is a matrix whose number of rows is equal to the size of the input vocabulary (`vocab_size`) and the number of columns equals to the feature vector's dimension (`embed_size`). For any input token index $i$,\nthe embedding layer fetches the $i^{\\mathrm{th}}$ row (starting from 0) of the weight matrix to return its feature vector. ere we choose a multilayer GRU to implement the encoder.\n\nThe returned variables of recurrent layers have been completely explained at [this link](https://www.d2l.ai/chapter_recurrent-neural-networks/rnn-concise.html#sec-rnn-concise). Let us still use a concrete example to illustrate the above encoder implementation. Below we instantiate a two-layer GRU encoder whose number of hidden units is 16. Given a minibatch of sequence inputs $X$ (`batch_size=4`, `number_of_time_steps=7`), the hidden states of the last layer at all the time steps (`output` returned by the encoder's recurrent layers) are a tensor of shape (number of time steps, batch size, number of hidden units).\n\n\n\n```python\nclass Seq2SeqEncoder(d2l.Encoder):\n \"\"\"The RNN encoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqEncoder, self).__init__(**kwargs)\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Encoder Unit\")\n ####################################################################\n # Embedding layer\n self.embedding = ...\n # Here you're going to implement a GRU as the RNN unit\n self.rnn = ...\n\n def forward(self, X, *args):\n # The output `X` shape: (`batch_size`, `num_steps`, `embed_size`)\n X = self.embedding(X)\n # In RNN models, the first axis corresponds to time steps\n X = X.permute(1, 0, 2)\n ####################################################################\n # Fill in missing code below (...),\n # then remove or comment the line below to test your function\n raise NotImplementedError(\"Forward pass\")\n ####################################################################\n # When state is not mentioned, it defaults to zeros, the output should be a RNN function of X!\n output, state = ...\n # `output` shape: (`num_steps`, `batch_size`, `num_hiddens`)\n # `state` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n\n return output, state\n\n\n# add event to airtable\natform.add_event('Coding Exercise 3: Encoder')\n\nX = torch.zeros((4, 7), dtype=torch.long)\n## uncomment the lines below.\n# encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)\n# encoder.eval()\n# output, state = encoder(X)\n# print(output.shape)\n# print(state.shape)\n```\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D3_ModernRecurrentNeuralNetworks/solutions/W2D3_Tutorial2_Solution_29fbb575.py)\n\n\n\n```\ntorch.Size([7, 4, 16])\ntorch.Size([2, 4, 16])\n```\n\n## Section 3.1: Decoder\n\nAs we just mentioned, the context variable $\\mathbf{c}$ of the encoder's output encodes the entire input sequence $x_1, \\ldots, x_T$. Given the output sequence $y_1, y_2, \\ldots, y_{T'}$ from the training dataset, for each time step $t'$\n(the symbol differs from the time step $t$ of input sequences or encoders),\nthe probability of the decoder output $y_{t'}$ is conditional on the previous output subsequence $y_1, \\ldots, y_{t'-1}$ and the context variable $\\mathbf{c}$, i.e., $P(y_{t'} \\mid y_1, \\ldots, y_{t'-1}, \\mathbf{c})$.\n\n\nTo model this conditional probability on sequences, we can use another RNN as the decoder. At any time step $t^\\prime$ on the output sequence, the RNN takes the output $y_{t^\\prime-1}$ from the previous time step and the context variable $\\mathbf{c}$ as its input, then transforms them and the previous hidden state $\\mathbf{s}_{t^\\prime-1}$ into the hidden state $\\mathbf{s}_{t^\\prime}$ at the current time step.\n\nAs a result, we can use a function $g$ to express the transformation of the decoder's hidden layer:\n\n\\begin{equation}\n\\mathbf{s}_{t^\\prime} = g(y_{t^\\prime-1}, \\mathbf{c}, \\mathbf{s}_{t^\\prime-1})\n\\end{equation}\n\nAfter obtaining the hidden state of the decoder, we can use an output layer and the softmax operation to compute the conditional probability distribution\n$P(y_{t^\\prime} \\mid y_1, \\ldots, y_{t^\\prime-1}, \\mathbf{c})$ for the output at time step $t^\\prime$.\n\nFollowing `fig_seq2seq`, when implementing the decoder as follows, we directly use the hidden state at the final time step of the encoder to initialize the hidden state of the decoder.\n\nThis requires that the RNN encoder and the RNN decoder have the same number of layers and hidden units. To further incorporate the encoded input sequence information, the context variable is concatenated with the decoder input at all the time steps. To predict the probability distribution of the output token,\na fully-connected layer is used to transform the hidden state at the final layer of the RNN decoder.\n\n\n```python\nclass Seq2SeqDecoder(d2l.Decoder):\n \"\"\"The RNN decoder for sequence to sequence learning.\"\"\"\n def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n dropout=0, **kwargs):\n super(Seq2SeqDecoder, self).__init__(**kwargs)\n self.embedding = nn.Embedding(vocab_size, embed_size)\n self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers,\n dropout=dropout)\n self.dense = nn.Linear(num_hiddens, vocab_size)\n\n def init_state(self, enc_outputs, *args):\n return enc_outputs[1]\n\n def forward(self, X, state):\n # The output `X` shape: (`num_steps`, `batch_size`, `embed_size`)\n X = self.embedding(X).permute(1, 0, 2)\n # Broadcast `context` so it has the same `num_steps` as `X`\n context = state[-1].repeat(X.shape[0], 1, 1)\n X_and_context = torch.cat((X, context), 2)\n output, state = self.rnn(X_and_context, state)\n output = self.dense(output).permute(1, 0, 2)\n # `output` shape: (`batch_size`, `num_steps`, `vocab_size`)\n # `state` shape: (`num_layers`, `batch_size`, `num_hiddens`)\n return output, state\n```\n\nTo illustrate the implemented decoder,\nbelow we instantiate it with the same hyperparameters from the aforementioned encoder.\nAs we can see, the output shape of the decoder becomes (batch size, number of time steps, vocabulary size),\nwhere the last dimension of the tensor stores the predicted token distribution.\n\n\n\n```python\ndecoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16,\n num_layers=2)\n# decoder.initialize()\nstate = decoder.init_state(encoder(X))\noutput, state = decoder(X, state)\noutput.shape, len(state), state[0].shape\n```\n\n## Section 3.2: Loss Function\n\nAt each time step, the decoder predicts a probability distribution for the output tokens. Similar to language modeling, we can apply softmax to obtain the distribution and calculate the cross-entropy loss for optimization. Recall that the special padding tokens are appended to the end of sequences so sequences of varying lengths can be efficiently loaded in minibatches of the same shape.\nHowever, prediction of padding tokens should be excluded from loss calculations.\n\nTo this end, we can use the following `sequence_mask` function to mask irrelevant entries with zero values so later multiplication of any irrelevant prediction with zero equals to zero. For example, if the valid length of two sequences excluding padding tokens (i.e., pads each sequence to the same length usually matching the longest sequence) are one and two, respectively, the remaining entries after the first one and the first two entries are cleared to zeros.\n\n\n\n```python\ndef sequence_mask(X, valid_len, value=0):\n \"\"\"Mask irrelevant entries in sequences.\"\"\"\n maxlen = X.size(1)\n mask = torch.arange((maxlen), dtype=torch.float32,\n device=X.device)[None, :] < valid_len[:, None]\n X[~mask] = value\n return X\n\n\nX = torch.tensor([[1, 2, 3], [4, 5, 6]])\nprint(sequence_mask(X, torch.tensor([1, 2])))\nX = torch.ones(2, 3, 4)\nprint(sequence_mask(X, torch.tensor([1, 2]), value=-1))\n```\n\nNow we can extend the softmax cross-entropy loss\nto allow the masking of irrelevant predictions.\nInitially,\nmasks for all the predicted tokens are set to one.\nOnce the valid length is given,\nthe mask corresponding to any padding token\nwill be cleared to zero.\nIn the end,\nthe loss for all the tokens\nwill be multipled by the mask to filter out\nirrelevant predictions of padding tokens in the loss.\n\n\n\n```python\nclass MaskedSoftmaxCELoss(nn.CrossEntropyLoss):\n \"\"\"The softmax cross-entropy loss with masks.\"\"\"\n\n # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)\n # `label` shape: (`batch_size`, `num_steps`)\n # `valid_len` shape: (`batch_size`,)\n\n def forward(self, pred, label, valid_len):\n weights = torch.ones_like(label)\n weights = sequence_mask(weights, valid_len)\n self.reduction = 'none'\n unweighted_loss = super(MaskedSoftmaxCELoss,\n self).forward(pred.permute(0, 2, 1), label)\n weighted_loss = (unweighted_loss * weights).mean(dim=1)\n\n return weighted_loss\n\n\nloss = MaskedSoftmaxCELoss()\nloss(torch.ones(3, 4, 10),\n torch.ones((3, 4), dtype=torch.long),\n torch.tensor([4, 2, 0]))\n```\n\nIn the following training loop,\nwe concatenate the special beginning-of-sequence token\nand the original output sequence excluding the final token as\nthe input to the decoder.\nThis is called *teacher forcing* because\nthe original output sequence (token labels) is fed into the decoder.\nAlternatively,\nwe could also feed the *predicted* token\nfrom the previous time step\nas the current input to the decoder.\n\n\n```python\n#@title Training\ndef train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):\n \"\"\"Train a model for sequence to sequence.\"\"\"\n def xavier_init_weights(m):\n if type(m) == nn.Linear:\n nn.init.xavier_uniform_(m.weight)\n if type(m) == nn.GRU:\n for param in m._flat_weights_names:\n if \"weight\" in param:\n nn.init.xavier_uniform_(m._parameters[param])\n\n\n net.apply(xavier_init_weights)\n net.to(device)\n optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n loss = MaskedSoftmaxCELoss()\n net.train()\n animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n xlim=[10, num_epochs])\n for epoch in range(num_epochs):\n timer = d2l.Timer()\n metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens\n for batch in data_iter:\n optimizer.zero_grad()\n X, X_valid_len, Y, Y_valid_len = [x.to(device) for x in batch]\n bos = torch.tensor([tgt_vocab['']] * Y.shape[0],\n device=device).reshape(-1, 1)\n dec_input = torch.cat([bos, Y[:, :-1]], 1) # Teacher forcing\n Y_hat, _ = net(X, dec_input, X_valid_len)\n l = loss(Y_hat, Y, Y_valid_len)\n l.sum().backward() # Make the loss scalar for `backward`\n d2l.grad_clipping(net, 1)\n num_tokens = Y_valid_len.sum()\n optimizer.step()\n with torch.no_grad():\n metric.add(l.sum(), num_tokens)\n if (epoch + 1) % 10 == 0:\n animator.add(epoch + 1, (metric[0] / metric[1],))\n print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n f'tokens/sec on {str(device)}')\n```\n\nNow we can create and train an RNN encoder-decoder model\nfor sequence to sequence learning on the machine translation dataset.\n\n\n\n```python\nembed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1\nbatch_size, num_steps = 64, 10\nlr, num_epochs = 0.005, 300\n\ntrain_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\nencoder = Seq2SeqEncoder(len(src_vocab), embed_size, num_hiddens, num_layers,\n dropout)\ndecoder = Seq2SeqDecoder(len(tgt_vocab), embed_size, num_hiddens, num_layers,\n dropout)\nnet = d2l.EncoderDecoder(encoder, decoder)\ntrain_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, DEVICE)\n```\n\nTo predict the output sequence token by token, at each decoder time step\nthe predicted token from the previous time step is fed into the decoder as an input.\n\nSimilar to training, at the initial time step the beginning-of-sequence (<bos>\") token is fed into the decoder. This prediction process is illustrated in `seq2seq` figure. When the end-of-sequence (\"<eos>\") token is predicted, the prediction of the output sequence is complete.\n\n\n
\n \n
\n Source d2l.ai\n
\n
\n\n\n```python\n# @title Prediction\ndef predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,\n device, save_attention_weights=False):\n \"\"\"Predict for sequence to sequence.\"\"\"\n # Set `net` to eval mode for inference\n net.eval()\n src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n src_vocab['']]\n enc_valid_len = torch.tensor([len(src_tokens)], device=device)\n src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab[''])\n # Add the batch axis\n enc_X = torch.unsqueeze(\n torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0)\n enc_outputs = net.encoder(enc_X, enc_valid_len)\n dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n # Add the batch axis\n dec_X = torch.unsqueeze(\n torch.tensor([tgt_vocab['']], dtype=torch.long, device=device),\n dim=0)\n output_seq, attention_weight_seq = [], []\n for _ in range(num_steps):\n Y, dec_state = net.decoder(dec_X, dec_state)\n # We use the token with the highest prediction likelihood as the input\n # of the decoder at the next time step\n dec_X = Y.argmax(dim=2)\n pred = dec_X.squeeze(dim=0).type(torch.int32).item()\n # Save attention weights (to be covered later)\n if save_attention_weights:\n attention_weight_seq.append(net.decoder.attention_weights)\n # Once the end-of-sequence token is predicted, the generation of the\n # output sequence is complete\n if pred == tgt_vocab['']:\n break\n output_seq.append(pred)\n return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq\n```\n\nWe can evaluate a predicted sequence by comparing it with the label sequence (the ground-truth). BLEU (Bilingual Evaluation Understudy), though originally proposed for evaluating machine translation results in [Papieni et al., 2002](https://dl.acm.org/doi/10.3115/1073083.1073135), has been extensively used in measuring the quality of output sequences for different applications.\n\nIn principle, for any $n$-grams in the predicted sequence, BLEU evaluates whether this $n$-grams appears in the label sequence.\n\nDenote by $p_n$ the precision of $n$-grams, which is the ratio of the number of matched $n$-grams in the predicted and label sequences to the number of $n$-grams in the predicted sequence.\nTo explain, given a label sequence $A$, $B$, $C$, $D$, $E$, $F$, and a predicted sequence $A$, $B$, $B$, $C$, $D$, we have $p_1 = 4/5$, $p_2 = 3/4$, $p_3 = 1/3$, and $p_4 = 0$.\n\nBesides, let $\\mathrm{len}_{\\text{label}}$ and $\\mathrm{len}_{\\text{pred}}$\nbe the numbers of tokens in the label sequence and the predicted sequence, respectively.\n\nThen, BLEU is defined as\n\n\\begin{equation}\n\\exp\\left(\\min\\left(0, 1 - \\frac{\\mathrm{len}_{\\text{label}}}{\\mathrm{len}_{\\text{pred}}}\\right)\\right) \\prod_{n=1}^k p_n^{1/2^n},\n\\end{equation}\n\nwhere $k$ is the longest $n$-grams for matching.\n\nBased on the definition of BLEU in the above equation, whenever the predicted sequence is the same as the label sequence, BLEU is 1.\n\nMoreover, since matching longer $n$-grams is more difficult, BLEU assigns a greater weight to a longer $n$-gram precision. Specifically, when $p_n$ is fixed, $p_n^{1/2^n}$ increases as $n$ grows (the original paper uses $p_n^{1/n}$).\n\nFurthermore, since predicting shorter sequences tends to obtain a higher $p_n$ value, the coefficient before the multiplication term in the above equation\npenalizes shorter predicted sequences.\n\nFor example, when $k=2$, given the label sequence $A$, $B$, $C$, $D$, $E$, $F$ and the predicted sequence $A$, $B$, although $p_1 = p_2 = 1$, the penalty factor $\\exp(1-6/2) \\approx 0.14$ lowers the BLEU.\n\nWe implement the BLEU measure as follows.\n\n\n\n```python\n#@title Evaluation of Predicted Sequences\ndef bleu(pred_seq, label_seq, k):\n \"\"\"Compute the BLEU.\"\"\"\n pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n len_pred, len_label = len(pred_tokens), len(label_tokens)\n score = math.exp(min(0, 1 - len_label / len_pred))\n for n in range(1, k + 1):\n num_matches, label_subs = 0, collections.defaultdict(int)\n for i in range(len_label - n + 1):\n label_subs[''.join(label_tokens[i:i + n])] += 1\n for i in range(len_pred - n + 1):\n if label_subs[''.join(pred_tokens[i:i + n])] > 0:\n num_matches += 1\n label_subs[''.join(pred_tokens[i:i + n])] -= 1\n score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n return score\n```\n\nIn the end,\nwe use the trained RNN encoder-decoder\nto translate a few English sentences into French\nand compute the BLEU of the results.\n\n\n\n```python\nengs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\n# fras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\nfras = [ 'je suis chez moi .', 'j\\'ai perdu .','va !', 'il est calme .']\nfor eng, fra in zip(engs, fras):\n translation, attention_weight_seq = predict_seq2seq(net,\n eng,\n src_vocab,\n tgt_vocab,\n num_steps,\n DEVICE)\n print(f'{eng} => {translation}, bleu {bleu(translation, fra, k=2):.3f}')\n```\n\n---\n# Section 4: Ethical aspects\n\n*Time estimate: ~7mins*\n\n\n```python\n# @title Video 5: Ethics of Representation and Generation\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1v54y1J7SC\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"2ULMWtaGQrQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 5: Ethics of Representation and Generation')\n\ndisplay(out)\n```\n\n---\n# Summary\n\nDuring this day, we have learned about modern RNNs and their variants. Now let's see some ethical aspects of representation and Generation, and then we will close the tutorials with an overview.\n\n\n```python\n# @title Video 6: Beyond Sequence\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1864y1x7Ek\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"lVcpMSJileA\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 6: Beyond Sequence')\n\ndisplay(out)\n```\n\n\n```python\n# @title Airtable Submission Link\nfrom IPython import display as IPydisplay\nIPydisplay.HTML(\n f\"\"\"\n
\n \n \n
\"\"\" )\n```\n\n\n\n\n\n
\n \n \n
\n\n\n\n---\n# Bonus: Attention\n\n\n```python\n# @title Video 7: Attention mechanisms\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Mo4y1S7oK\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"Vt9GhJKcEiM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\n# add event to airtable\natform.add_event('Video 7: Attention mechanisms')\n\ndisplay(out)\n```\n\n\n Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})\n\n\nPreviously, we designed an encoder-decoder architecture based on two RNNs for sequence to sequence learning. Specifically, the RNN encoder transforms a variable-length sequence into a fixed-shape context variable, then the RNN decoder generates the output (target) sequence token by token based on the generated tokens and the context variable. However, even though not all the input (source) tokens are useful for decoding a certain token, the same context variable that encodes the entire input sequence is still used at each decoding step. It is challenging for the models to deal with long sentences. \n\nIn [Bahdanau et al., 2014](https://arxiv.org/abs/1409.0473), the authors proposed a technique called attention. When predicting a token, if not all the input tokens are relevant, the model aligns (or attends) only to parts of the input sequence that are relevant to the current prediction. \n\n\nIn contrast to seq2seq model, the encoder passes a lot more data to the decoder. Instead of passing the last hidden state of the encoding stage, the encoder passes all the hidden states to the decoder. \n\nIn order to focus on the parts of input relevant to the decoder, look at the set of encoder hidden states it received. Each encoder hidden state is at most associated with a certain word in the input sentence. We can assign each hidden state a score and multiply it with the softmaxed score, thus amplifying hidden states with high scores, and drowning out hidden states with low scores.\n\n\nReference Links: \\\\\n https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/ \\\\\n\n https://d2l.ai/chapter_attention-mechanisms/attention-cues.html\n\n\n```python\n# @markdown Media 1: Sequence to Sequence model with Attention\n\nurl = \"https://jalammar.github.io/images/seq2seq_7.mp4\"\nfrom IPython.display import HTML\nHTML(f\"\"\"
\n\n## In this tutorial module we explain the algorithm used to get the primitive variables out of the conservative ones\n\n### Required and recommended citations:\n\n* **(Required)** Etienne, Z. B., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L. IllinoisGRMHD: an open-source, user-friendly GRMHD code for dynamical spacetimes. Class. Quantum Grav. 32 (2015) 175009. ([arxiv:1501.07276](http://arxiv.org/abs/1501.07276)).\n* **(Required)** Noble, S. C., Gammie, C. F., McKinney, J. C., Del Zanna, L. Primitive Variable Solvers for Conservative General Relativistic Magnetohydrodynamics. Astrophysical Journal, 641, 626 (2006) ([astro-ph/0512420](https://arxiv.org/abs/astro-ph/0512420)).\n* **(Recommended)** Del Zanna, L., Bucciantini N., Londrillo, P. An efficient shock-capturing central-type scheme for multidimensional relativistic flows - II. Magnetohydrodynamics. A&A 400 (2) 397-413 (2003). DOI: 10.1051/0004-6361:20021641 ([astro-ph/0210618](https://arxiv.org/abs/astro-ph/0210618)).\n\nIf using the version of `IllinoisGRMHD` with piecewise polytropic *or* tabulated (coming soon!) EOS support, then the following citation is also required:\n\n* **(Required)** Etienne, Z. B., Werneck, L., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L., *IllinoisGRMHD github repository* (2019). Source Code URL: https://github.com/zachetienne/nrpytutorial/tree/master/IllinoisGRMHD/.\n\n### Dependencies\n\nThe files generated in this tutorial notebook depend on the following files:\n\n* `IllinoisGRMHD_headers.h` \\[[**tutorial**](Tutorial-IllinoisGRMHD__IllinoisGRMHD_headers.ipynb)\\]\n* `apply_tau_floor__enforce_limits_on_primitives_and_recompute_conservs.C` \\[[**tutorial**](Tutorial-IllinoisGRMHD__apply_tau_floor__enforce_limits_on_primitives_and_recompute_conservs.ipynb)\\]\n* `IllinoisGRMHD_convert_ADM_to_BSSN__enforce_detgtij_eq_1__and_compute_gtupij.C` \\[[**tutorial**](Tutorial-IllinoisGRMHD__convert_ADM_to_BSSN__enforce_detgtij_eq_1__and_compute_gtupij.ipynb)\\]\n* `IllinoisGRMHD_EoS_lowlevel_functs.C` \\[[**tutorial**](Tutorial-IllinoisGRMHD__EoS_lowlevel_functs.ipynb)\\]\n* `harm_utoprim_2d.c` \\[[**tutorial**](Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb)\\]\n* `harm_u2p_util.c` \\[[**tutorial**](Tutorial-IllinoisGRMHD__harm_u2p_util.ipynb)\\]\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis module is organized as follows\n\n0. [Step 0](#src_dir): **Source directory creation**\n1. [Step 1](#introduction): **Introduction**\n1. [Step 2](#driver_conserv_to_prims): **`driver_conserv_to_prims.C`**\n 1. [Step 2.a](#equatorial_symmetry): *Applying equatorial symmetry*\n 1. [Step 2.b](#c2p): *Conservative-to-primitives*\n 1. [Step 2.b.i](#variable_setup__prims_conservs): Reading in primitives and conservatives\n 1. [Step 2.b.ii](#variable_setup__adm_3metric): Reading in the physical metric\n 1. [Step 2.b.iii](#variable_setup__temp_conservs): Temporary storage for current values of the conservative variables\n 1. [Step 2.b.iv](#c2p_fct_call): Invoking the conservative-to-primitive algorithm\n 1. [Step 2.b.v](#standalone__update_prims_conservs): Standalone routine: updating conservatives and primitives\n \n 1. [Step 2.c](#updating_tdnmunu): *Updating $T_{\\mu\\nu}^{\\rm GRMHD}$*\n 1. [Step 2.d](#diagnostics_and_debugging_tools): *Diagnostics and debugging tools*\n1. [Step 3](#noble2d_con2prim_onepoint): **The `IllinoisGRMHD_Noble2D_con2prim_onepoint.C` file**\n 1. [Step 3.a](#compute_sqrtgamma_gammainv): *Computing $\\sqrt{\\gamma}$ and $\\gamma^{ij}$ from ADM variables*\n 1. [Step 3.b](#compute_g4dn): *Computing $g_{\\mu\\nu}$ from ADM variables*\n 1. [Step 3.c](#compute_g4up): *Computing $g^{\\mu\\nu}$ from ADM variables*\n 1. [Step 3.d](#c2p): *Compute primitives from conservatives*\n1. [Step 4](#harm_primitives_lowlevel): **`harm_primitives_lowlevel.C`**\n 1. [Step 4.a](#variables_needed_by_harm__bi_harm): *Computing $B^{i}_{\\rm HARM}$*\n 1. [Step 4.b](#variables_needed_by_harm__init_rhob_pressure_vi): *Initializing $\\rho_{b}$, $P$, and $v^{i}$*\n 1. [Step 4.c](#variables_needed_by_harm__original_conserv): *Storing the original values of the conservative variables*\n 1. [Step 4.d](#variables_needed_by_harm__guessing_rhob_pressure_vi): *Guessing $\\rho_{b}$, $P$, and $v^{i}$*\n 1. [Step 4.e](#variables_needed_by_harm__conservs): *Writing $\\boldsymbol{C}_{\\rm HARM}$ in terms of $\\boldsymbol{C}_{\\rm IGM}$*\n 1. [Step 4.f](#variables_needed_by_harm__prims): *Writing $\\boldsymbol{P}_{\\rm HARM}$ in terms of $\\boldsymbol{P}_{\\rm IGM}$*\n 1. [Step 4.g](#calling_harm_conservs_to_prims_solver): *Calling the `HARM` conservative-to-primitive solver*\n 1. [Step 4.h](#font_fix): *Applying the Font *et al.* fix, if the inversion fails*\n 1. [Step 4.i](#compute_utconi): *Compute $\\tilde{u}^{i}$*\n 1. [Step 4.j](#limiting_velocities): *Limiting velocities*\n 1. [Step 4.k](#primitives): *Setting the primitives*\n1. [Step 5](#font_fix_gamma_law__c): **`font_fix_gamma_law.C`**\n 1. [Step 5.a](#font_fix_gamma_law__basic_quantities): Computing the basic quantities needed by the algorithm\n 1. [Step 5.b](#font_fix_gamma_law__initial_guesses): Initial guesses for $W$, $S_{{\\rm fluid}}^{2}$, and $\\rho$\n 1. [Step 5.c](#font_fix_main_loop): Font fix main loop\n 1. [Step 5.d](#font_fix_gamma_law__outputs): Output $\\rho_{b}$ and $u_{i}$\n 1. [Step 5.e](#font_fix__rhob_loop): The `font_fix__rhob_loop()` function\n1. [Step 6](#harm_primitives_headers): **`harm_primitives_headers.h`**\n1. [Step 7](#code_validation): **Code validation**\n 1. [Step 7.a](#driver_conserv_to_prims_validation): *`driver_conserv_to_prims.C`*\n 1. [Step 7.b](#harm_primitives_lowlevel_validation): *`harm_primitives_lowlevel.C`*\n 1. [Step 7.c](#font_fix_gamma_law_validation): *`font_fix_gamma_law.C`*\n 1. [Step 7.d](#harm_primitives_headers_validation): *`harm_primitives_headers.h`*\n1. [Step 8](#latex_pdf_output): **Output this notebook to $\\LaTeX$-formatted PDF file**\n\n\n\n# Step 0: Source directory creation \\[Back to [top](#toc)\\]\n$$\\label{src_dir}$$\n\nWe will now use the [cmdline_helper.py NRPy+ module](Tutorial-Tutorial-cmdline_helper.ipynb) to create the source directory within the `IllinoisGRMHD` NRPy+ directory, if it does not exist yet.\n\n\n```python\n# Step 0: Creation of the IllinoisGRMHD source directory\n# Step 0a: Add NRPy's directory to the path\n# https://stackoverflow.com/questions/16780014/import-file-from-parent-directory\nimport os,sys\nnrpy_dir_path = os.path.join(\"..\",\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Step 0b: Load up cmdline_helper and create the directory\nimport cmdline_helper as cmd\noutdir = os.path.join(\"..\",\"src\")\ncmd.mkdir(outdir)\n```\n\n\n\n# Step 1: Introduction \\[Back to [top](#toc)\\]\n$$\\label{introduction}$$\n\n\n\n# Step 2: `driver_conserv_to_prims.C` \\[Back to [top](#toc)\\]\n$$\\label{driver_conserv_to_prims}$$\n\nWe start here by creating the `driver_conserv_to_prims.C` file and loading all files used by it. Note that of the files loaded, we have the following `IllinoisGRMHD` files:\n\n1. `harm_primitives_headers.h`: we will discuss this file [in step 4 of this tutorial module](#harm_primitives_headers).\n1. `apply_tau_floor__enforce_limits_on_primitives_and_recompute_conservs.C`: this file is discussed in the [apply_tau_floor__enforce_limits_on_primitives_and_recompute_conservs NRPy tutorial module](Tutorial-IllinoisGRMHD__apply_tau_floor__enforce_limits_on_primitives_and_recompute_conservs.ipynb)\n\n\n```python\n%%writefile $outdir/driver_conserv_to_prims.C\n/* We evolve forward in time a set of functions called the \n * \"conservative variables\", and any time the conserv's\n * are updated, we must solve for the primitive variables \n * (rho, pressure, velocities) using a Newton-Raphson \n * technique, before reconstructing & evaluating the RHSs\n * of the MHD equations again. \n *\n * This file contains the driver routine for this Newton-\n * Raphson solver. Truncation errors in conservative \n * variables can lead to no physical solutions in \n * primitive variables. We correct for these errors here \n * through a number of tricks described in the appendices \n * of http://arxiv.org/pdf/1112.0568.pdf.\n *\n * This is a wrapper for the 2d solver of Noble et al. See \n * harm_utoprim_2d.c for references and copyright notice \n * for that solver. This wrapper was primarily written by\n * Zachariah Etienne & Yuk Tung Liu, in 2011-2013.\n * \n * For optimal compatibility, this wrapper is licensed under \n * the GPL v2 or any later version.\n *\n * Note that this code assumes a simple gamma law for the \n * moment, though it would be easy to extend to a piecewise\n * polytrope. */\n\n// Standard #include's\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#ifdef ENABLE_STANDALONE_IGM_C2P_SOLVER\n#include \"standalone_conserv_to_prims_main_function.h\"\n#else\n#include \"cctk.h\"\n#include \"cctk_Arguments.h\"\n#include \"cctk_Parameters.h\"\n#include \"Symmetry.h\"\n\n#include \"IllinoisGRMHD_headers.h\"\n#include \"harm_primitives_headers.h\"\n#include \"harm_u2p_util.c\"\n#include \"apply_tau_floor__enforce_limits_on_primitives_and_recompute_conservs.C\"\n#include \"IllinoisGRMHD_Noble2D_con2prim_onepoint.C\"\n\nextern \"C\" void IllinoisGRMHD_conserv_to_prims(CCTK_ARGUMENTS) {\n DECLARE_CCTK_ARGUMENTS;\n DECLARE_CCTK_PARAMETERS;\n \n // We use proper C++ here, for file I/O later.\n using namespace std;\n#endif\n \n /**********************************\n * Piecewise Polytropic EOS Patch *\n * Setting up the EOS struct *\n **********************************/\n /*\n * The short piece of code below takes care of\n * initializing the EOS parameters. Please refer\n * to the \"IllinoisGRMHD_EoS_lowlevel_functs.C\"\n * source file for the documentation on the\n * function.\n */\n eos_struct eos;\n initialize_EOS_struct_from_input(eos);\n```\n\n Overwriting ../src/driver_conserv_to_prims.C\n\n\n\n\n## Step 2.a: Applying equatorial symmetry \\[Back to [top](#toc)\\]\n$$\\label{equatorial_symmetry}$$\n\nWe then use the [CardGrid3D ETK thorn](https://einsteintoolkit.org/thornguide/CactusBase/CartGrid3D/documentation.html) to apply equatorial symmetry to our problem.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n if(CCTK_EQUALS(Symmetry,\"equatorial\")) {\n // SET SYMMETRY GHOSTZONES ON ALL CONSERVATIVE VARIABLES!\n int ierr=0;\n ierr+=CartSymGN(cctkGH,\"IllinoisGRMHD::grmhd_conservatives\");\n // FIXME: UGLY. Filling metric ghostzones is needed for, e.g., Cowling runs.\n ierr+=CartSymGN(cctkGH,\"lapse::lapse_vars\");\n ierr+=CartSymGN(cctkGH,\"bssn::BSSN_vars\");\n ierr+=CartSymGN(cctkGH,\"bssn::BSSN_AH\");\n ierr+=CartSymGN(cctkGH,\"shift::shift_vars\");\n if(ierr!=0) CCTK_VError(VERR_DEF_PARAMS,\"IllinoisGRMHD ERROR (grep for it, foo!) :(\");\n }\n#endif\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n## Step 2.b: Setting up the variables needed by `HARM` \\[Back to [top](#toc)\\]\n$$\\label{variable_setup}$$\n\nWe will now set up all the necessary variables to start the conservative to primitive algorithm. We begin by declaring useful debugging variables.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n //Start the timer, so we can benchmark the primitives solver during evolution.\n // Slower solver -> harder to find roots -> things may be going crazy!\n //FIXME: Replace this timing benchmark with something more meaningful, like the avg # of Newton-Raphson iterations per gridpoint!\n /*\n struct timeval start, end;\n long mtime, seconds, useconds;\n gettimeofday(&start, NULL);\n */\n\n int failures=0,font_fixes=0,vel_limited_ptcount=0;\n int pointcount=0;\n int failures_inhoriz=0;\n int pointcount_inhoriz=0;\n\n int pressure_cap_hit=0;\n\n CCTK_REAL error_int_numer=0,error_int_denom=0;\n\n int imin=0,jmin=0,kmin=0;\n int imax=cctk_lsh[0],jmax=cctk_lsh[1],kmax=cctk_lsh[2];\n\n int rho_star_fix_applied=0;\n long n_iter=0;\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n### Step 2.b.i: Reading in primitives and conservatives \\[Back to [top](#toc)\\]\n$$\\label{variable_setup__prims_conservs}$$\n\nWe load our current known values for the primitive variables, $\\left(\\rho_{b}, P, v^{i}, B^{i}\\right)$, into a new array called $\\rm PRIMS$, and the conservative variables, $\\left(\\rho_{\\star}, \\tilde{S}_{i},\\tilde\\tau\\right)$, into a new array called $\\rm CONSERVS$. Note that this is a ***pointwise*** operation.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n#pragma omp parallel for reduction(+:failures,vel_limited_ptcount,font_fixes,pointcount,failures_inhoriz,pointcount_inhoriz,error_int_numer,error_int_denom,pressure_cap_hit,rho_star_fix_applied,n_iter) schedule(static)\n for(int k=kmin;k\n\n### Step 2.b.ii: Reading in the physical metric \\[Back to [top](#toc)\\]\n$$\\label{variable_setup__adm_3metric}$$\n\nThen we load our current known values for the ADM 3-metric variables, $\\left(\\alpha,\\beta^{i},\\gamma_{ij}\\right)$. Note that this is a ***pointwise*** operation.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n CCTK_REAL ADM_3METRIC[NUMVARS_FOR_ADM_3METRIC];\n ADM_3METRIC[GAMMAXX] = gxx[index];\n ADM_3METRIC[GAMMAXY] = gxy[index];\n ADM_3METRIC[GAMMAXZ] = gxz[index];\n ADM_3METRIC[GAMMAYY] = gyy[index];\n ADM_3METRIC[GAMMAYZ] = gyz[index];\n ADM_3METRIC[GAMMAZZ] = gzz[index];\n\n ADM_3METRIC[ALPHA] = alp[index];\n\n ADM_3METRIC[BETAX] = betax[index];\n ADM_3METRIC[BETAY] = betay[index];\n ADM_3METRIC[BETAZ] = betaz[index];\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n### Step 2.b.iii: Temporary storage for current values of the conservative variables \\[Back to [top](#toc)\\]\n$$\\label{variable_setup__temp_conservs}$$\n\nInstead of declaring new variables to store the currently known values of the conservative variables $\\left(\\rho_{\\star}, \\tilde{S}_{i}, \\tilde{\\tau}\\right)$, we will simply use the flux variables $\\left(\\rho_{\\star}^{\\rm flux}, \\tilde{S}_{i}^{\\rm flux}, \\tilde{\\tau}^{\\rm flux}\\right)$, which are used elsewhere in `IllinoisGRMHD`, as temporary storage. This is done for debugging purposes.\n\nWe also store the original values in the variables $\\left(\\rho_{\\star}^{\\rm orig}, \\tilde{S}_{i}^{\\rm orig}, \\tilde{\\tau}^{\\rm orig}\\right)$. Note that because we are now using the $\\rm CONSERVS$ array, this is also a ***pointwise*** operation.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n // Here we use _flux variables as temp storage for original values of conservative variables.. This is used for debugging purposes only.\n rho_star_flux[index] = CONSERVS[RHOSTAR];\n st_x_flux[index] = CONSERVS[STILDEX];\n st_y_flux[index] = CONSERVS[STILDEY];\n st_z_flux[index] = CONSERVS[STILDEZ];\n tau_flux[index] = CONSERVS[TAUENERGY];\n#endif\n\n CCTK_REAL rho_star_orig = CONSERVS[RHOSTAR];\n CCTK_REAL mhd_st_x_orig = CONSERVS[STILDEX];\n CCTK_REAL mhd_st_y_orig = CONSERVS[STILDEY];\n CCTK_REAL mhd_st_z_orig = CONSERVS[STILDEZ];\n CCTK_REAL tau_orig = CONSERVS[TAUENERGY];\n\n struct output_stats stats;\n stats.n_iter=0;\n stats.vel_limited=0;\n stats.failure_checker=0;\n stats.rho_star_fix_applied=0;\n\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n### Step 2.b.iv: Invoking the conservative-to-primitive algorithm \\[Back to [top](#toc)\\]\n$$\\label{c2p_fct_call}$$\n\nWe now call the `IllinoisGRMHD_Noble2D_con2prim_onepoint()` function (documented [below](#noble2d_con2prim_onepoint)) to perform the conservative-to-primitive (C2P) operation.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n CCTK_REAL TUPMUNU[10],TDNMUNU[10];\n /*\n if(i==14 && j==14 && k==14) {\n printf(\"HEY1 %e %e %e %e %e\\n\",CONSERVS[RHOSTAR],CONSERVS[STILDEX],CONSERVS[STILDEY],CONSERVS[STILDEZ],CONSERVS[TAUENERGY]);\n printf(\"HEY2 %e %e %e %e %e %e\\n\",ADM_3METRIC[GAMMAXX],ADM_3METRIC[GAMMAXY],ADM_3METRIC[GAMMAXZ],ADM_3METRIC[GAMMAYY],ADM_3METRIC[GAMMAYZ],ADM_3METRIC[GAMMAZZ]);\n }\n */\n int check = IllinoisGRMHD_Noble2D_con2prim_onepoint(eos,stats, CONSERVS,ADM_3METRIC, TUPMUNU,TDNMUNU,PRIMS);\n /*\n if(i==14 && j==14 && k==14) {\n printf(\"HEY3 %e %e %e %e %e\\n\",PRIMS[RHOB],PRIMS[PRESSURE],PRIMS[VX],PRIMS[VY],PRIMS[VZ]);\n printf(\"HEY4 %e %e %e %e %e\\n\",CONSERVS[RHOSTAR],CONSERVS[STILDEX],CONSERVS[STILDEY],CONSERVS[STILDEZ],CONSERVS[TAUENERGY]);\n }\n */\n rho_star_fix_applied += stats.rho_star_fix_applied;\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n### Step 2.b.v: Standalone routine: updating conservatives and primitives \\[Back to [top](#toc)\\]\n$$\\label{standalone__update_prims_conservs}$$\n\nIf the standalone flag is enabled, then we simply update the conservatives and primitives gridfunctions.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n // POST-C2P\n\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n rho_star[index] = CONSERVS[RHOSTAR];\n mhd_st_x[index] = CONSERVS[STILDEX];\n mhd_st_y[index] = CONSERVS[STILDEY];\n mhd_st_z[index] = CONSERVS[STILDEZ];\n tau[index] = CONSERVS[TAUENERGY];\n\n // Set primitives, and/or provide a better guess.\n rho_b[index] = PRIMS[RHOB];\n P[index] = PRIMS[PRESSURE];\n vx[index] = PRIMS[VX];\n vy[index] = PRIMS[VY];\n vz[index] = PRIMS[VZ];\n#endif\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n## Step 2.c: Updating $T_{\\mu\\nu}^{\\rm GRMHD}$ \\[Back to [top](#toc)\\]\n$$\\label{updating_tdnmunu}$$\n\nThe function `IllinoisGRMHD_Noble2D_con2prim_onepoint()` also computes $T_{\\mu\\nu}^{\\rm GRMHD}$, so we update the global variables ${\\rm eTmunu}$ (where ${\\rm mu,nu=t,x,y,z}$, and ${\\rm eTmunu}$ is a symmetric tensor). Note that this operation is only performed if the `update_Tmunu` variable is set to 1.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n if(update_Tmunu) {\n ww=0;\n eTtt[index] = TDNMUNU[ww]; ww++;\n eTtx[index] = TDNMUNU[ww]; ww++;\n eTty[index] = TDNMUNU[ww]; ww++;\n eTtz[index] = TDNMUNU[ww]; ww++;\n eTxx[index] = TDNMUNU[ww]; ww++;\n eTxy[index] = TDNMUNU[ww]; ww++;\n eTxz[index] = TDNMUNU[ww]; ww++;\n eTyy[index] = TDNMUNU[ww]; ww++;\n eTyz[index] = TDNMUNU[ww]; ww++;\n eTzz[index] = TDNMUNU[ww];\n }\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n## Step 2.d: Diagnostics and debugging tools \\[Back to [top](#toc)\\]\n$$\\label{diagnostics_and_debugging_tools}$$\n\nNow we simply append to the file useful diagnostics and debugging tools for our code.\n\n\n```python\n%%writefile -a $outdir/driver_conserv_to_prims.C\n\n\n error_int_numer += fabs(CONSERVS[TAUENERGY] - tau_orig) + fabs(CONSERVS[RHOSTAR] - rho_star_orig) + \n fabs(CONSERVS[STILDEX] - mhd_st_x_orig) + fabs(CONSERVS[STILDEY] - mhd_st_y_orig) + fabs(CONSERVS[STILDEZ] - mhd_st_z_orig);\n error_int_denom += tau_orig + rho_star_orig + fabs(mhd_st_x_orig) + fabs(mhd_st_y_orig) + fabs(mhd_st_z_orig);\n\n if(stats.font_fixed==1) font_fixes++;\n vel_limited_ptcount+=stats.vel_limited;\n if(check!=0) {\n failures++;\n if(ADM_3METRIC[SQRTGAMMA]>Psi6threshold) {\n failures_inhoriz++;\n pointcount_inhoriz++;\n }\n }\n pointcount++;\n /***************************************************************************************************************************/\n failure_checker[index] = stats.failure_checker;\n n_iter += stats.n_iter;\n }\n\n /*\n gettimeofday(&end, NULL);\n\n seconds = end.tv_sec - start.tv_sec;\n useconds = end.tv_usec - start.tv_usec;\n\n mtime = ((seconds) * 1000 + useconds/1000.0) + 0.999; // We add 0.999 since mtime is a long int; this rounds up the result before setting the value. Here, rounding down is incorrect.\n solutions per second: cctk_lsh[0]*cctk_lsh[1]*cctk_lsh[2] / ((CCTK_REAL)mtime/1000.0),\n */\n if(CCTK_Equals(verbose, \"essential\") || CCTK_Equals(verbose, \"essential+iteration output\")) {\n CCTK_VInfo(CCTK_THORNSTRING,\"C2P: Lev: %d NumPts= %d | Fixes: Font= %d VL= %d rho*= %d | Failures: %d InHoriz= %d / %d | Error: %.3e, ErrDenom: %.3e | %.2f iters/gridpt\",\n (int)GetRefinementLevel(cctkGH),\n pointcount,font_fixes,vel_limited_ptcount,rho_star_fix_applied,\n failures,\n failures_inhoriz,pointcount_inhoriz,\n error_int_numer/error_int_denom,error_int_denom,\n (double)n_iter/( (double)(cctk_lsh[0]*cctk_lsh[1]*cctk_lsh[2]) ));\n }\n \n // Very useful con2prim debugger. E.g., if the primitives (con2prim) solver fails, this will output all data needed to\n // debug where and why the solver failed. Strongly suggested for experimenting with new fixes.\n if(conserv_to_prims_debug==1 && error_int_numer/error_int_denom > 0.05) {\n\n ofstream myfile;\n char filename[100];\n srand(time(NULL));\n sprintf(filename,\"primitives_debug-%e.dat\",error_int_numer/error_int_denom);\n //Alternative, for debugging purposes as well:\n //srand(time(NULL));\n //sprintf(filename,\"primitives_debug-%d.dat\",rand());\n myfile.open (filename, ios::out | ios::binary);\n //myfile.open (\"data.bin\", ios::out | ios::binary);\n myfile.write((char*)cctk_lsh, 3*sizeof(int));\n\n myfile.write((char*)&GAMMA_SPEED_LIMIT, 1*sizeof(CCTK_REAL));\n\n myfile.write((char*)&rho_b_max, 1*sizeof(CCTK_REAL));\n myfile.write((char*)&rho_b_atm, 1*sizeof(CCTK_REAL));\n myfile.write((char*)&tau_atm, 1*sizeof(CCTK_REAL));\n\n myfile.write((char*)&Psi6threshold, 1*sizeof(CCTK_REAL));\n\n myfile.write((char*)&update_Tmunu, 1*sizeof(int));\n\n myfile.write((char*)&neos, 1*sizeof(int));\n myfile.write((char*)&Gamma_th, 1*sizeof(CCTK_REAL));\n myfile.write((char*)&K_ppoly_tab0, 1*sizeof(CCTK_REAL));\n myfile.write((char*)Gamma_ppoly_tab_in, neos*sizeof(CCTK_REAL));\n myfile.write((char*)rho_ppoly_tab_in, (neos-1)*sizeof(CCTK_REAL));\n\n int fullsize=cctk_lsh[0]*cctk_lsh[1]*cctk_lsh[2];\n myfile.write((char*)x, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)y, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)z, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char *)failure_checker, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTtt, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTtx, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTty, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTtz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTxx, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTxy, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTxz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTyy, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTyz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)eTzz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)alp, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)gxx, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)gxy, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)gxz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)gyy, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)gyz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)gzz, fullsize*sizeof(CCTK_REAL));\n myfile.write((char *)psi_bssn, fullsize*sizeof(CCTK_REAL));\n \n myfile.write((char*)phi_bssn, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtxx, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtxy, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtxz, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtyy, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtyz, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtzz, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char*)gtupxx, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtupxy, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtupxz, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtupyy, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtupyz, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)gtupzz, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char*)betax, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)betay, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)betaz, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char*)lapm1, (fullsize)*sizeof(CCTK_REAL));\n \n // HERE WE USE _flux variables as temp storage for original values of conservative variables.. This is used for debugging purposes only.\n myfile.write((char*)tau_flux, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)st_x_flux, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)st_y_flux, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)st_z_flux, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char*)rho_star_flux, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char*)Bx, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)By, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)Bz, (fullsize)*sizeof(CCTK_REAL));\n\n myfile.write((char*)vx, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)vy, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)vz, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)P, (fullsize)*sizeof(CCTK_REAL));\n myfile.write((char*)rho_b,(fullsize)*sizeof(CCTK_REAL));\n\n int checker=1063; myfile.write((char*)&checker,sizeof(int));\n\n myfile.close();\n CCTK_VInfo(CCTK_THORNSTRING,\"Finished writing %s\",filename);\n }\n\n#ifdef ENABLE_STANDALONE_IGM_C2P_SOLVER\n return 0; // int main() requires an integer be returned\n#endif\n\n}\n\n#include \"harm_primitives_lowlevel.C\"\n\n\n```\n\n Appending to ../src/driver_conserv_to_prims.C\n\n\n\n\n# Step 3: The `IllinoisGRMHD_Noble2D_con2prim_onepoint.C` file \\[Back to [top](#toc)\\]\n$$\\label{noble2d_con2prim_onepoint}$$\n\nThis is the main C2P loop, where we perform all tasks necessary for the algorithm. The general flow is the following:\n\n* Before performing the C2P\n * Determine $\\sqrt{\\gamma}$ and $\\gamma^{ij}$\n * Determine $g_{\\mu\\nu}$ from $\\left(\\alpha,\\beta^{i},\\gamma_{ij}\\right)$\n * Determine $g^{\\mu\\nu}$ from $\\left(\\alpha,\\beta^{i},\\gamma^{ij}\\right)$\n * Check whether or not we need to apply a floor to $\\rho_{\\star}$.\n * Check whether or not we need to apply a floor to $\\tilde{\\tau}$.\n* Invoke the C2P main routine\n * This is also the step in which we apply the Font fix routine, if necessary\n* After performing the C2P\n * Apply physical limits to the primitives and recompute the conservatives\n\n\n```python\n%%writefile $outdir/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\nint IllinoisGRMHD_Noble2D_con2prim_onepoint(struct eos_struct &eos, struct output_stats &stats, CCTK_REAL *CONSERVS,CCTK_REAL *ADM_3METRIC, CCTK_REAL *TUPMUNU,CCTK_REAL *TDNMUNU, CCTK_REAL *PRIMS) {\n\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n DECLARE_CCTK_PARAMETERS;\n#endif\n \n int check = 0;\n```\n\n Overwriting ../src/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n\n\n## Step 3.a: Computing $\\sqrt{\\gamma}$ and $\\gamma^{ij}$ from ADM variables \\[Back to [top](#toc)\\]\n$$\\label{compute_sqrtgamma_gammainv}$$\n\nWe now write down the code that computes the determinant of the physical ADM 3-metric, $\\sqrt{\\gamma}$, and its inverse, $\\gamma^{ij}$.\n\n\n```python\n# Import necessary Python system modules\nimport os,sys\n\n# Register NRPy+ root directory to the path\nnrpy_dir_path = os.path.join(\"..\",\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Import necessary Python/NRPy+ modules\nimport sympy as sp # Python module: used for symbolic expressions\nfrom outputC import * # NRPy+ module: used for C code output\nimport cmdline_helper as cmd # NRPy+ module: used for command line features\nimport indexedexp as ixp # NRPy+ module: used to generate indexed expressions (e.g. g_{\\mu\\nu})\nimport IllinoisGRMHD_output_functions as IGMout # NRPy+ module: IllinoisGRMHD specific output functions\n\n# Create the NRPy+ header file directory, if it doesn't already exist\nIGM_src_dir_path = os.path.join(\"..\",\"src\")\ncmd.mkdir(os.path.join(IGM_src_dir_path,\"NRPy_generated_headers\"))\nNRPy_headers_dir_path = os.path.join(IGM_src_dir_path,\"NRPy_generated_headers\")\n\n# Step 1.a: Set up gamma_{ij}\nDIM = 3\ngammaDD = ixp.zerorank2()\nfor i in range(DIM):\n for j in range(i,DIM):\n gammaDD[i][j] = gammaDD[j][i] = sp.Symbol('ADM_3METRIC[GAMMA'+chr(ord('X')+i)+chr(ord('X')+j)+\"]\",real=True)\n\n# Step 1.b: The compute_ADM_gammaUU_and_sqrtgamma.h file\n# Step 1.b.i: Compute eh inverse ADM 3-metric and the determinant of the ADM 3-metric\ngammaINVUU, gammaDET = ixp.symm_matrix_inverter3x3(gammaDD)\n\n# Step 1.b.ii: Populate ADM_3METRIC[GAMMAUPYZ] and ADM_3METRIC[SQRTGAMMA]\n# with the results of our inverter\nexprlist = [sp.sqrt(gammaDET)]\nvarslist = [\"ADM_3METRIC[SQRTGAMMA]\"]\nfor i in range(DIM):\n for j in range(i,DIM):\n exprlist.append(gammaINVUU[i][j])\n varslist.append(\"ADM_3METRIC[GAMMAUP\"+chr(ord('X')+i)+chr(ord('X')+j)+\"]\")\n\n# Step 1.c.i: Output result to string\nstring = outputC(exprlist,varslist,filename=\"returnstring\", params=\"outCverbose=False\")\n\n# Step 1.c.ii: Output result to file\nfilename = \"compute__ADM_gammaUU_and_sqrtgamma__in_terms_of__ADM_3METRIC.h\"\nfilepath = os.path.join(NRPy_headers_dir_path,filename)\nIGMout.NRPy_IGM_write_to_file(filepath,filename,string)\n```\n\n Just generated the file: ../src/NRPy_generated_headers/compute__ADM_gammaUU_and_sqrtgamma__in_terms_of__ADM_3METRIC.h\n\n\nWe then use the file we just generated to compute $\\sqrt{\\gamma}$ and $\\gamma^{ij}$ in `IllinoisGRMHD`.\n\n\n```python\n%%writefile -a $outdir/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n#include \"NRPy_generated_headers/compute__ADM_gammaUU_and_sqrtgamma__in_terms_of__ADM_3METRIC.h\"\n```\n\n Appending to ../src/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n\n\n## Step 3.b: Computing $g_{\\mu\\nu}$ from ADM variables \\[Back to [top](#toc)\\]\n$$\\label{compute_g4dn}$$\n\nWe now use the `g4DD_ito_BSSN_or_ADM()` function from the [BSSN/ADMBSSN_tofrom_4metric NRPy+ module](/edit/NRPyIGM/BSSN/ADMBSSN_tofrom_4metric.py) to compute $g_{\\mu\\nu}$ from the ADM variables.\n\n\n```python\n# Step 1.b: Compute the ADM 4-metric, g_{\\mu\\nu}\n# Step 1.b.i: Load the BSSN.ADMBSSN_tofrom_4metric NRPy+ module\nimport BSSN.ADMBSSN_tofrom_4metric as AB4m\n\n# Step 1.b.ii: Set up alpha\nalpha = sp.Symbol(\"ADM_3METRIC[ALPHA]\",real=True)\ngfslist = [[\"ALPHA\"]]\n# Step 1.b.iii: Set up beta^{i}\nbetaU = ixp.zerorank1()\nfor i in range(DIM):\n betaU[i] = sp.Symbol('ADM_3METRIC[BETA'+chr(ord('X')+i)+\"]\",real=True)\n gfslist.append([\"BETA\"+chr(ord('X')+i)])\n\n# Step 1.b.iv: Compute the g_{\\mu\\nu} in terms of our ADM variables\nAB4m.g4DD_ito_BSSN_or_ADM(\"ADM\",gammaDD=gammaDD,betaU=betaU,alpha=alpha)\ng4DD = AB4m.g4DD\n\n# Step 1.b.v: Set up lists to store the expressions and output variables\nexprlist = []\nnamelist = []\nfor mu in range(4):\n for nu in range(4):\n exprlist.append(g4DD[mu][nu])\n namelist.append(\"g4dn[\"+str(mu)+\"][\"+str(nu)+\"]\")\n \n# Step 1.b.vi: Convert our results to C output\nstring = outputC(exprlist,namelist,\"returnstring\", params=\"outCverbose=False\")\n\n# Step 1.b.vii: Output to file\nfilename = \"compute__g4DD__in_terms_of__ADM_3METRIC.h\"\nfilepath = os.path.join(NRPy_headers_dir_path,filename)\nIGMout.NRPy_IGM_write_to_file(filepath,filename,string)\n```\n\n Just generated the file: ../src/NRPy_generated_headers/compute__g4DD__in_terms_of__ADM_3METRIC.h\n\n\nWe then use the file we just generated to compute $g_{\\mu\\nu}$ in `IllinoisGRMHD`.\n\n\n```python\n%%writefile -a $outdir/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n CCTK_REAL g4dn[4][4];\n#include \"NRPy_generated_headers/compute__g4DD__in_terms_of__ADM_3METRIC.h\"\n```\n\n Appending to ../src/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n\n\n## Step 3.c: Computing $g^{\\mu\\nu}$ from ADM variables \\[Back to [top](#toc)\\]\n$$\\label{compute_g4up}$$\n\nWe now use the `g4UU_ito_BSSN_or_ADM()` function from the [BSSN/ADMBSSN_tofrom_4metric NRPy+ module](/edit/NRPyIGM/BSSN/ADMBSSN_tofrom_4metric.py) to compute $g^{\\mu\\nu}$ from the ADM variables.\n\n\n```python\n# Step 1.c.i: Set up gamma^{ij}\ngammaUU = ixp.zerorank2()\nfor i in range(3):\n for j in range(i,3):\n gammaUU[i][j] = gammaUU[j][i] = sp.Symbol('ADM_3METRIC[GAMMAUP'+chr(ord('X')+i)+chr(ord('X')+j)+\"]\",real=True)\n\n# Step 1.c.ii: Compute the g_{\\mu\\nu} in terms of our ADM variables\nAB4m.g4UU_ito_BSSN_or_ADM(\"ADM\",betaU=betaU,alpha=alpha,gammaUU=gammaUU)\ng4UU = AB4m.g4UU\n\n# Step 1.c.iii: Set up lists to store the expressions and output variables\nexprlist = []\nnamelist = []\nfor mu in range(4):\n for nu in range(4):\n exprlist.append(g4UU[mu][nu])\n namelist.append(\"g4up[\"+str(mu)+\"][\"+str(nu)+\"]\")\n \n# Step 1.c.iv: Convert our results to C output\nstring = outputC(exprlist,namelist,\"returnstring\", params=\"outCverbose=False\")\n\n# Step 1.c.v: Output to file\nfilename = \"compute__g4UU__in_terms_of__ADM_3METRIC.h\"\nfilepath = os.path.join(NRPy_headers_dir_path,filename)\nIGMout.NRPy_IGM_write_to_file(filepath,filename,string)\n```\n\n Just generated the file: ../src/NRPy_generated_headers/compute__g4UU__in_terms_of__ADM_3METRIC.h\n\n\nWe then use the file we just generated to compute $g^{\\mu\\nu}$ in `IllinoisGRMHD`.\n\n\n```python\n%%writefile -a $outdir/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n CCTK_REAL g4up[4][4];\n#include \"NRPy_generated_headers/compute__g4UU__in_terms_of__ADM_3METRIC.h\"\n```\n\n Appending to ../src/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n\n\n## Step 3.d: Compute primitives from conservatives \\[Back to [top](#toc)\\]\n$$\\label{c2p}$$\n\nWe now call upon the `harm_primitives_gammalaw_lowlevel()` function from `IllinoisGRMHD` to perform the C2P routine. Notice that to minimize the chance of failing in the C2P routine, we set up to call it 3 times. If at any point the algorithm converges, however, then we skip the extra calls.\n\nPrior to each call of the `harm_primitives_gammalaw_lowlevel()` function, we apply a floor to $\\tilde{\\tau}$ by invoking the `apply_tau_floor()` function.\n\nNotice that all of this is done *only* when $\\rho_{\\star}>0$. If we encounter a point where $\\rho_{\\star}\\leq0$, then we instead set $\\rho_{b}$ to its atmospheric value, compute $P=P_{\\rm cold}(\\rho_{b}^{\\rm atm})$, and set the velocities as $v^{i} = -\\beta^{i}$. This is the essence of the *$\\rho_{\\star}$ fix algorithm*.\n\nFinally, after the steps above are completed, we call upon the `IllinoisGRMHD_enforce_limits_on_primitives_and_recompute_conservs()` function, which, as its name suggests, enforces physical limits on the primitive variables and then recompute the conservatives from them.\n\n\n```python\n%%writefile -a $outdir/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n /* Idea: Apply a rho_star floor. rho_* = alpha*sqrt(gamma)*rho_b*u^0, so minimum rho_star is simply alpha*sqrt(gamma)*rho_b_atm*1.0\n if(CONSERVS[RHOSTAR] < ADM_3METRIC[ALPHA]*ADM_3METRIC[SQRTGAMMA]*rho_b_atm*1.0) {\n stats.failure_checker+=1;\n CONSERVS[RHOSTAR] = ADM_3METRIC[ALPHA]*ADM_3METRIC[SQRTGAMMA]*rho_b_atm*1.0;\n stats.rho_star_fix_applied=1;\n }\n */\n if(CONSERVS[RHOSTAR]>0.0) {\n // Apply the tau floor\n apply_tau_floor(tau_atm,rho_b_atm,Psi6threshold,PRIMS,ADM_3METRIC,stats,eos, CONSERVS);\n\n stats.font_fixed=0;\n for(int ii=0;ii<3;ii++) {\n check = harm_primitives_gammalaw_lowlevel(/*index,i,j,k,x,y,z,*/\n ADM_3METRIC,CONSERVS,PRIMS, g4dn,g4up, stats,eos);\n if(check==0) ii=4;\n else stats.failure_checker+=100000;\n }\n } else {\n stats.failure_checker+=1;\n PRIMS[RHOB] =rho_b_atm;\n \n /* Set P = P_cold */\n int polytropic_index = find_polytropic_K_and_Gamma_index(eos, rho_b_atm);\n CCTK_REAL K_ppoly_tab = eos.K_ppoly_tab[polytropic_index];\n CCTK_REAL Gamma_ppoly_tab = eos.K_ppoly_tab[polytropic_index];\n PRIMS[PRESSURE] = K_ppoly_tab*pow(rho_b_atm,Gamma_ppoly_tab);\n\n PRIMS[VX] = - ADM_3METRIC[BETAX];\n PRIMS[VY] = - ADM_3METRIC[BETAY];\n PRIMS[VZ] = - ADM_3METRIC[BETAZ];\n\n stats.rho_star_fix_applied=1;\n }\n // Enforce limits on primitive variables and recompute conservatives.\n const int already_computed_physical_metric_and_inverse=1;\n IllinoisGRMHD_enforce_limits_on_primitives_and_recompute_conservs(already_computed_physical_metric_and_inverse,PRIMS,stats,eos,ADM_3METRIC,g4dn,g4up, TUPMUNU,TDNMUNU,CONSERVS);\n\n return check;\n}\n\n```\n\n Appending to ../src/IllinoisGRMHD_Noble2D_con2prim_onepoint.C\n\n\n\n\n# Step 4: `harm_primitives_lowlevel.C` \\[Back to [top](#toc)\\]\n$$\\label{harm_primitives_lowlevel}$$\n\nWe will now begin documenting the `harm_primitives_lowlevel.C` code. Notice that in the latest iterations of `IllinoisGRMHD`, we have adapted this function so that it now supports both single and piecewise polytropic equations of state.\n\n\n```python\n%%writefile $outdir/harm_primitives_lowlevel.C\ninline int harm_primitives_gammalaw_lowlevel(/*const int index,const int i,const int j,const int k,CCTK_REAL *X,CCTK_REAL *Y,CCTK_REAL *Z,*/\n CCTK_REAL *ADM_3METRIC,\n CCTK_REAL *CONSERVS,CCTK_REAL *PRIMS,\n CCTK_REAL g4dn[NDIM][NDIM],CCTK_REAL g4up[NDIM][NDIM],\n struct output_stats &stats, eos_struct &eos) {\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n DECLARE_CCTK_PARAMETERS;\n#endif\n \n // declare some variables for HARM.\n CCTK_REAL U[NPR]; \n CCTK_REAL prim[NPR];\n CCTK_REAL detg = ADM_3METRIC[ALPHA]*ADM_3METRIC[SQRTGAMMA]; // == alpha sqrt{gamma} = alpha Psi^6\n\n // Check to see if the metric is positive-definite.\n // Note that this will slow down the code, and if the metric doesn't obey this, the run is probably too far gone to save,\n // though if it happens deep in the horizon, it might resurrect the run.\n /*\n CCTK_REAL lam1,lam2,lam3;\n CCTK_REAL M11 = CONF_METRIC[CM_GAMMATILDEXX], M12=CONF_METRIC[CM_GAMMATILDEXY], M13=CONF_METRIC[CM_GAMMATILDEXZ], M22=CONF_METRIC[CM_GAMMATILDEYY], M23=CONF_METRIC[CM_GAMMATILDEYZ], M33=CONF_METRIC[CM_GAMMATILDEZZ];\n eigenvalues_3by3_real_sym_matrix(lam1, lam2, lam3,M11, M12, M13, M22, M23, M33);\n if (lam1 < 0.0 || lam2 < 0.0 || lam3 < 0.0) {\n // Metric is not positive-defitive, reset the physical metric to be conformally-flat.\n CCTK_REAL psi4 = cbrt(ADM_3METRIC[SQRTGAMMA]*ADM_3METRIC[SQRTGAMMA]);\n CCTK_REAL psim4 = 1.0/psi4;\n ADM_3METRIC[GAMMAXX] = psi4;\n ADM_3METRIC[GAMMAXY] = 0.0;\n ADM_3METRIC[GAMMAXZ] = 0.0;\n ADM_3METRIC[GAMMAYY] = psi4;\n ADM_3METRIC[GAMMAYZ] = 0.0;\n ADM_3METRIC[GAMMAZZ] = psi4;\n ADM_3METRIC[GAMMAUPXX] = psim4;\n ADM_3METRIC[GAMMAUPXY] = 0.0;\n ADM_3METRIC[GAMMAUPXZ] = 0.0;\n ADM_3METRIC[GAMMAUPYY] = psim4;\n ADM_3METRIC[GAMMAUPYZ] = 0.0;\n ADM_3METRIC[GAMMAUPZZ] = psim4;\n }\n */\n```\n\n Overwriting ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.a: Computing $B^{i}_{\\rm HARM}$ \\[Back to [top](#toc)\\]\n$$\\label{variables_needed_by_harm__bi_harm}$$\n\nNow we must relate `HARM`'s $B^{i}_{\\rm HARM}$ with the variables used by `IllinoisGRMHD`. We can start by looking at eqs. (23), (24), and (31) in [Duez *et al.* (2005)](https://arxiv.org/pdf/astro-ph/0503420.pdf) to find the following useful relations\n\n$$\n{\\rm IllinoisGRMHD:}\\ \n\\left\\{\n\\begin{align}\n\\sqrt{4\\pi}b^{0} &= \\frac{u_{i}B^{i}}{\\alpha}\\ ,\\\\\n\\sqrt{4\\pi}b^{i} &= \\frac{B^{i}/\\alpha + \\sqrt{4\\pi}b^{0}u^{i}}{u^{0}}\\ .\n\\end{align}\n\\right.\n$$\n\nNow, if we look at eqs. (16) and (17) in [Gammie & McKinney (2003)](https://arxiv.org/pdf/astro-ph/0301509.pdf) we find the following relations\n\n$$\n{\\rm HARM:}\\ \n\\left\\{\n\\begin{align}\nb^{0} &= u_{i}B^{i}_{\\rm HARM}\\ ,\\\\\nb^{i} &= \\frac{B^{i}_{\\rm HARM} + b^{0}u^{i}}{u^{0}}\\ ,\n\\end{align}\n\\right.\n$$\n\nfrom which we can then find the relation\n\n$$\n\\boxed{B^{i}_{\\rm HARM} = \\frac{B^{i}}{\\alpha\\sqrt{4\\pi}}}\\ .\n$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n // Note that ONE_OVER_SQRT_4PI gets us to the object\n // referred to as B^i in the Noble et al paper (and\n // apparently also in the comments to their code).\n // This is NOT the \\mathcal{B}^i, which differs by \n // a factor of the lapse.\n CCTK_REAL inv_lapse = 1.0/ADM_3METRIC[ALPHA];\n CCTK_REAL BxL_over_alpha_sqrt_fourpi = PRIMS[BX_CENTER]*inv_lapse*ONE_OVER_SQRT_4PI;\n CCTK_REAL ByL_over_alpha_sqrt_fourpi = PRIMS[BY_CENTER]*inv_lapse*ONE_OVER_SQRT_4PI;\n CCTK_REAL BzL_over_alpha_sqrt_fourpi = PRIMS[BZ_CENTER]*inv_lapse*ONE_OVER_SQRT_4PI;\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.b: Initializing $\\rho_{b}$, $P$, and $v^{i}$ \\[Back to [top](#toc)\\]\n$$\\label{variables_needed_by_harm__init_rhob_pressure_vi}$$\n\nHere we simply initialize $\\rho_{b}$, $P$, and $v^{i}$.\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n CCTK_REAL rho_b_oldL = PRIMS[RHOB];\n CCTK_REAL P_oldL = PRIMS[PRESSURE];\n CCTK_REAL vxL = PRIMS[VX];\n CCTK_REAL vyL = PRIMS[VY];\n CCTK_REAL vzL = PRIMS[VZ];\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.c: Storing the original values of the conservative variables \\[Back to [top](#toc)\\]\n$$\\label{variables_needed_by_harm__original_conserv}$$\n\nHere we store the currently known values of $\\left\\{\\rho_{\\star},\\tilde{\\tau},\\tilde{S}_{i}\\right\\}$.\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n /*\n -- Driver for new prim. var. solver. The driver just translates\n between the two sets of definitions for U and P. The user may \n wish to alter the translation as they see fit. \n\n\n // / rho u^t \\ //\n // U = | T^t_t + rho u^t | * sqrt(-det(g_{\\mu\\nu})) //\n // | T^t_i | //\n // \\ B^i / //\n // //\n // / rho \\ //\n // P = | uu | //\n // | \\tilde{u}^i | //\n // \\ B^i / //\n\n (above equations have been fixed by Yuk Tung & Zach)\n */\n \n // U[NPR] = conserved variables (current values on input/output);\n // g4dn[NDIM][NDIM] = covariant form of the 4-metric ;\n // g4up[NDIM][NDIM] = contravariant form of the 4-metric ;\n // gdet = sqrt( - determinant of the 4-metric) ;\n // prim[NPR] = primitive variables (guess on input, calculated values on \n // output if there are no problems);\n\n // U[1] = \n // U[2-4] = stildei + rhostar\n\n CCTK_REAL rho_star_orig = CONSERVS[RHOSTAR];\n CCTK_REAL mhd_st_x_orig = CONSERVS[STILDEX];\n CCTK_REAL mhd_st_y_orig = CONSERVS[STILDEY];\n CCTK_REAL mhd_st_z_orig = CONSERVS[STILDEZ];\n CCTK_REAL tau_orig = CONSERVS[TAUENERGY];\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.d: Guessing $\\rho_{b}$, $P$, and $v^{i}$ \\[Back to [top](#toc)\\]\n$$\\label{variables_needed_by_harm__guessing_rhob_pressure_vi}$$\n\nWe will now start preparing the primitives for the conservative-to-primitive algorithm, which employs the [Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_method).\n\nWe offer the algorithm the initial guess\n\n$$\n\\boxed{\n{\\rm Guess\\ \\#1:}\\ \n\\left\\{\n\\begin{align}\n\\rho_{b}^{\\rm guess} &= \\frac{\\rho_{\\star}}{\\psi^{6}}\\\\\nP_{\\rm guess} &= \\kappa \\left(\\rho_{b}^{\\rm guess}\\right)^{\\Gamma}\\\\\nu0 &= \\frac{1}{\\alpha}\\\\\nv^{i} &= -\\beta^{i}\n\\end{align}\n\\right.\n}\\ .\n$$\n\nIf this initial guess causes the Newton-Raphson method to fail, we try a second guess\n\n$$\n\\boxed{\n{\\rm Guess\\ \\#2:}\\ \n\\left\\{\n\\begin{align}\n\\rho_{b}^{\\rm guess} &= 100\\rho_{b}^{\\rm atm}\\\\\nP_{\\rm guess} &= \\kappa \\left(\\rho_{b}^{\\rm guess}\\right)^{\\Gamma}\\\\\nu0 &= \\frac{1}{\\alpha}\\\\\nv^{i} &= -\\beta^{i}\n\\end{align}\n\\right.\n}\\ .\n$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n // Other ideas for setting the gamma speed limit\n //CCTK_REAL GAMMA_SPEED_LIMIT = 100.0;\n //if(ADM_3METRIC[SQRTGAMMA]>Psi6threshold) GAMMA_SPEED_LIMIT=500.0;\n //if(ADM_3METRIC[SQRTGAMMA]>Psi6threshold) GAMMA_SPEED_LIMIT=100.0;\n\n //FIXME: Only works if poisoning is turned on. Otherwise will access unknown memory. This trick alone speeds up the whole code (Cowling) by 2%.\n //int startguess=0;\n //if(std::isnan(PRIMS[VX])) startguess=1;\n int startguess=1;\n\n CCTK_REAL u0L=1.0;\n CCTK_REAL K_ppoly_tab,Gamma_ppoly_tab;\n\n for(int which_guess=startguess;which_guess<3;which_guess++) {\n int check;\n\n if(which_guess==1) {\n //Use a different initial guess:\n rho_b_oldL = CONSERVS[RHOSTAR]/ADM_3METRIC[SQRTGAMMA];\n\n /*******************************************\n * Piecewise Polytropic EOS Patch *\n * Finding Gamma_ppoly_tab and K_ppoly_tab *\n *******************************************/\n /* Here we use our newly implemented\n * find_polytropic_K_and_Gamma() function\n * to determine the relevant polytropic\n * Gamma and K parameters to be used\n * within this function.\n */\n int polytropic_index = find_polytropic_K_and_Gamma_index(eos,rho_b_oldL);\n K_ppoly_tab = eos.K_ppoly_tab[polytropic_index];\n Gamma_ppoly_tab = eos.Gamma_ppoly_tab[polytropic_index];\n\n // After that, we compute P_cold\n P_oldL = K_ppoly_tab*pow(rho_b_oldL,Gamma_ppoly_tab);\n\n u0L = 1.0/ADM_3METRIC[ALPHA];\n vxL = -ADM_3METRIC[BETAX];\n vyL = -ADM_3METRIC[BETAY];\n vzL = -ADM_3METRIC[BETAZ];\n }\n\n if(which_guess==2) {\n //Use atmosphere as initial guess:\n rho_b_oldL = 100.0*rho_b_atm;\n \n /*******************************************\n * Piecewise Polytropic EOS Patch *\n * Finding Gamma_ppoly_tab and K_ppoly_tab *\n *******************************************/\n /* Here we use our newly implemented\n * find_polytropic_K_and_Gamma() function\n * to determine the relevant polytropic\n * Gamma and K parameters to be used\n * within this function.\n */\n int polytropic_index = find_polytropic_K_and_Gamma_index(eos,rho_b_oldL);\n K_ppoly_tab = eos.K_ppoly_tab[polytropic_index];\n Gamma_ppoly_tab = eos.Gamma_ppoly_tab[polytropic_index];\n\n // After that, we compute P_cold\n P_oldL = K_ppoly_tab*pow(rho_b_oldL,Gamma_ppoly_tab);\n\n u0L = 1.0/ADM_3METRIC[ALPHA];\n vxL = -ADM_3METRIC[BETAX];\n vyL = -ADM_3METRIC[BETAY];\n vzL = -ADM_3METRIC[BETAZ];\n }\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.e: Writing $\\boldsymbol{C}_{\\rm HARM}$ in terms of $\\boldsymbol{C}_{\\rm IGM}$ \\[Back to [top](#toc)\\]\n$$\\label{variables_needed_by_harm__conservs}$$\n\nWe will now relate $\\boldsymbol{C}_{\\rm HARM}$ to $\\boldsymbol{C}_{\\rm IGM}$. As previously mentioned, we have\n\n$$\n\\begin{align}\n\\boldsymbol{C}_{\\rm IGM} &= \\left(\\rho_{\\star},\\tilde{\\tau},\\tilde{S}_{i},\\tilde{B}^{i}\\right)\\ ,\\\\\n\\boldsymbol{C}_{\\rm HARM} &= \\left(\\sqrt{-g}\\rho_{b}u^{0},\\sqrt{-g}\\left(T^{0}_{\\ 0}+\\rho_{b}u^{0}\\right),\\sqrt{-g}T^{0}_{\\ i},\\sqrt{-g}B^{i}_{\\rm HARM}\\right) \\equiv \\left(\\rho_{\\rm HARM},\\tilde{\\tau}_{\\rm HARM},\\tilde{S}_{i}^{\\rm HARM},\\tilde{B}^{i}_{\\rm HARM}\\right)\\ .\n\\end{align}\n$$\n\nThe following relations immediately hold\n\n$$\n\\boxed{\n\\begin{align}\n\\rho_{\\rm HARM} &= \\rho_{\\star}\\\\\n\\tilde{S}_{i}^{\\rm HARM} &= \\tilde{S}_{i}\n\\end{align}\n}\\ .\n$$\n\nAs previously derived in [Step 4.b](#variables_needed_by_harm__bi_harm), we then have\n\n$$\n\\boxed{\\tilde{B}^{i}_{\\rm HARM} = \\underbrace{\\left(\\alpha\\sqrt{\\gamma}\\right)}_{\\rm detg}\\underbrace{\\left(\\frac{B^{i}}{\\alpha\\sqrt{4\\pi}}\\right)}_{\\rm BiL\\_over\\_alpha\\_sqrt\\_fourpi}}\\ .\n$$\n\nFinally, we must relate $\\tilde{\\tau}_{\\rm HARM} = \\sqrt{-g}\\left(T^{0}_{\\ 0}+\\rho_{b}u^{0}\\right)$ to the `IllinoisGRMHD` variables. Let us start by looking at\n\n$$\n\\begin{align}\nS^{i} &= -\\gamma^{i}_{\\ \\mu}n_{\\nu}T^{\\mu\\nu}\\\\\n &= -\\left(\\delta^{i}_{\\mu} + n^{i}n_{\\mu}\\right)n_{\\nu}T^{\\mu\\nu}\\\\\n &= -\\delta^{i}_{\\mu}n_{\\nu}T^{\\mu\\nu} - n^{i}n_{\\mu}n_{\\nu}T^{\\mu\\nu}\\\\\n &= -n_{0}T^{i0} - n^{i}n_{0}n_{0}T^{00}\\\\\n &= \\alpha T^{i0} - \\left(-\\frac{\\beta^{i}}{\\alpha}\\right)\\alpha^{2}T^{00}\\\\\n\\implies S^{i}&= \\alpha\\left[\\beta^{i}T^{00} + T^{i0}\\right]\\ .\n\\end{align}\n$$\n\nNow let us look remember that\n\n$$\n\\tilde{\\tau} = \\alpha^{2}\\sqrt{\\gamma}T^{00} - \\rho_{\\star} \\implies T^{00} = \\frac{\\left(\\tilde\\tau + \\rho_{\\star}\\right)}{\\alpha^{2}\\sqrt{\\gamma}}\\ .\n$$\n\nThen\n\n$$\n\\begin{align}\nT^{0}_{0} &= g_{0\\mu}T^{0\\mu}\\\\\n &= g_{00}T^{00} + g_{0i}T^{0i}\\\\\n &= \\left(-\\alpha^{2}+\\beta_{\\ell}\\beta^{\\ell}\\right)T^{00} + \\beta_{i}T^{0i}\\\\\n &= -\\alpha^{2}T^{00} + \\beta_{i}\\left[\\beta^{i}T^{00} + T^{i0}\\right]\\\\\n &= -\\alpha^{2}\\left[\\frac{\\left(\\tilde\\tau + \\rho_{\\star}\\right)}{\\alpha^{2}\\sqrt{\\gamma}}\\right] + \\frac{\\beta^{i}S_{i}}{\\alpha}\\\\\n\\implies T^{0}_{0} &= -\\frac{\\tilde\\tau+\\rho_{\\star}}{\\sqrt{\\gamma}} + \\frac{\\beta^{i}S_{i}}{\\alpha}\\ .\n\\end{align}\n$$\n\nFinally, we can compute\n\n$$\n\\begin{align}\n\\tilde\\tau_{\\rm HARM} &= \\sqrt{-g}\\left(T^{0}_{0} + \\rho_{b}u^{0}\\right)\\\\\n &= \\alpha\\sqrt{\\gamma}T^{0}_{0} + \\alpha\\sqrt{\\gamma}\\rho_{b}u^{0}\\\\\n &= \\alpha\\sqrt{\\gamma}\\left[-\\frac{\\tilde\\tau+\\rho_{\\star}}{\\sqrt{\\gamma}} + \\frac{\\beta^{i}S_{i}}{\\alpha}\\right] + \\rho_{\\star}\\\\\n &= -\\alpha\\tilde{\\tau} -\\alpha\\rho_{\\star} + \\beta^{i}\\left(\\sqrt{\\gamma}S_{i}\\right) + \\rho_{\\star}\\\\\n\\implies &\\boxed{\\tilde\\tau_{\\rm HARM} = -\\alpha\\tilde{\\tau} - \\left(\\alpha-1\\right)\\rho_{\\star} + \\beta^{i}\\tilde{S}_{i}}\\ .\n\\end{align}\n$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n // Fill the array of conserved variables according to the wishes of Utoprim_2d.\n U[RHO] = CONSERVS[RHOSTAR];\n U[UU] = -CONSERVS[TAUENERGY]*ADM_3METRIC[ALPHA] - (ADM_3METRIC[ALPHA]-1.0)*CONSERVS[RHOSTAR] + \n ADM_3METRIC[BETAX]*CONSERVS[STILDEX] + ADM_3METRIC[BETAY]*CONSERVS[STILDEY] + ADM_3METRIC[BETAZ]*CONSERVS[STILDEZ] ; // note the minus sign on tau\n U[UTCON1] = CONSERVS[STILDEX];\n U[UTCON2] = CONSERVS[STILDEY];\n U[UTCON3] = CONSERVS[STILDEZ];\n U[BCON1] = detg*BxL_over_alpha_sqrt_fourpi;\n U[BCON2] = detg*ByL_over_alpha_sqrt_fourpi;\n U[BCON3] = detg*BzL_over_alpha_sqrt_fourpi;\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.f: Writing $\\boldsymbol{P}_{\\rm HARM}$ in terms of $\\boldsymbol{P}_{\\rm IGM}$ \\[Back to [top](#toc)\\]\n$$\\label{variables_needed_by_harm__prims}$$\n\nKeep in mind that for the primitive variables, we are not intereted in providing exact relations. Instead, what we are interested in doing is providing an educated guess of what it should look like in hopes that the Newton-Raphson method then converges to the correct values. With that in mind, the primitive variables are then initialized to:\n\n$$\n\\boxed{\n\\begin{align}\n\\rho_{\\rm HARM} &= \\rho_{b}\\\\\nu &= \\frac{P}{\\Gamma_{\\rm poly} - 1}\\\\\n\\tilde{u}^{i} &= u^{0}\\left(v^{i}+\\beta^{i}\\right)\\\\\nB^{i}_{\\rm HARM} &= \\frac{B^{i}}{\\alpha\\sqrt{4\\pi}}\n\\end{align}\\ ,\n}\n$$\n\nwhere $\\Gamma_{\\rm poly}$ stands for the *local* polytropic $\\Gamma$-factor.\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n CCTK_REAL uL = P_oldL/(Gamma_ppoly_tab - 1.0);\n CCTK_REAL utxL = u0L*(vxL + ADM_3METRIC[BETAX]);\n CCTK_REAL utyL = u0L*(vyL + ADM_3METRIC[BETAY]);\n CCTK_REAL utzL = u0L*(vzL + ADM_3METRIC[BETAZ]);\n\n prim[RHO] = rho_b_oldL;\n prim[UU] = uL;\n prim[UTCON1] = utxL;\n prim[UTCON2] = utyL;\n prim[UTCON3] = utzL;\n prim[BCON1] = BxL_over_alpha_sqrt_fourpi;\n prim[BCON2] = ByL_over_alpha_sqrt_fourpi;\n prim[BCON3] = BzL_over_alpha_sqrt_fourpi;\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.g: Calling the `HARM` conservative-to-primitive solver \\[Back to [top](#toc)\\]\n$$\\label{calling_harm_conservs_to_prims_solver}$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n /*************************************************************/\n // CALL HARM PRIMITIVES SOLVER:\n check = Utoprim_2d(eos, U, g4dn, g4up, detg, prim,stats.n_iter);\n // Note that we have modified this solver, so that nearly 100% \n // of the time it yields either a good root, or a root with \n // negative epsilon (i.e., pressure).\n /*************************************************************/\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.h: Applying the Font *et al.* fix, if the inversion fails \\[Back to [top](#toc)\\]\n$$\\label{font_fix}$$\n\nIf the conservative-to-primitive solver fails to converge, we apply the procedure suggested by [Font *et al.* (1998)](https://arxiv.org/abs/gr-qc/9811015). The algorithm can be summarized as the requirement that\n\n$$\nP=P_{\\rm cold} = \\kappa \\rho^{\\Gamma_{\\rm cold}}_{b}\\ ,\n$$\n\nand then recomputing the velocities $u_{i}$. We will describe this procedure in detail in [Step 4](#font_fix_gamma_law__c) below.\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n // Use the new Font fix subroutine \n int font_fix_applied=0;\n if(check!=0) {\n font_fix_applied=1;\n CCTK_REAL u_xl=1e100, u_yl=1e100, u_zl=1e100; // Set to insane values to ensure they are overwritten.\n /************************\n * New Font fix routine *\n ************************/\n check = font_fix__hybrid_EOS(u_xl,u_yl,u_zl, CONSERVS,PRIMS,ADM_3METRIC, eos);\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.i: Compute $\\tilde{u}^{i}$ \\[Back to [top](#toc)\\]\n$$\\label{compute_utconi}$$\n\nNow we evaluate\n\n$$\n\\tilde{u}^{i} = \\gamma^{ij}u_{i} \\implies\n\\boxed{\n\\left\\{\n\\begin{align}\n\\tilde{u}^{x} &= \\gamma^{xx}u_{x} + \\gamma^{xy}u_{y} + \\gamma^{xz}u_{z}\\\\\n\\tilde{u}^{y} &= \\gamma^{yx}u_{x} + \\gamma^{yy}u_{y} + \\gamma^{yz}u_{z}\\\\\n\\tilde{u}^{z} &= \\gamma^{zx}u_{x} + \\gamma^{zy}u_{y} + \\gamma^{zz}u_{z}\n\\end{align}\n\\right.\n}\n$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n //Translate to HARM primitive now:\n prim[UTCON1] = ADM_3METRIC[GAMMAUPXX]*u_xl + ADM_3METRIC[GAMMAUPXY]*u_yl + ADM_3METRIC[GAMMAUPXZ]*u_zl;\n prim[UTCON2] = ADM_3METRIC[GAMMAUPXY]*u_xl + ADM_3METRIC[GAMMAUPYY]*u_yl + ADM_3METRIC[GAMMAUPYZ]*u_zl;\n prim[UTCON3] = ADM_3METRIC[GAMMAUPXZ]*u_xl + ADM_3METRIC[GAMMAUPYZ]*u_yl + ADM_3METRIC[GAMMAUPZZ]*u_zl;\n if (check==1) {\n CCTK_VInfo(CCTK_THORNSTRING,\"Font fix failed!\");\n CCTK_VInfo(CCTK_THORNSTRING,\"stats.failure_checker = %d , st_i = %e %e %e, rhostar = %e, Bi = %e %e %e, gij = %e %e %e %e %e %e, Psi6 = %e\",stats.failure_checker,mhd_st_x_orig,mhd_st_y_orig,mhd_st_z_orig,rho_star_orig,PRIMS[BX_CENTER],PRIMS[BY_CENTER],PRIMS[BZ_CENTER],ADM_3METRIC[GAMMAXX],ADM_3METRIC[GAMMAXY],ADM_3METRIC[GAMMAXZ],ADM_3METRIC[GAMMAYY],ADM_3METRIC[GAMMAYZ],ADM_3METRIC[GAMMAZZ],ADM_3METRIC[SQRTGAMMA]);\n }\n }\n stats.failure_checker+=font_fix_applied*10000;\n stats.font_fixed=font_fix_applied;\n /*************************************************************/\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.j: Limiting velocities \\[Back to [top](#toc)\\]\n$$\\label{limiting_velocities}$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n if(check==0) {\n //Now that we have found some solution, we first limit velocity:\n //FIXME: Probably want to use exactly the same velocity limiter function here as in mhdflux.C\n CCTK_REAL utx_new = prim[UTCON1];\n CCTK_REAL uty_new = prim[UTCON2];\n CCTK_REAL utz_new = prim[UTCON3];\n\n //Velocity limiter:\n CCTK_REAL gijuiuj = ADM_3METRIC[GAMMAXX]*SQR(utx_new ) +\n 2.0*ADM_3METRIC[GAMMAXY]*utx_new*uty_new + 2.0*ADM_3METRIC[GAMMAXZ]*utx_new*utz_new +\n ADM_3METRIC[GAMMAYY]*SQR(uty_new) + 2.0*ADM_3METRIC[GAMMAYZ]*uty_new*utz_new +\n ADM_3METRIC[GAMMAZZ]*SQR(utz_new);\n CCTK_REAL au0m1 = gijuiuj/( 1.0+sqrt(1.0+gijuiuj) );\n u0L = (au0m1+1.0)/ADM_3METRIC[ALPHA];\n\n // *** Limit velocity\n stats.vel_limited=0;\n if (au0m1 > 0.9999999*(GAMMA_SPEED_LIMIT-1.0)) {\n CCTK_REAL fac = sqrt((SQR(GAMMA_SPEED_LIMIT)-1.0)/(SQR(1.0+au0m1) - 1.0));\n utx_new *= fac;\n uty_new *= fac;\n utz_new *= fac;\n gijuiuj = gijuiuj * SQR(fac);\n au0m1 = gijuiuj/( 1.0+sqrt(1.0+gijuiuj) );\n // Reset rho_b and u0\n u0L = (au0m1+1.0)/ADM_3METRIC[ALPHA];\n prim[RHO] = rho_star_orig/(ADM_3METRIC[ALPHA]*u0L*ADM_3METRIC[SQRTGAMMA]);\n stats.vel_limited=1;\n stats.failure_checker+=1000;\n } //Finished limiting velocity\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n## Step 4.k: Setting the primitives \\[Back to [top](#toc)\\]\n$$\\label{primitives}$$\n\nFinally, we update the primitives,\n\n$$\n\\boxed{\n\\begin{align}\n\\rho_{b} &= \\rho\\\\\nP &= \\left(\\Gamma - 1\\right)u = P_{\\rm cold}\\\\\nv^{i} &= \\frac{\\tilde{u}^{i}}{u^{0}} - \\beta^{i}\n\\end{align}\n}\n$$\n\n\n```python\n%%writefile -a $outdir/harm_primitives_lowlevel.C\n\n\n //The Font fix only sets the velocities. Here we set the pressure & density HARM primitives.\n if(font_fix_applied==1) {\n prim[RHO] = rho_star_orig/(ADM_3METRIC[ALPHA]*u0L*ADM_3METRIC[SQRTGAMMA]);\n //Next set P = P_cold:\n CCTK_REAL P_cold;\n \n /**********************************\n * Piecewise Polytropic EOS Patch *\n * Finding Gamma_ppoly_tab and K_ppoly_tab *\n **********************************/\n /* Here we use our newly implemented\n * find_polytropic_K_and_Gamma() function\n * to determine the relevant polytropic\n * Gamma and K parameters to be used\n * within this function.\n */\n int polytropic_index = find_polytropic_K_and_Gamma_index(eos,prim[RHO]);\n K_ppoly_tab = eos.K_ppoly_tab[polytropic_index];\n Gamma_ppoly_tab = eos.Gamma_ppoly_tab[polytropic_index];\n\n // After that, we compute P_cold\n P_cold = K_ppoly_tab*pow(prim[RHO],Gamma_ppoly_tab);\n \n prim[UU] = P_cold/(Gamma_ppoly_tab-1.0);\n } //Finished setting remaining primitives if there was a Font fix.\n\n /* Set rho_b */\n PRIMS[RHOB] = prim[RHO];\n\n /***************\n * PPEOS Patch *\n * Hybrid EOS *\n ***************\n */\n /* We now compute the pressure as a function\n * of rhob, P_cold, eps_cold, and u = rhob*eps,\n * using the function pressure_rho0_u(), which\n * implements the equation:\n * .-------------------------------------------------------------.\n * | p(rho_b,u) = P_cold + (Gamma_th - 1)*(u - rho_b * eps_cold) |\n * .-------------------------------------------------------------.\n */\n PRIMS[PRESSURE] = pressure_rho0_u(eos, prim[RHO],prim[UU]);\n\n /* Already set u0L. */\n PRIMS[VX] = utx_new/u0L - ADM_3METRIC[BETAX];\n PRIMS[VY] = uty_new/u0L - ADM_3METRIC[BETAY];\n PRIMS[VZ] = utz_new/u0L - ADM_3METRIC[BETAZ];\n\n return 0;\n } else {\n //If we didn't find a root, then try again with a different guess.\n }\n }\n CCTK_VInfo(CCTK_THORNSTRING,\"Couldn't find root from: %e %e %e %e %e, rhob approx=%e, rho_b_atm=%e, Bx=%e, By=%e, Bz=%e, gij_phys=%e %e %e %e %e %e, alpha=%e\",\n\t tau_orig,rho_star_orig,mhd_st_x_orig,mhd_st_y_orig,mhd_st_z_orig,rho_star_orig/ADM_3METRIC[SQRTGAMMA],rho_b_atm,PRIMS[BX_CENTER],PRIMS[BY_CENTER],PRIMS[BZ_CENTER],ADM_3METRIC[GAMMAXX],ADM_3METRIC[GAMMAXY],ADM_3METRIC[GAMMAXZ],ADM_3METRIC[GAMMAYY],ADM_3METRIC[GAMMAYZ],ADM_3METRIC[GAMMAZZ],ADM_3METRIC[ALPHA]);\n return 1;\n}\n\n//#include \"harm_u2p_util.c\"\n#include \"harm_utoprim_2d.c\"\n#include \"eigen.C\"\n#include \"font_fix_gamma_law.C\"\n\n\n```\n\n Appending to ../src/harm_primitives_lowlevel.C\n\n\n\n\n# Step 5: `font_fix_gamma_law.C` \\[Back to [top](#toc)\\]\n$$\\label{font_fix_gamma_law__c}$$\n\nThe [Font *et al.*](https://arxiv.org/pdf/gr-qc/9811015.pdf) algorithm (henceforth Font Fix algorithm) can be summarized by the following assumpition ssume:\n\n$$\nP = P_{\\rm cold}\\ ,\n$$\n\nwhere $P_{\\rm cold}$ is computed assuming a simple or piecewise polytropic equation of state. It is also assumed that\n\n$$\n\\epsilon = \\epsilon_{\\rm cold}\\ ,\n$$\n\nhence\n\n$$\nh = 1 + \\epsilon + \\frac{P}{\\rho_{b}}\n$$\n\nWe then run an iterative process that updates $\\rho$ based on the value of $h$, until convergence is obtained.\n\n\n\n## Step 5.a: Computing the basic quantities needed by the algorithm \\[Back to [top](#toc)\\]\n$$\\label{font_fix_gamma_law__basic_quantities}$$\n\nWe start by computing all basic quantities needed by the Font Fix algorithm:\n\n$$\n\\boxed{\n\\begin{align}\n\\bar{B}^{i} &= \\frac{B^i}{\\sqrt{4\\pi}}\\\\\n\\bar{B}_{i} &= \\gamma_{ij}\\bar{B}^{j}\\\\\n\\bar{B}^{2} &= \\bar{B}_{i}\\bar{B}^{i}\\\\\n\\bar{B} &= \\sqrt{\\bar{B}^{2}}\\\\\n\\bar{B}\\cdot\\tilde{S} &= \\bar{B}^{i}\\tilde{S}_{i}\\\\\n (\\bar{B}&\\cdot\\tilde{S})^{2}\\\\\n\\hat{\\bar{B}}\\cdot\\tilde{S} &= \\hat{\\bar{B}}^{i}\\tilde{S}_{i} \\equiv \\left(\\frac{\\bar{B}^{i}}{\\bar{B}}\\right)\\tilde{S}_{i}\\\\\n\\tilde{S}\\cdot\\tilde{S} &= \\gamma^{ij}\\tilde{S}_{i}\\tilde{S}_{j}\n\\end{align}\n}\\ .\n$$\n\nThe algorithm then checks whether or not $\\tilde{S}\\cdot\\tilde{S} = 0$, returning\n\n$$\n\\begin{align}\n\\rho_{b} &= \\psi^{-6}\\rho_{\\star}\\ ,\\\\\nu^{i} &= 0\\ ,\n\\end{align}\n$$\n\nif that is the case and terminating the function call.\n\n\n```python\n%%writefile $outdir/font_fix_gamma_law.C\n\n// Function prototype\nstatic inline int font_fix__rhob_loop( int maxits, CCTK_REAL tol,\n CCTK_REAL W, CCTK_REAL Sf2, CCTK_REAL Psim6, CCTK_REAL sdots, CCTK_REAL BbardotS2, CCTK_REAL B2bar, \n CCTK_REAL *CONSERVS,\n eos_struct eos, CCTK_REAL rhob_in, CCTK_REAL &rhob_out );\n\n/**********************************\n * Piecewise Polytropic EOS Patch *\n * Font fix: function call *\n **********************************/\ninline int font_fix__hybrid_EOS(CCTK_REAL &u_x, CCTK_REAL &u_y, CCTK_REAL &u_z,CCTK_REAL *CONSERVS,CCTK_REAL *PRIMS,CCTK_REAL *ADM_3METRIC, eos_struct eos) {\n\n CCTK_REAL Bxbar = PRIMS[BX_CENTER]*ONE_OVER_SQRT_4PI;\n CCTK_REAL Bybar = PRIMS[BY_CENTER]*ONE_OVER_SQRT_4PI;\n CCTK_REAL Bzbar = PRIMS[BZ_CENTER]*ONE_OVER_SQRT_4PI;\n CCTK_REAL Bbar_x = ADM_3METRIC[GAMMAXX]*Bxbar + ADM_3METRIC[GAMMAXY]*Bybar + ADM_3METRIC[GAMMAXZ]*Bzbar;\n CCTK_REAL Bbar_y = ADM_3METRIC[GAMMAXY]*Bxbar + ADM_3METRIC[GAMMAYY]*Bybar + ADM_3METRIC[GAMMAYZ]*Bzbar;\n CCTK_REAL Bbar_z = ADM_3METRIC[GAMMAXZ]*Bxbar + ADM_3METRIC[GAMMAYZ]*Bybar + ADM_3METRIC[GAMMAZZ]*Bzbar;\n CCTK_REAL B2bar = Bxbar*Bbar_x + Bybar*Bbar_y + Bzbar*Bbar_z;\n CCTK_REAL Bbar = sqrt(B2bar);\n\n CCTK_REAL check_B_small = fabs(Bxbar)+fabs(Bybar)+fabs(Bzbar);\n if (check_B_small>0 && check_B_small<1.e-150) {\n // need to compute B2bar specially to prevent floating-point underflow\n CCTK_REAL Bmax = fabs(Bxbar);\n if (Bmax < fabs(Bybar)) Bmax=fabs(Bybar);\n if (Bmax < fabs(Bzbar)) Bmax=fabs(Bzbar);\n CCTK_REAL Bxtmp=Bxbar/Bmax, Bytemp=Bybar/Bmax, Bztemp=Bzbar/Bmax;\n CCTK_REAL B_xtemp=Bbar_x/Bmax, B_ytemp=Bbar_y/Bmax, B_ztemp=Bbar_z/Bmax;\n Bbar = sqrt(Bxtmp*B_xtemp + Bytemp*B_ytemp + Bztemp*B_ztemp)*Bmax;\n }\n CCTK_REAL BbardotS = Bxbar*CONSERVS[STILDEX] + Bybar*CONSERVS[STILDEY] + Bzbar*CONSERVS[STILDEZ];\n CCTK_REAL BbardotS2 = BbardotS*BbardotS;\n CCTK_REAL hatBbardotS = BbardotS/Bbar;\n if (Bbar<1.e-300) hatBbardotS = 0.0;\n CCTK_REAL Psi6 = ADM_3METRIC[SQRTGAMMA];\n CCTK_REAL Psim6 = 1.0/Psi6;\n\n // Limit hatBbardotS\n //CCTK_REAL max_gammav = 100.0;\n //CCTK_REAL rhob_max = CONSERVS[RHOSTAR]*Psim6;\n //CCTK_REAL hmax = 1.0 + gam_gamm1_kpoly*pow(rhob_max,gam1);\n //CCTK_REAL abs_hatBbardotS_max = sqrt(SQR(max_gammav)-1.0)*CONSERVS[RHOSTAR]*hmax;\n //if (fabs(hatBbardotS) > abs_hatBbardotS_max) {\n // CCTK_REAL fac_reduce = abs_hatBbardotS_max/fabs(hatBbardotS);\n // CCTK_REAL hatBbardotS_max = hatBbardotS*fac_reduce;\n // CCTK_REAL Bbar_inv = 1.0/Bbar;\n // CCTK_REAL hat_Bbar_x = Bbar_x*Bbar_inv;\n // CCTK_REAL hat_Bbar_y = Bbar_y*Bbar_inv;\n // CCTK_REAL hat_Bbar_z = Bbar_z*Bbar_inv;\n // CCTK_REAL sub_fact = hatBbardotS_max - hatBbardotS;\n // CONSERVS[STILDEX] += sub_fact*hat_Bbar_x;\n // CONSERVS[STILDEY] += sub_fact*hat_Bbar_y;\n // CONSERVS[STILDEZ] += sub_fact*hat_Bbar_z;\n // hatBbardotS = hatBbardotS_max;\n // BbardotS *= fac_reduce;\n // BbardotS2 = BbardotS*BbardotS;\n //}\n\n CCTK_REAL sdots = ADM_3METRIC[GAMMAUPXX]*SQR(CONSERVS[STILDEX]) + ADM_3METRIC[GAMMAUPYY]*SQR(CONSERVS[STILDEY]) + ADM_3METRIC[GAMMAUPZZ]*SQR(CONSERVS[STILDEZ])\n + 2.0*( ADM_3METRIC[GAMMAUPXY]*CONSERVS[STILDEX]*CONSERVS[STILDEY] + ADM_3METRIC[GAMMAUPXZ]*CONSERVS[STILDEX]*CONSERVS[STILDEZ]\n + ADM_3METRIC[GAMMAUPYZ]*CONSERVS[STILDEY]*CONSERVS[STILDEZ]);\n\n CCTK_REAL rhob;\n if (sdots<1.e-300) {\n rhob = CONSERVS[RHOSTAR]*Psim6;\n u_x=0.0; u_y=0.0; u_z=0.0;\n return 0;\n }\n /* This test has some problem.\n if (fabs(BbardotS2 - sdots*B2bar) > 1e-8) {\n CCTK_VInfo(CCTK_THORNSTRING,\"(Bbar dot S)^2, Bbar^2 * sdotS, %e %e\",SQR(BbardotS),sdots*B2bar);\n CCTK_VInfo(CCTK_THORNSTRING,\"Cauchy-Schwartz inequality is violated!\");\n }\n */\n```\n\n Overwriting ../src/font_fix_gamma_law.C\n\n\n\n\n## Step 5.b: Initial guesses for $W$, $S_{{\\rm fluid}}^{2}$, and $\\rho$ \\[Back to [top](#toc)\\]\n$$\\label{font_fix_gamma_law__initial_guesses}$$\n\nWe set the initial data based on eqs. (A52), (A53), and (A59) found in [Appendix A of Zachariah *et al.* (2012)](https://arxiv.org/pdf/1112.0568.pdf):\n\n$$\n\\boxed{\n\\begin{align}\nW_{0} &= \\psi^{-6}\\sqrt{\\left(\\hat{\\bar{B}}\\cdot\\tilde{S}\\right)^{2} + \\rho_{\\star}^{2}}\\\\\nS_{{\\rm fluid},0}^{2} &=\\frac{W_{0}^{2}\\left(\\tilde{S}\\cdot\\tilde{S}\\right)+\\left(\\bar{B}\\cdot\\tilde{S}\\right)^{2}\\left(\\bar{B}^{2} + 2W_{0}\\right)}{\\left(W_{0} + \\bar{B}^{2}\\right)^{2}}\\\\\n\\rho_{0} &= \\frac{\\psi^{-6}\\rho_{\\star}}{\\sqrt{1+\\frac{S_{{\\rm fluid},0}^{2}}{\\rho_{\\star}^{2}}}}\n\\end{align}\n}\\ .\n$$\n\n\n```python\n%%writefile -a $outdir/font_fix_gamma_law.C\n\n\n // Initial guess for W, S_fluid and rhob\n CCTK_REAL W0 = sqrt( SQR(hatBbardotS) + SQR(CONSERVS[RHOSTAR]) ) * Psim6;\n CCTK_REAL Sf20 = (SQR(W0)*sdots + BbardotS2*(B2bar + 2.0*W0))/SQR(W0+B2bar);\n CCTK_REAL rhob0 = CONSERVS[RHOSTAR]*Psim6/sqrt(1.0+Sf20/SQR(CONSERVS[RHOSTAR]));\n\n //****************************************************************\n // FONT FIX\n // Impose Font fix when HARM primitives solver fails to find\n // acceptable set of primitives.\n //****************************************************************\n\n /* Set the maximum number of iterations */\n int maxits = 500;\n \n /* Set the allowed tolerance */\n CCTK_REAL tol = 1.e-15;\n \n /* Declare basic variables */\n int font_fix_status;\n```\n\n Appending to ../src/font_fix_gamma_law.C\n\n\n\n\n## Step 5.c: Font fix main loop \\[Back to [top](#toc)\\]\n$$\\label{font_fix_main_loop}$$\n\nWe now perform the Font fix algorithm by calling the `font_fix__rhob_loop()` function. To see the details of what this function do, please refer to [step 5.e](#font_fix__rhob_loop) below.\n\n\n```python\n%%writefile -a $outdir/font_fix_gamma_law.C\n\n \n /**********************\n * FONT FIX MAIN LOOP *\n **********************\n * Perform the font fix routine until convergence\n * is obtained and the algorithm returns with no\n * error. Every time the Font fix fails, increase\n * the tolerance by a factor of 10.\n */\n int font_fix_attempts = 5;\n CCTK_REAL font_fix_tol_factor = 10.0;\n for(int n=0; n\n\n## Step 5.d: Output $\\rho_{b}$ and $u_{i}$ \\[Back to [top](#toc)\\]\n$$\\label{font_fix_gamma_law__outputs}$$\n\nFinally, we return $\\rho_{b}$ and $u_{i}$. In the relations below, $N$ indicates the last computed value of $\\rho$ obtained by our iterative process. The quantities evaluated here are\n\n$$\n\\boxed{\n\\begin{align}\n\\rho_{b} &= \\rho_{N}\\\\\n\\gamma_{v} &= \\frac{\\psi^{-6}\\rho_{\\star}}{\\rho_{b}}\\\\\nh &= 1 + \\epsilon_{\\rm cold} + \\frac{P_{\\rm cold}}{\\rho_{b}}\\\\\nf_{1} &= \\frac{\\psi^{6}\\left(\\bar{B}\\cdot\\tilde{S}\\right)}{\\gamma_{v}\\rho_{\\star} h}\\\\\nf_{2} &= \\left(\\rho_{\\star}h + \\psi^{6}\\frac{\\bar{B}^{2}}{\\gamma_{v}}\\right)^{-1}\\\\\nu_{i} &= f_{2}\\left(\\tilde{S}_{i} + f_{1}\\bar{B}_{i}\\right)\n\\end{align}\n}\\ .\n$$\n\n\n\n```python\n%%writefile -a $outdir/font_fix_gamma_law.C\n\n \n /* Font fix works! */\n /* First compute P_cold, eps_cold, then h = h_cold */\n CCTK_REAL P_cold, eps_cold;\n compute_P_cold__eps_cold(eos,rhob, P_cold,eps_cold);\n CCTK_REAL h = 1.0 + eps_cold + P_cold/rhob;\n\n /* Then compute gamma_v using equation (A19) in\n * Etienne et al. (2011) [https://arxiv.org/pdf/1112.0568.pdf]\n * .-----------------------------------------.\n * | gamma_v = psi^{-6} * (rho_star / rho_b) |\n * .-----------------------------------------.\n */\n CCTK_REAL gammav = CONSERVS[RHOSTAR]*Psim6/rhob;\n \n /* Finally, compute u_{i} */\n CCTK_REAL rhosh = CONSERVS[RHOSTAR]*h;\n CCTK_REAL fac1 = Psi6*BbardotS/(gammav*rhosh);\n CCTK_REAL fac2 = 1.0/(rhosh + Psi6*B2bar/gammav);\n u_x = fac2*(CONSERVS[STILDEX] + fac1*Bbar_x);\n u_y = fac2*(CONSERVS[STILDEY] + fac1*Bbar_y);\n u_z = fac2*(CONSERVS[STILDEZ] + fac1*Bbar_z);\n\n return 0;\n}\n```\n\n Appending to ../src/font_fix_gamma_law.C\n\n\n\n\n## Step 5.e: The `font_fix__rhob_loop()` function \\[Back to [top](#toc)\\]\n$$\\label{font_fix__rhob_loop}$$\n\nWe now perform the following iterative process, which is again described in [Appendix A of Zachariah *et al.* (2012)](https://arxiv.org/pdf/1112.0568.pdf). We refer the reader to eqs. (A60), (A61), and (A62).\n\n1. Store the previously computed values of $W_{n}$, $S_{{\\rm fluid},n}^{2}$, and $\\rho_{n}$\n2. Compute $h = 1 + \\epsilon + P/\\rho_{n}$\n3. Set\n$$\n\\boxed{\\rho_{n+1} = \\psi^{-6}\\rho_{\\star}\\left(1 + \\frac{S_{{\\rm fluid},n}^{2}}{\\rho_{\\star} h_{n}}\\right)^{-1/2}}\n$$\n\n4. For a given value of $n$, perform steps 1 (for $\\rho$), 2 and 3 until $\\left|\\rho_{n+1}-\\rho_{n}\\right| < \\rho_{n+1}\\epsilon$, where $\\epsilon$ is a user given tolerance\n5. After convergence is obtained, update:\n$$\n\\boxed{\n\\begin{align}\nh_{n+1} &= 1 + 2k_{\\rm poly}\\rho_{n+1}\\\\\nW_{n+1} &= \\psi^{-6}\\sqrt{\\tilde{S}^{2}_{{\\rm fluid},n} + \\rho_{\\star}^{2} h_{n+1}^{2}}\\\\\nS_{{\\rm fluid},n+1}^{2} &= \\frac{W^{2}_{n+1}\\left(\\tilde{S}\\cdot\\tilde{S}\\right) + \\left(\\bar{B}\\cdot\\tilde{S}\\right)^{2}\\left(\\bar{B}^{2} + 2W_{n+1}\\right)}{\\left(W_{n+1} + \\bar{B}^{2}\\right)^{2}}\n\\end{align}\n}\\ .\n$$\n6. Repeat steps 1 through 5 until $\\left|W_{n+1}-W_{n}\\right| < W_{n+1}\\epsilon$ *and* $\\left|S^{2}_{{\\rm fluid},n+1}-S^{2}_{{\\rm fluid},n}\\right| < S^{2}_{{\\rm fluid},n+1}\\epsilon$ *or* we reach the maximum number of iterations\n\n\n```python\n%%writefile -a $outdir/font_fix_gamma_law.C\n\n/* Function : font_fix__rhob_loop()\n * Authors : Leo Werneck\n * Description : Determines rhob using the font fix prescription\n * Dependencies: find_polytropic_K_and_Gamma_index()\n * : compute_P_cold__eps_cold()\n * Reference : Etienne et al. (2011) [https://arxiv.org/pdf/1112.0568.pdf]\n *\n * Inputs : maxits - maximum number of iterations allowed\n * : tol - font fix tolerance\n * : W - See eq. (A26)\n * : Sf2 - S_{fluid}^{2}, see eq. (A24)\n * : Psim6 - This is equal to sqrt(\\gamma)\n * : sdots - \\tilde{S}_{\\mu}\\tilde{S}^{\\mu}\n * : BbardotS2 - (\\bar{B}^{\\mu}S_{\\mu})^{2}, \n * : B2bar - \\bar{B}^{2}, see eq. (A28)\n * : CONSERVS - Array of conservative variables\n * : eos - Struct of EOS parameters\n * : rhob_in - Initial value of rhob\n * : rhob_out - Output variable\n *\n * Outputs : rhob_out - Updated value of rhob\n * : return value: 0 - Font fix worked\n * : return value: 1 - Font fix failed\n */\ninline int font_fix__rhob_loop( int maxits, CCTK_REAL tol,\n CCTK_REAL W, CCTK_REAL Sf2, CCTK_REAL Psim6, CCTK_REAL sdots, CCTK_REAL BbardotS2, CCTK_REAL B2bar, \n CCTK_REAL *CONSERVS,\n eos_struct eos, CCTK_REAL rhob_in, CCTK_REAL &rhob_out ) {\n\n /* Declare basic variables */\n bool fontcheck=true;\n int itcount = 0, j0, j1;\n CCTK_REAL W0, Sf20, rhob0, rhob1, h, P_cold, eps_cold;\n\n //////////////////////\n // OUTER LOOP START //\n //////////////////////\n while(fontcheck && itcount < maxits) {\n\n /* Set variables to their input values */\n itcount++;\n W0 = W;\n Sf20 = Sf2;\n rhob1 = rhob_in;\n\n /* Based on rhob_in (i.e. rhob1), determine the\n * polytropic index j1\n */\n j1 = find_polytropic_K_and_Gamma_index(eos,rhob1);\n\n //////////////////////\n // INNER LOOP START //\n //////////////////////\n do {\n\n /* Set rhob0/j0 to be equal to the rhob/j used\n * in the previous iteration, i.e. rhob1/j1.\n */\n rhob0 = rhob1;\n j0 = j1;\n\n /* Compute h using h_cold and our polytropic EOS\n * .------------------------------------------.\n * | h = h_cold = 1 + eps_cold + P_cold/rhob. |\n * .------------------------------------------.\n */\n compute_P_cold__eps_cold(eos,rhob0, P_cold, eps_cold);\n h = 1.0 + eps_cold + P_cold/rhob0;\n\n /* Update rhob using eq. (A62) in Etienne et al. (2011)\n * https://arxiv.org/pdf/1112.0568.pdf\n * .---------------------------------------------------------------------------.\n * | rhob = rho_star * Psi^{-6} / sqrt( 1 + S_fluid^{2}/( (rho_star*h)^{2} ) ) |\n * .---------------------------------------------------------------------------.\n */\n rhob1 = CONSERVS[RHOSTAR]*Psim6/sqrt(1.0+Sf20/SQR(CONSERVS[RHOSTAR]*h)); \n\n /* Update j1 */\n j1 = find_polytropic_K_and_Gamma_index(eos,rhob1);\n\n } while( fabs(rhob1-rhob0) > rhob1*tol || j1 != j0);\n //////////////////////\n // INNER LOOP END //\n //////////////////////\n\n /* Output the last value of rhob */\n rhob_out = rhob1;\n\n /* Perform physical checks on the variables\n * and output the last value of h obtained\n */\n compute_P_cold__eps_cold(eos,rhob_out, P_cold, eps_cold);\n h = 1.0 + eps_cold + P_cold/rhob_out;\n\n /* Set W based on eq. (A60) in Etienne et al. (2011)\n * https://arxiv.org/pdf/1112.0568.pdf\n * .-------------------------------------------------------.\n * | W = psi^{-6} * sqrt( S_fluid^{2} + (rho_star*h)^{2} ) |\n * .-------------------------------------------------------.\n */ \n W = sqrt( Sf20 + SQR(CONSERVS[RHOSTAR]*h))*Psim6;\n\n /* Then update S_{fluid}^{2} using eq. (A61) in Etienne et al. (2011)\n * https://arxiv.org/pdf/1112.0568.pdf\n * .---------------------------------------------------------------------------.\n * | S_fluid^{2} = ( W^{2}*S^{2} + (B.S)^2*(B^{2} + 2W) )/( ( W + B^{2} )^{2} )|\n * .---------------------------------------------------------------------------.\n */\n Sf2 = (SQR(W)*sdots + BbardotS2*(B2bar + 2.0*W))/SQR(W+B2bar);\n\n if ( fabs(W-W0) < W*tol && fabs(Sf20-Sf2) < Sf2*tol) fontcheck=false;\n }\n //////////////////////\n // OUTER LOOP END //\n //////////////////////\n\n /* If the code converged before the max \n * number of iterations were exceeded,\n * return 0, otherwise return 1.\n */\n if(fontcheck || itcount >= maxits) {\n return 1;\n }\n else {\n return 0;\n }\n}\n```\n\n Appending to ../src/font_fix_gamma_law.C\n\n\n\n\n# Step 6: `harm_primitives_headers.h` \\[Back to [top](#toc)\\]\n$$\\label{harm_primitives_headers}$$\n\nHere we set all the function prototypes and constants we need to use the `HARM` files.\n\n\n```python\n%%writefile $outdir/harm_primitives_headers.h\n/***********************************************************************************\n Copyright 2006 Charles F. Gammie, Jonathan C. McKinney, Scott C. Noble, \n Gabor Toth, and Luca Del Zanna\n\n HARM version 1.0 (released May 1, 2006)\n\n This file is part of HARM. HARM is a program that solves hyperbolic \n partial differential equations in conservative form using high-resolution\n shock-capturing techniques. This version of HARM has been configured to \n solve the relativistic magnetohydrodynamic equations of motion on a \n stationary black hole spacetime in Kerr-Schild coordinates to evolve\n an accretion disk model. \n\n You are morally obligated to cite the following two papers in his/her \n scientific literature that results from use of any part of HARM:\n\n [1] Gammie, C. F., McKinney, J. C., \\& Toth, G.\\ 2003, \n Astrophysical Journal, 589, 444.\n\n [2] Noble, S. C., Gammie, C. F., McKinney, J. C., \\& Del Zanna, L. \\ 2006, \n Astrophysical Journal, 641, 626.\n\n \n Further, we strongly encourage you to obtain the latest version of \n HARM directly from our distribution website:\n http://rainman.astro.uiuc.edu/codelib/\n\n\n HARM is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n HARM is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with HARM; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\n***********************************************************************************/\n#ifndef HARM_PRIMITIVES_HEADERS_H_\n#define HARM_PRIMITIVES_HEADERS_H_\n\nstatic const int NPR =8;\nstatic const int NDIM=4;\n\n/* Adiabatic index used for the state equation */\n//#define GAMMA (2.0)\n\nstatic const CCTK_REAL G_ISOTHERMAL = 1.0;\n\n/* use K(s)=K(r)=const. (G_ATM = GAMMA) of time or T = T(r) = const. of time (G_ATM = 1.) */\n/*\n #define USE_ISENTROPIC 1\n\n #if( USE_ISENTROPIC ) \n #define G_ATM GAMMA\n #else\n #define G_ATM G_ISOTHERMAL\n #endif\n*/\n\nstatic const int MAX_NEWT_ITER=30; /* Max. # of Newton-Raphson iterations for find_root_2D(); */\n//#define MAX_NEWT_ITER 300 /* Max. # of Newton-Raphson iterations for find_root_2D(); */\nstatic const CCTK_REAL NEWT_TOL =1.0e-10; /* Min. of tolerance allowed for Newton-Raphson iterations */\nstatic const CCTK_REAL MIN_NEWT_TOL=1.0e-10; /* Max. of tolerance allowed for Newton-Raphson iterations */\nstatic const int EXTRA_NEWT_ITER=0; /* ZACH SAYS: Original value = 2. But I don't think this parameter > 0 is warranted. Just slows the code for no reason, since our tolerances are fine. */\n\nstatic const CCTK_REAL NEWT_TOL2 =1.0e-15; /* TOL of new 1D^*_{v^2} gnr2 method */\nstatic const CCTK_REAL MIN_NEWT_TOL2=1.0e-10; /* TOL of new 1D^*_{v^2} gnr2 method */\n\nstatic const CCTK_REAL W_TOO_BIG =1.e20; /* \\gamma^2 (\\rho_0 + u + p) is assumed\n to always be smaller than this. This\n is used to detect solver failures */\nstatic const CCTK_REAL UTSQ_TOO_BIG =1.e20; /* \\tilde{u}^2 is assumed to be smaller\n than this. Used to detect solver\n failures */\n\nstatic const CCTK_REAL FAIL_VAL =1.e30; /* Generic value to which we set variables when a problem arises */\n\nstatic const CCTK_REAL NUMEPSILON=(2.2204460492503131e-16);\n\n\n/* some mnemonics */\n/* for primitive variables */\nstatic const int RHO =0; \nstatic const int UU =1;\nstatic const int UTCON1 =2;\nstatic const int UTCON2 =3;\nstatic const int UTCON3 =4;\nstatic const int BCON1 =5;\nstatic const int BCON2 =6;\nstatic const int BCON3 =7;\n\n/* for conserved variables */\nstatic const int QCOV0 =1;\nstatic const int QCOV1 =2;\nstatic const int QCOV2 =3;\nstatic const int QCOV3 =4;\n\n/********************************************************************************************/\n// Function prototype declarations:\nint Utoprim_2d(eos_struct eos, CCTK_REAL U[NPR], CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL gcon[NDIM][NDIM], \n CCTK_REAL gdet, CCTK_REAL prim[NPR], long &n_iter);\n\ninline int harm_primitives_gammalaw_lowlevel(/*const int index,const int i,const int j,const int k,CCTK_REAL *X,CCTK_REAL *Y,CCTK_REAL *Z,*/\n CCTK_REAL *ADM_3METRIC,\n CCTK_REAL *CONSERVS,CCTK_REAL *PRIMS,\n CCTK_REAL g4dn[NDIM][NDIM],CCTK_REAL g4up[NDIM][NDIM],\n output_stats &stats,eos_struct &eos);\n\ninline int font_fix__hybrid_EOS(CCTK_REAL &u_x, CCTK_REAL &u_y, CCTK_REAL &u_z,CCTK_REAL *CONSERVS,CCTK_REAL *PRIMS,CCTK_REAL *ADM_3METRIC, eos_struct eos);\nvoid eigenvalues_3by3_real_sym_matrix(CCTK_REAL & lam1, CCTK_REAL & lam2, CCTK_REAL & lam3,\n CCTK_REAL M11, CCTK_REAL M12, CCTK_REAL M13, CCTK_REAL M22, CCTK_REAL M23, CCTK_REAL M33);\n\n/********************************************************************************************/\n\n#endif /* HARM_PRIMITIVES_HEADERS_H_ */\n\n\n```\n\n Overwriting ../src/harm_primitives_headers.h\n\n\n\n\n# Step 7: Code validation \\[Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\n\n\n## Step 7.a: `driver_conserv_to_prims.C` \\[Back to [top](#toc)\\]\n$$\\label{driver_conserv_to_prims_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/driver_conserv_to_prims.C\"\n# original_IGM_file_name = \"driver_conserv_to_prims-original.C\"\n# original_IGM_file_path = os.path.join(outdir,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__driver_conserv_to_prims__C = !diff $original_IGM_file_path $outdir/driver_conserv_to_prims.C\n\n# if Validation__driver_conserv_to_prims__C == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for driver_conserv_to_prims.C: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for driver_conserv_to_prims.C: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__driver_conserv_to_prims__C:\n# print(diff_line)\n```\n\n\n\n## Step 7.b: `harm_primitives_lowlevel.C` \\[Back to [top](#toc)\\]\n$$\\label{harm_primitives_lowlevel_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/harm_primitives_lowlevel.C\"\n# original_IGM_file_name = \"harm_primitives_lowlevel-original.C\"\n# original_IGM_file_path = os.path.join(outdir,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__harm_primitives_lowlevel__C = !diff $original_IGM_file_path $outdir/harm_primitives_lowlevel.C\n\n# if Validation__harm_primitives_lowlevel__C == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for harm_primitives_lowlevel.C: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for harm_primitives_lowlevel.C: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__harm_primitives_lowlevel__C:\n# print(diff_line)\n```\n\n\n\n## Step 7.c: `font_fix_gamma_law.C` \\[Back to [top](#toc)\\]\n$$\\label{font_fix_gamma_law_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/font_fix_gamma_law.C\"\n# original_IGM_file_name = \"font_fix_gamma_law-original.C\"\n# original_IGM_file_path = os.path.join(outdir,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__font_fix_gamma_law__C = !diff $original_IGM_file_path $outdir/font_fix_gamma_law.C\n\n# if Validation__font_fix_gamma_law__C == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for font_fix_gamma_law.C: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for font_fix_gamma_law.C: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__font_fix_gamma_law__C:\n# print(diff_line)\n```\n\n\n\n## Step 7.d: `harm_primitives_headers.h` \\[Back to [top](#toc)\\]\n$$\\label{harm_primitives_headers_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/harm_primitives_headers.h\"\n# original_IGM_file_name = \"harm_primitives_headers-original.h\"\n# original_IGM_file_path = os.path.join(outdir,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__harm_primitives_headers__h = !diff $original_IGM_file_path $outdir/harm_primitives_headers.h\n\n# if Validation__harm_primitives_headers__h == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for harm_primitives_headers.h: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for harm_primitives_headers.h: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__harm_primitives_headers__h:\n# print(diff_line)\n```\n\n\n\n# Step 8: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-IllinoisGRMHD__driver_conserv_to_prims.pdf](Tutorial-IllinoisGRMHD__driver_conserv_to_prims.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means).\n\n\n```python\nlatex_nrpy_style_path = os.path.join(nrpy_dir_path,\"latex_nrpy_style.tplx\")\n#!jupyter nbconvert --to latex --template $latex_nrpy_style_path --log-level='WARN' Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.ipynb\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.tex\n!rm -f Tut*.out Tut*.aux Tut*.log\n```\n", "meta": {"hexsha": "a01d268daddfb3436bde40c00b3f63f020a8633c", "size": 127399, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.ipynb", "max_stars_repo_name": "leowerneck/NRPyIGM", "max_stars_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.ipynb", "max_issues_repo_name": "leowerneck/NRPyIGM", "max_issues_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__the_conservative_to_primitive_algorithm.ipynb", "max_forks_repo_name": "leowerneck/NRPyIGM", "max_forks_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2831065383, "max_line_length": 438, "alphanum_fraction": 0.5505380733, "converted": true, "num_tokens": 30395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7718435030872967, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.32610745740560204}} {"text": "# Variational Quantum Eigensolver\n\n Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. \n\n## Overview\n\nIt is widely believed that one of the most promising applications of quantum computing in the near future is solving quantum chemistry problems [1-2]. **Variational Quantum Eigensolver** (VQE) is a strong proof to this possibility of studying quantum chemistry with **Noisy Intermediate-Scale Quantum** (NISQ) devices [1-4]. The core task is to solve the ground state of any molecular Hamiltonian $\\hat{H}$ by preparing a parametrized wave function ansatz $|\\Psi(\\boldsymbol\\theta)\\rangle$ on a quantum computer and adopt classical optimization methods (e.g. gradient descent) to adjust the parameters $\\boldsymbol\\theta$ to minimize the expectation value $\\langle \\Psi(\\boldsymbol\\theta)|\\hat{H}|\\Psi(\\boldsymbol\\theta)\\rangle$. This approach is based on the **Rayleigh-Ritz variational principle**. \n\n$$\nE_0 = \\min_{\\boldsymbol\\theta} \\langle \\Psi(\\boldsymbol\\theta)|\\hat{H}|\\Psi(\\boldsymbol\\theta)\\rangle.\n\\tag{1}\n$$\n\nwhere $E_0$ denotes the ground state energy. Numerically, it can be understood as finding the smallest eigenvalue $\\lambda_{\\min}$ of a **discretized** Hamiltonian $H$ (hermitian matrix) and its corresponding eigenvector $|\\Psi_0\\rangle$. How such a discretization can be done on a classical computer belongs to the art of quantum chemistry and is far beyond the scope of this tutorial. We will discuss this part with a few words in the background section. In general, such a Hamiltonian $H$ is expressed as a weighted sum of Pauli spin operators $\\{X,Y,Z\\}$ (native to quantum devices) such that this information can be processed on a quantum computer.\n\n$$\nH = \\sum_k c_k ~ \\bigg( \\bigotimes_{j=0}^{M-1} \\sigma_j^{(k)} \\bigg),\n\\tag{2}\n$$\n\nwhere $\\sigma_j^{(k)} \\in \\{I,X,Y,Z\\}$ and $M$ stands for qubit number. We refer this form of Hamiltonian as **Pauli strings**. For example, \n\n$$\nH= 0.12~Y_0 \\otimes I_1-0.04~X_0\\otimes Z_1.\n\\tag{3}\n$$\n\nIn the next section, we will provide a brief review on the electronic structure problem which essentially tells us how to calculate the Hamiltonian $H$. For those who are already familiar with this topic or only interested in how to implement VQE on Paddle Quantum, please skip this part and jump into the illustrative example of hydrogen molecule $H_2$.\n\n## Background: the electronic structure problem\n\nIn this section, we focus on one of the fundamental problems in quantum chemistry -- **the electronic structure problem**. To be more specific, we are interested in the low lying energy eigenstates of any given molecule. These knowledge could help predict reaction rates and location of stable structures [5]. Suppose a molecule consists of $N_n$ nuclei and $N_e$ electrons, the first quantized (canonical quantization) Hamiltonian operator $\\hat{H}_{mol}$ describing the total energy of this molecular system can be written as\n\n$$\n\\begin{align}\n\\hat{H}_{\\text{mol}} & = -\\sum_{i}\\frac{\\nabla_{R_i}^2}{2M_i} - \\sum_{i} \\frac{\\nabla_{r_i}^2}{2} -\\sum_{i,j}\\frac{Z_i}{\\lvert R_i - r_j\\lvert} + \\sum_{i,j>i}\\frac{Z_iZ_j}{\\lvert R_i - R_j\\lvert} + \\sum_{i, j>i}\\frac{1}{\\lvert r_i - r_j\\lvert}, \n\\tag{4}\n\\end{align}\n$$\n\nwhere $R_i, M_i,$ and $Z_i$ denote the position, mass and atomic number (the number of protons) of the $i^{th}$ nucleus, and the positions of electrons are $r_i$. The first two sums describe the kinetic energy of nuclei and electrons, respectively. The third sum describes the attractive Coulomb interaction between the positively charged nuclei and the negatively charged electrons. The last two terms represent the repulsive nuclei-nuclei and electron-electron interactions. Here, the molecular Hamiltonian $\\hat{H}_\\text{mol}$ is already in atomic units of energy, **Hartree**. $1$ Hartree is $[\\hbar^2/(m_ee^2a_0^2)] = 27.2$ eV or $630$ kcal/mol, where $m_e, e,$ and $a_0$ stand for the mass of electron, charge of electron, and Bohr radius. \n\n\n**Note:** The spin-orbit interaction and hyperfine interaction are not considered in this picture. They can be treated as perturbations if necessary. \n\n### Born-Oppenheimer approximation\n\nSince the nuclei are much heavier than electrons, the electrons will move much faster than the nuclei. It is reasonable to treat the positions of nuclei as fixed, $R_i =$ constants. This is known as the Born-Oppenheimer approximation by decoupling the behavior of nuclei and electrons in time scale. Consequently, the kinetic energy term of nuclei will disappear and the nuclei-nuclei repulsive interaction term can be viewed as an energy shift (independent of electron positions $r_i$). We could derive the electronic Hamiltonian $\\hat{H}_{\\text{electron}}$ as\n\n$$\n\\begin{align}\n\\hat{H}_{\\text{electron}} & = - \\sum_{i} \\frac{\\nabla_{r_i}^2}{2} -\\sum_{i,j}\\frac{Z_i}{\\lvert R_i - r_j\\lvert} + \\sum_{i, j>i}\\frac{1}{\\lvert r_i - r_j\\lvert} \n\\tag{5},\n\\end{align}\n$$\n\nThe energy levels of the electrons in the molecule can be found by solving the time independent Schrödinger equation\n\n$$\n\\hat{H}_{\\text{electron}} |\\Psi_n \\rangle = E_n |\\Psi_n \\rangle,\n\\tag{6}\n$$\n\nwhere $n$ stands for the energy level. Notice the electron repulsion terms scale as $N_e(N_e-1)/2$ which means for the Oxygen molecule $O_2$ carrying 16 electrons there will be 120 electron repulsion terms in total! In general, this problem cannot be solved analytically. As Dirac concluded in [Quantum mechanics of many-electron systems](https://royalsocietypublishing.org/doi/10.1098/rspa.1929.0094) [6],\n\n> *The underlying physical laws necessary for the mathematical theory of a large part of physics and the whole of chemistry are thus completely known, and the difficulty is only that the exact application of these laws leads to equations much too complicated to be soluble.* \n>\n> ​\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-- Paul Dirac (1929)\n\nA straightforward numerical approach is discretizing the infinite-dimensional Hilbert space into equidistant grid points where linear algebra guides the whole calculation. Suppose each axis of space is discretized into $k$ points, the $N$-electron (drop the subscript e for simplicity) wave function can be written as [2]\n\n$$\n|\\Psi \\rangle = \\sum_{\\mathbf{x_1}, \\ldots, \\mathbf{x_N}} \\psi(\\mathbf{x_1}, \\ldots, \\mathbf{x_N}) \\mathcal{A}(|\\mathbf{x_1}, \\ldots, \\mathbf{x_N}\\rangle).\n\\tag{7}\n$$\n\nwhere coordinate $|\\mathbf{x_j}\\rangle = |r_j\\rangle |\\sigma_j\\rangle$ records the spatial location and spin of the $j^{th}$ electron, $|r_j\\rangle = |x_j,y_j,z_j\\rangle$ for $j\\in \\{1,2,\\cdots,N\\}$, $x_j,y_j,z_j \\in \\{0,1,\\cdots,k-1\\}$ and $\\sigma_j \\in \\{\\downarrow,\\uparrow\\}$ for spin down or up. There will be $k^{3N}\\times 2^{N}$ complex amplitudes in total. Here, $\\mathcal{A}$ denotes anti-symmetrization and a consequence of the Pauli exclusion principle (electrons are fermion), and $\\psi(\\mathbf{x_1}, \\mathbf{x_2}, \\ldots, \\mathbf{x_N})=\\langle\\mathbf{x_1}, \\mathbf{x_2}, \\ldots, \\mathbf{x_N}|\\Psi\\rangle$. One can see that storing such a wave function already requires **exponentially growing memory** with respect to the number of electrons $N$. This would make classical simulation methods based on this naive numerical approach intractable for systems size larger than few tens of electrons. Now, the question becomes can we prepare such a wave function $|\\Psi\\rangle$ directly on a quantum computer and measure the expectation value $E_0$? In the next section, let's take the simplest molecular system -- hydrogen molecule $H_2$ as a concrete example.\n\n\n\n**Note:** A detailed review on quantum chemistry and existing classical computational methods are far beyond the scope of this tutorial, we refer the enthusiastic readers to the standard textbooks *'Molecular Electronic-Structure Theory'* [5] by Helgaker and *'Modern Quantum Chemistry: Introduction to Advanced Electronic Structure Theory'* [7] by Szabo & Ostlund. To bridge to knowledge gap between quantum chemistry and quantum computing, please check the following review papers [Quantum computational chemistry](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.92.015003) [2] and [Quantum Chemistry in the Age of Quantum Computing](https://pubs.acs.org/doi/10.1021/acs.chemrev.8b00803) [1].\n\n**Note:** For energy calculation, it is desired to reach the **chemical accuracy** of $1.6\\times10^{-3}$ Hartree or 1 kcal/mol . \n\n## Ground state of the hydrogen molecule $H_2$\n\n### Building electronic Hamiltonian\n\nFirst of all, let us import the necessary libraries and packages.`qchem` module in Paddle Quantum is developed basing on `psi4` and `openfermion`, so you need to install these two packages before executing the following codes. We strongly encourage you to read the tutorial [Building molecular Hamiltonian](./BuildingMolecule_EN.ipynb) first, which introduces how to utilize our quantum chemistry toolkit `qchem`.\n\n**Note: As to the environment setting, please refer to [README.md](https://github.com/PaddlePaddle/Quantum/blob/master/README.md).**\n\n\n```python\nimport paddle\nimport paddle_quantum.qchem as qchem\nfrom paddle_quantum.utils import Hamiltonian\nfrom paddle_quantum.circuit import UAnsatz\n\nimport os\nimport matplotlib.pyplot as plt\n\nimport numpy\nfrom numpy import pi as PI\nfrom numpy import savez, zeros\n\n# Eliminate noisy python warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n```\n\nTo analyze specific molecules, we need several key information such as **geometry**, **basis set** (such as STO-3G), **multiplicity**, and **charge** to model the molecule and achieve more information about the molecule, such as one-body integrations, two-body integrations, and others. Next, through our built-in quantum chemistry toolkit, we could set a `Hamiltonian` class to carry molecule Hamiltonian information, which may simplify the following calculations.\n\n\n```python\ngeo = qchem.geometry(structure=[['H', [-0., 0., 0.0]], ['H', [-0., 0., 0.74]]])\n# geo = qchem.geometry(file='h2.xyz')\n\n# Save molecule information in to variable molecule, including one-body integrations, one-body integrations, molecular and Hamiltonian\nmolecule = qchem.get_molecular_data(\n geometry=geo,\n basis='sto-3g',\n charge=0,\n multiplicity=1,\n method=\"fci\",\n if_save=True,\n if_print=True\n)\n# Recall Hamiltonian\nmolecular_hamiltonian = qchem.spin_hamiltonian(molecule=molecule,\n filename=None, \n multiplicity=1, \n mapping_method = 'jordan_wigner',)\n# Print results\nprint(\"\\nThe generated h2 Hamiltonian is \\n\", molecular_hamiltonian)\n```\n\n FCI energy for H2_sto-3g_singlet (2 electrons) is -1.137283834485513.\n \n The generated h2 Hamiltonian is \n -0.09706626861762556 I\n -0.04530261550868938 X0, X1, Y2, Y3\n 0.04530261550868938 X0, Y1, Y2, X3\n 0.04530261550868938 Y0, X1, X2, Y3\n -0.04530261550868938 Y0, Y1, X2, X3\n 0.1714128263940239 Z0\n 0.16868898168693286 Z0, Z1\n 0.12062523481381837 Z0, Z2\n 0.16592785032250773 Z0, Z3\n 0.17141282639402394 Z1\n 0.16592785032250773 Z1, Z2\n 0.12062523481381837 Z1, Z3\n -0.2234315367466399 Z2\n 0.17441287610651626 Z2, Z3\n -0.2234315367466399 Z3\n\n\n**Note:** This Hamiltonian is generated with an interatomic distance of $d = 74$ pm. \n\nIn addition to inputting molecular geometry directly, inputting molecular geometry file (.xyz file) is also allowed. For more information about quantum chemistry toolkit, please refer to the tutorial [Building molecular Hamiltonian](./BuildingMolecule_EN.ipynb). If you need to test the geometric configuration of more molecules, please check out this [database](http://smart.sns.it/molecules/index.html).\n\n### Building QNN and trial wave function\n\nTo implement VQE, we firstly need to design a quantum neural network QNN to prepare the wave function ansatz $|\\Psi(\\boldsymbol\\theta)\\rangle$. Here, we provide a 4-qubit quantum circuit template with a depth of $D$ blocks. The dotted frame in the figure below denotes a single block:\n\n\n\n\nNext, we use the `UAnsatz` class and the built-in `real_entangled_layer(theta, D)` circuit template in Paddle Quantum to realize this QNN.\n\n\n\n\n```python\ndef U_theta(theta, Hamiltonian, N, D):\n \"\"\"\n Quantum Neural Network\n \"\"\"\n \n # Initialize the quantum neural network according to the number of qubits N\n cir = UAnsatz(N)\n \n # Built-in {R_y + CNOT} circuit template\n cir.real_entangled_layer(theta[:D], D)\n \n # Lay R_y gates in the last row\n for i in range(N):\n cir.ry(theta=theta[D][i][0], which_qubit=i)\n \n # The quantum neural network acts on the default initial state |0000>\n fin_state = cir.run_state_vector()\n \n # Calculate the expectated value of the given Hamiltonian\n expectation_val = cir.expecval(Hamiltonian)\n\n return expectation_val, cir, fin_state\n```\n\n### Setting up the loss function and model\n\nNow that we have the target Hamiltonian and QNN, we will further define the training model and loss function. By applying the QNN $U(\\theta)$ on the initial state $|0..0\\rangle$, we get the output state $|\\psi(\\boldsymbol\\theta)\\rangle $. Then, the loss function to be minimized is the expectation value, \n\n\n$$\n\\min_{\\boldsymbol\\theta} \\mathcal{L}(\\boldsymbol \\theta) = \\min_{\\boldsymbol\\theta} \\langle \\Psi(\\boldsymbol\\theta)|H |\\Psi(\\boldsymbol\\theta)\\rangle\n= \\min_{\\boldsymbol\\theta} \\sum_k c_k~\\langle \\Psi(\\boldsymbol\\theta)| \\bigotimes_j \\sigma_j^{(k)}|\\Psi(\\boldsymbol\\theta)\\rangle.\n\\tag{8}\n$$\n\n\n```python\nclass StateNet(paddle.nn.Layer):\n \"\"\"\n Construct the model net\n \"\"\"\n\n def __init__(self, shape, dtype=\"float64\"):\n super(StateNet, self).__init__()\n \n # Initialize the list of theta parameters, filling the initial values with a uniform distribution of [0, 2* PI] \n self.theta = self.create_parameter(shape=shape, \n default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2*PI),\n dtype=dtype, is_bias=False)\n \n # Define loss function and forward propagation mechanism\n def forward(self, N, D):\n \n # Calculate loss function/expected value\n loss, cir, fin_state = U_theta(self.theta, molecular_hamiltonian.pauli_str, N, D)\n\n return loss, cir, fin_state\n```\n\n### Hyper-parameters\n\nBefore training the QNN, we also need to set some training hyper-parameters, mainly the learning rate (LR), the number of iterations (ITR), and the depth (D) of repeated blocks. \n\n\n```python\nITR = 80 # Set the number of optimization iterations\nLR = 0.4 # Set the learning rate\nD = 2 # Set the depth of the repetitive calculation module in QNN\nN = molecular_hamiltonian.n_qubits # Set number of qubits\n```\n\n### Training\n\nAfter all the training model parameters are set, we convert the data into Tensor in the Paddle, and then train the quantum neural network. The results of the training process is stored in the summary_data file.\n\n\n\n```python\n# Determine the parameter dimensions of the network \nnet = StateNet(shape=[D + 1, N, 1])\n\n# In general, we use the Adam optimizer to obtain relatively good convergence,\n# Of course you can change it to SGD or RMS prop.\nopt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n\n# Record optimization results\nsummary_iter, summary_loss = [], []\n\n# Optimize iterations\nfor itr in range(1, ITR + 1):\n\n # Forward propagation calculates the loss function\n loss, cir, fin_state = net(N, D)\n\n # Back propagation minimizes the loss function\n loss.backward()\n opt.minimize(loss)\n opt.clear_grad()\n\n # Update optimization results\n summary_loss.append(loss.numpy())\n summary_iter.append(itr)\n\n # Print results\n if itr % 20 == 0:\n print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n print(\"iter:\", itr, \"Ground state energy:\", \"%.4f Ha\" \n % loss.numpy())\n if itr == ITR:\n print(\"\\nCircuit after training:\") \n print(cir)\n\n# Save the training results in the Output folder\nos.makedirs(\"output\", exist_ok=True)\nsavez(\"./output/summary_data\", iter = summary_iter, \n energy=summary_loss)\n```\n\n iter: 20 loss: -1.0510\n iter: 20 Ground state energy: -1.0510 Ha\n iter: 40 loss: -1.1298\n iter: 40 Ground state energy: -1.1298 Ha\n iter: 60 loss: -1.1361\n iter: 60 Ground state energy: -1.1361 Ha\n iter: 80 loss: -1.1371\n iter: 80 Ground state energy: -1.1371 Ha\n \n Circuit after training:\n --Ry(4.710)----*--------------x----Ry(1.569)----*--------------x----Ry(-0.01)--\n | | | | \n --Ry(1.507)----x----*---------|----Ry(1.566)----x----*---------|----Ry(4.392)--\n | | | | \n --Ry(5.984)---------x----*----|----Ry(4.476)---------x----*----|----Ry(1.692)--\n | | | | \n --Ry(0.132)--------------x----*----Ry(7.773)--------------x----*----Ry(3.194)--\n \n\n\n### Benchmarking\nWe have now completed the training of the quantum neural network, and the estimated value of the ground state energy obtained is $E_0 \\approx -1.137 $ Hartree, we compare it with the theoretical value $E_0 = -1.1371$ to benchmark our model. The estimation obtained with VQE agree with a full configuration-interaction (FCI) calculation within chemical accuracy $\\varepsilon = 1.6 \\times 10^{-3}$ Hartree.\n\n\n\n\n```python\nresult = numpy.load('./output/summary_data.npz')\n\neig_val, eig_state = numpy.linalg.eig(\n molecular_hamiltonian.construct_h_matrix())\nmin_eig_H = numpy.min(eig_val.real)\nmin_loss = numpy.ones([len(result['iter'])]) * min_eig_H\n\nplt.figure(1)\nfunc1, = plt.plot(result['iter'], result['energy'], \n alpha=0.7, marker='', linestyle=\"-\", color='r')\nfunc_min, = plt.plot(result['iter'], min_loss, \n alpha=0.7, marker='', linestyle=\":\", color='b')\nplt.xlabel('Number of iteration')\nplt.ylabel('Energy (Ha)')\n\nplt.legend(handles=[\n func1,\n func_min\n],\n labels=[\n r'$\\left\\langle {\\psi \\left( {\\theta } \\right)} '\n r'\\right|H\\left| {\\psi \\left( {\\theta } \\right)} \\right\\rangle $',\n 'Ground-state energy',\n ], loc='best')\n\n#plt.savefig(\"vqe.png\", bbox_inches='tight', dpi=300)\nplt.show()\n```\n\n## Determining the interatomic distance\n\nRecall the above calculation is done with an interatomic distance $d = 74$ pm between two hydrogen atoms. Another interesting aspect we can try with VQE is determining the true interatomic distance by modifying the `h2.xyz` file. The results are summarize in figure below,\n\n\n\nThe lowest value is found around $d = 74$ pm (1 pm = $1\\times 10^{-12}$m), which is consistent with the [experimental data](https://cccbdb.nist.gov/exp2x.asp?casno=1333740&charge=0) $d_{exp} (H_2) = 74.14$ pm.\n\n_______\n\n## References\n\n[1] Cao, Yudong, et al. Quantum Chemistry in the Age of Quantum Computing. [Chemical reviews 119.19 (2019): 10856-10915.](https://pubs.acs.org/doi/10.1021/acs.chemrev.8b00803)\n\n[2] McArdle, Sam, et al. Quantum computational chemistry. [Reviews of Modern Physics 92.1 (2020): 015003.](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.92.015003)\n\n\n[3] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)\n\n[4] Moll, Nikolaj, et al. Quantum optimization using variational algorithms on near-term quantum devices. [Quantum Science and Technology 3.3 (2018): 030503.](https://iopscience.iop.org/article/10.1088/2058-9565/aab822)\n\n[5] Helgaker, Trygve, Poul Jorgensen, and Jeppe Olsen. Molecular electronic-structure theory. John Wiley & Sons, 2014.\n\n[6] Dirac, Paul Adrien Maurice. Quantum mechanics of many-electron systems. [Proceedings of the Royal Society of London. Series A, Containing Papers of a Mathematical and Physical Character 123.792 (1929): 714-733.](https://royalsocietypublishing.org/doi/10.1098/rspa.1929.0094)\n\n[7] Szabo, Attila, and Neil S. Ostlund. Modern quantum chemistry: introduction to advanced electronic structure theory. Courier Corporation, 2012.\n", "meta": {"hexsha": "ab3344f4619ca6c97f820668248ce44cc79c6ae9", "size": 44893, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial/quantum_simulation/VQE_EN.ipynb", "max_stars_repo_name": "gsq7474741/Quantum", "max_stars_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-14T14:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T14:10:23.000Z", "max_issues_repo_path": "tutorial/quantum_simulation/VQE_EN.ipynb", "max_issues_repo_name": "gsq7474741/Quantum", "max_issues_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/quantum_simulation/VQE_EN.ipynb", "max_forks_repo_name": "gsq7474741/Quantum", "max_forks_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 79.8807829181, "max_line_length": 17344, "alphanum_fraction": 0.7428106832, "converted": true, "num_tokens": 5486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.3255874879064411}} {"text": "# Assessing the accuracy of ML-based uncertainties in the context of galaxy photometric redshifts\n\nA data challenge for [From Quarks to Cosmos with AI](https://events.mcs.cmu.edu/qtc2021/)\n\n_Alex I. Malz (German Centre for Cosmological Lensing)_\n\n## Motivation: Uncertainty quantification\n\nMore and more ML/AI methods, particularly in Bayesian deep learning, yield uncertainties $\\hat{p}(y | x_{i})$ of target parameters $y$ given observed random variables $x_{i}$, rather than just point estimates $\\hat{y}_{i}$.\nThough rarely framed as such, these uncertainties are _posteriors_, and there's more than meets the eye to what lies on the righthand side of the conditional.\n\nReally, an estimated posterior should be writen as $p(y | x_{i}, \\{y_{n}, x_{n}\\}_{N}, \\pi)$ for training data $\\{y_{n}, x_{n}\\}_{N}$ and algorithm $\\pi$.\nThough the dependence on training data is straightforward, the dependence on the algorithm, meaning the estimation model and its implementation, is subtle.\nHowever, if it were not there, then every method trained on the same data would yield identical estimated uncertainties, which is not observed.\nWhile the training set $\\{y_{n}, x_{n}\\}_{N}$ is equivalent to an _explicit prior_, the algorithm $\\pi$ must be an _implicit prior_.\n\nAnother way of looking at estimated posteriors is in terms of the type of uncertainty encompassed by each term on the righthand side of the conditional.\nFor a noisy measurement or a stochastic generative process, the random variable $x_{i} \\sim p(x | y_{i})$ represents the _aleatoric uncertainty_, that inherent to the data.\nHowever, the training set $\\{y_{n}, x_{n}\\}_{N}$ and implemented algorithm $\\pi$ could potentially be improved to yield a better estimate and thus constitute sources of _epistemic uncertainty_.\nIn physics, we want to learn the aleatoric uncertainty $p(x | y_{i})$, which we can't get from the $p(y | x_{i}, \\{y_{n}, x_{n}\\}_{N}, \\pi)$ in hand without knowing $p(y | \\{y_{n}, x_{n}\\}_{N}, \\pi)$.\n\nMeanwhile, assessments of the performance of estimated $p(y | x_{i}, \\{y_{n}, x_{n}\\}_{N}, \\pi)$ are almost always made by comparison to known $y_{i}$, leaving unanswered the question of how well the estimator approximates $p(y | x_{i})$.\nWhy?\nThe problem is that $p(y | x_{i})$ is not necessarily known, certainly not for observed $y_{i}$ measured in nature, but also generally for simulated $y_{i}$, at least in astrophysics.\n\n## tl;dr Goals\n\nThis data challenge invites participants to address any of the following open problems.\n- How can we use AI to estimate posteriors?\n- How should we assess posterior estimates?\n- How may we quantify the implicit prior(s)?\n\nThis tutorial/demo provides some starting points for answering these questions in the context of photometric redshifts (photo-$z$s).\n\n## Context: Photometric redshifts\n\n[Photo-$z$s](https://en.wikipedia.org/wiki/Photometric_redshift) provide an excellent testbed for addressing these issues but require some introduction.\nThere isn't a definitive primer, but here are several overviews that are informative, if a bit dry.\n- [basic intro from Rubin Observatory](https://www.lsst.org/science/dark-energy/photometric-redshift)\n- [old overview covering classic concepts](https://ned.ipac.caltech.edu/level5/Glossary/Essay_photredshifts.html)\n- [recent review of estimation methods](https://arxiv.org/abs/1805.12574)\nIf these don't answer your questions, Chapter 0 of [my thesis](https://zenodo.org/record/3973536) might, or, better yet, [the slides from my defense](https://github.com/aimalz/ship-of-theses/tree/master/presentation) make for a better tl;dr.\n\nOne reason photo-$z$s are perfect for a data challenge is that they are simple enough to obtain $p(y | x_{i})$ along the way to generating a sample of $(y_{i}, x_{i})$ pairs.\nHere, the target variable $y \\to z$ is redshift, a scalar, and the data $x \\to \\vec{d} = (u, g, r, i, z, y)$, or some trivial function thereof, is a vector of length $<10$ observed [photometric magnitudes](https://en.wikipedia.org/wiki/Magnitude_(astronomy)) of galaxies through [broadband optical filters](https://en.wikipedia.org/wiki/Photometric_system) (which I somewhat arbitrarily choose to be those of [the Vera C. Rubin Observatory](https://www.lsst.org/)).\nBecause of the extremely low dimensionality of the problem, we can forward model not just individual pairs $(z_{i}, \\vec{d}_{i})$ but the entire joint probability space $p(z, \\vec{d})$, thereby obtaining $p(y | x_{i})$ for every $(z_{i}, \\vec{d}_{i})$.\nThat doesn't mean it's trivial to do so -- most of this tutorial concerns that forward-modeling procedure -- but it is possible.\n\nAnother reason photo-$z$s are perfect for this data challenge is that comprehensive uncertainty quantification for galaxy redshifts in the absence of spectroscopy are crucial for the Legacy Survey of Space and Time (LSST), an upcoming photometric survey on the Rubin Observatory.\nThis data challenge has the ulterior motive of strengthening the cosmology analysis pipeline of LSST's Dark Energy Science Collaboration (DESC).\nThis tutorial makes use of two pieces of software DESC members are publicly developing right now, [RAIL](https://github.com/LSSTDESC/RAIL) and [qp](https://github.com/LSSTDESC/qp), whose functionality will be introduced where relevant, along with other code dependencies.\nParticipants need not use either in their responses to the challenge questions, but the development team welcomes feedback from potential users, contributions to the codebase that could result from this data challenge, and new team members, DESC membership not required.\n\n# Tutorial and challenge prompts\n\nFinally, without more ado, we set the stage with a tutorial that:\n1. creates realistically complex mock photo-$z$ posteriors, redshifts, and photometry to define training and test sets;\n2. estimates photo-$z$ posteriors of the test set given the training set using ML;\n3. quantifies how closely the estimated posteriors approximate the true ones.\n\n_The three-pronged structure of this tutorial is inspired by that of RAIL, which has subpackages corresponding to each of the enumerated parts of the tutorial: `rail.creation`, `rail.estimation`, and `rail.evaluation`._\n\nThe challenge comes from building on the tutorial content to conduct a self-guided investigation of the open questions.\nTo get the most out of this opportunity, think of this tutorial as a lab manual that presents an experimental procedure to answer each question and includes an example of a possible solution, then invites participants to \"riff\" on those solutions to devise and implement their own.\nThe greatest opportunities for such investigations can be found under the headings **\"Your turn!\"** throughout the tutorial, but there are certainly more interesting directions to go in.\n\n## 0. Setup\n\nThis tutorial uses several packages that may not be installed in the conference's kernel.\nThe following commands installed them successfully on Google Colab, but there might be a better way to install it on PSC machines.\nOn the PSC machines, first follow [these instructions](https://gist.github.com/EiffL/a8cfa39c635334d063f0d3c07a85d1ec).\n\n\n```python\n# !pip install cde-diagnostics\n# !pip install cdetools\n# !pip install corner\n# !pip install FlexCode\n# !pip install pzflow\n# !pip install sklearn\n# !pip install xgboost==0.90\n```\n\n\n```python\nimport jax.numpy as jnp\nimport numpy as np\nimport pandas as pd\nimport sklearn\n```\n\n\n```python\n# !git clone https://github.com/COINtoolbox/photoz_catalogues.git ..\n# !pip install git+https://github.com/LSSTDESC/RAIL.git#egg=rail[Full]\n# !pip install git+https://github.com/LSSTDESC/qp.git#egg=qp[Full]\n```\n\n\n```python\nimport cdetools\nimport flexcode\nimport pzflow\nimport qp\nimport rail\n```\n\n\n```python\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpl_patches\nmpl.rc('text', usetex=False)\n\nimport corner\n```\n\n## 1. Generating test and training data, including true photo-$z$ posteriors\n\nThis is the most complex of the parts of the tutorial, which should leave readers with a sense of why this kind of experiment has not been done for higher-dimensional data.\nThere are three main steps:\n0. Prepare and explore data to use as the basis for a realistically complex generative model.\n1. Emulate a realistically complex $p(z, \\vec{d})$ probability space using input data.\n2. Emulate a distinct $p'(z, \\vec{d})$ probability space from an existing model $p(z, \\vec{d})$ of that space.\n3. Sample $p(z, \\vec{d})$ and $p'(z, \\vec{d})$ to produce test and training sets, respectively, with known $z$, $\\vec{d}$, and $p(z | \\vec{d})$.\n\n### Data\n\nThough we're going to forward-model mock data to experiment on, we want it to be _realistically complex_, meaning it shares the physical degeneracies and systematic errors that would be present in a real data set.\nThe [Happy/Teddy data sets](https://github.com/COINtoolbox/photoz_catalogues) (see [Beck, et al 2017](https://arxiv.org/abs/1701.08748) for full release notes) are curated subsamples of the [Sloan Digital Sky Survey (SDSS) Data Release (DR) 12](https://www.sdss.org/dr12/), a spectroscopic survey with high-fidelity redshift measurements, and were created by the [Cosmostatistics Initiative (COIN)](https://cosmostatistics-initiative.org/).\nThe data sets are defined to emulate the kinds of differences in observational properties of galaxies with measured spectroscopic redshifts and those for which only photometry is available, and they were created with the goal of determining the impact of imbalance between training, validation, and test sets for photo-$z$ point estimation.\nThey are thus an appropriate starting point for creating a realistically complex model of the joint probability space $p(z, \\vec{d})$.\n\nOf course there are plenty of other potential data sets available, including those that are simulated, which may be advantageous for the potential to estimate other galaxy properties such as stellar mass and star formation rate that are known in a simulation but not directly measurable with real data.\n\n\n```python\nhappy_path = '../photoz_catalogues/Happy/happy_'\nheader = pd.read_csv(happy_path+'A', delim_whitespace=True, nrows=0).columns[1:]\nteddy_path = '../photoz_catalogues/Teddy/teddy_'\n\nhappy, teddy = {}, {}\nfor lett in ['A', 'B', 'C', 'D']:\n happy[lett] = pd.read_csv(happy_path+lett, delim_whitespace=True, header=None, skiprows=1, names=header)\n happy[lett] = happy[lett]\n teddy[lett] = pd.read_csv(teddy_path+lett, delim_whitespace=True, header=None, skiprows=7, names=header)\n teddy[lett] = teddy[lett]\n```\n\n\n```python\n# TODO: separate Happy and Teddy\n\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\nfor j, col in enumerate(['z_spec', 'mag_r']):\n for i, lett in enumerate(['A', 'B', 'C', 'D']):\n ax[j][0].hist(happy[lett][col], alpha=0.25, bins=100, density=False, label='happy_'+lett)\n ax[j][1].hist(teddy[lett][col], alpha=0.25, bins=100, density=False, label='teddy_'+lett)\n ax[j][0].set_xlabel(col)\n ax[j][0].legend()\n ax[j][1].set_xlabel(col)\n ax[j][1].legend()\n```\n\nFor convenience later on, we can safely cut off the tiny fraction of outliers in redshift and $r$-band magnitude.\n\n\n```python\nz_min, z_max = 0., 1.5\nr_min, r_max = 10., 25.\n```\n\n\n```python\ncolorcycle = 'rbgcmy'\nfig = corner.corner(happy['A'][['u-g', 'g-r', 'r-i', 'i-z']], color='k', alpha=0.25)\nfor i, lett in enumerate(['B', 'C', 'D']):\n corner.corner(happy[lett][['u-g', 'g-r', 'r-i', 'i-z']], fig=fig, color=colorcycle[i], alpha=0.25)\n \nfig = corner.corner(teddy['A'][['u-g', 'g-r', 'r-i', 'i-z']], color='k', alpha=0.25)\nfor i, lett in enumerate(['B', 'C', 'D']):\n corner.corner(teddy[lett][['u-g', 'g-r', 'r-i', 'i-z']], fig=fig, color=colorcycle[i], alpha=0.25)\n```\n\n### Emulating $p(z, \\vec{d})$ from input data with `pzflow`\n\n[`pzflow`](https://github.com/jfcrenshaw/pzflow) is a package for making normalizing flows from sets of redshifts and photometry in order to estimate or otherwise model photo-$z$ posteriors.\nWe'll use it to make a normalizing flow that will serve as the model for $p(z, \\vec{d})$.\nThis is the only part of the tutorial that explicitly takes advantage of GPU capabilities.\n\n_This content is adapted from pzflow's [conditional redshifts demo](https://github.com/jfcrenshaw/pzflow/blob/main/examples/conditional_redshift_example.ipynb), written by John Franklin Crenshaw (UW)._\n_The same functionality can also be accessed through a `rail.Creator()` object._\n\n\n```python\nfrom pzflow import Flow\nfrom pzflow.bijectors import Chain, ColorTransform, InvSoftplus, StandardScaler, RollingSplineCoupling\nfrom pzflow.examples import galaxy_data\n```\n\nLet's start with a demonstration of how pzflow makes a model of $p(z, \\vec{d}$ from its own demo data.\n\n\n```python\ndata = galaxy_data()\n\n# restrict to Happy/Teddy range for coverage in demo\ndata = data[(data['redshift'] > z_min) & (data['redshift'] < z_max) & (data['r'] > r_min) & (data['r'] < r_max)]\n\n# normalize\ndata = data.values\n\n# use fewer bands to be able to compare with Happy/Teddy\ndata = data[:, :-1]\n\n# convert magnitudes to a reference magnitude and colors\ndata[:, 1], data[:, 2:] = data[:, 3], np.diff(data[:,1:])\n\n# standard scale the reference magnitude and colors\ndata[:, 1:] = (data[:, 1:] - data[:, 1:].mean(axis=0))/data[:, 1:].std(axis=0)\n\n# calculate the mean and standard deviations of the dimensions\n# note that on this side of the color transform, we are working\n# in color space, so I calculate the mean and std dev of these \n# variables instead of the raw magnitudes\nmeans = data[:, 1:].mean(axis=1)\nstds = data[:, 1:].std(axis=1)\n\n# save the new set\ndata = pd.DataFrame(data, columns=('redshift', 'r', 'u-g', 'g-r', 'r-i', 'i-z'))\n# trim_data[i][lett] = data\n```\n\n\n```python\n# set the inverse softplus parameters, estimated\n# to ensure that sampled redshifts are positive\ncolumn_idx = 0\nsharpness = 5\nn_epoch = 125\n\n# construct our bijector\n# by chaining all these layers\nbijector = Chain(\n InvSoftplus(column_idx, sharpness),\n StandardScaler(means[column_idx], stds[column_idx]),\n RollingSplineCoupling(nlayers=1, n_conditions=len(data.columns)-1),\n)\n\n# To create the conditional flow, we have to provide\n# 1. The names of the data columns\n# 2. The bijector\n# 3. The names of the conditional columns\nflow = Flow(data.columns[:1], bijector, conditional_columns=data.columns[1:])\n\nlosses = flow.train(data, epochs=n_epoch, verbose=True)\n\nplt.plot(losses)\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Training loss\")\nplt.show()\n```\n\nWe need to choose a redshift grid upon which to evaluate the posterior PDFs.\n\n\n```python\ngranularity = 100\ngrid = np.linspace(z_min, z_max, granularity)\n```\n\nLet's check one of them before making more.\n\n\n```python\nchosen = 999\n\ngalaxy = data.loc[[chosen]]\npdf = flow.posterior(galaxy, column=\"redshift\", grid=grid)\n\nplt.plot(grid, pdf[0], label='Posterior')\nplt.axvline(galaxy['redshift'].values[0], 0, 1, c='C3', label='True redshift')\nplt.legend()\nplt.xlabel(\"redshift\")\nplt.show()\n```\n\nThe code below limits the number of sample posteriors to generate only because I ran out of memory when attempting to save posteriors for the whole set of demo data on PSC (but not on Google Colab).\n\n\n```python\nsamples = flow.sample(1, conditions=data[:5000], seed=0)\nplt.hist(data['redshift'], range=(0, 2.5), bins=40, histtype='step', label='data', density=True)\nplt.hist(samples['redshift'], range=(0, 2.5), bins=40, histtype='step', label='samples', density=True)\nplt.xlabel('z')\nplt.legend()\nplt.show()\n```\n\n\n```python\nz = samples['redshift']\nz.to_csv('test_set_redshifts.csv')\n\nphot = samples[['r', 'u-g', 'g-r', 'r-i', 'i-z']]\nphot.to_csv('test_set_photometry.csv')\n\nposteriors = flow.posterior(samples, column=\"redshift\", grid=grid)\nwith open('test_set_posteriors.csv', 'wb') as fn:\n jnp.save(fn, posteriors)\n```\n\nWe can do this procedure for all the Happy/Teddy samples so we can experiment with them later.\nIt's kind of slow, at least without using GPU, and it only needs to be done once, so we won't do it in realtime.\n\n\n```python\n# full_data = {'happy': happy, 'teddy': teddy}\n# n_out = 1000\n\n# for name, dat in full_data.items():\n# for lett in ['A', 'B', 'C', 'D']:\n# print(name+lett)\n# print(dat[lett].columns)\n# dat[lett] = dat[lett][['z_spec', 'mag_r', 'u-g', 'g-r', 'r-i', 'i-z']]\n# dat[lett] = dat[lett][(dat[lett]['z_spec'] > z_min) & (dat[lett]['z_spec'] < z_max) & (dat[lett]['mag_r'] > r_min) & (dat[lett]['mag_r'] < r_max)]\n# dat[lett] = dat[lett].rename(columns={'z_spec': 'redshift', 'mag_r': 'r'})\n \n# data = dat[lett].values\n\n# # standard scale the reference magnitude and colors\n# data[:, 1:] = (data[:, 1:] - data[:, 1:].mean(axis=0))/data[:, 1:].std(axis=0)\n\n# # calculate the mean and standard deviations of thefrom sklearn.cross_validation import train_test_split dimensions\n# # note that on this side of the color transform, we are working\n# # in color space, so I calculate the mean and std dev of these \n# # variables instead of the raw magnitudes\n# means = data[:, 1:].mean(axis=0)\n# stds = data[:, 1:].std(axis=0)\n\n# # save the new set\n# data = pd.DataFrame(data, columns=('redshift', 'r', 'u-g', 'g-r', 'r-i', 'i-z'))\n\n# # construct our bijector\n# # by chaining all these layers\n# bijector = Chain(\n# InvSoftplus(column_idx, sharpness),\n# StandardScaler(means[column_idx], stds[column_idx]),\n# RollingSplineCoupling(nlayers=1, n_conditions=len(data.columns)-1),\n# )\n\n# # To create the conditional flow, we have to provide\n# # 1. The names of the data columns\n# # 2. The bijector\n# # 3. The names of the conditional columns\n# flow = Flow(data.columns[:1], bijector, conditional_columns=data.columns[1:])\n\n# losses = flow.train(data, epochs=n_epoch, verbose=False)\n\n# samples = flow.sample(1, conditions=data.sample(n_out), seed=0)\n\n# z = samples['redshift']\n# z.to_csv(name+lett+'redshifts.csv', index=False)\n\n# phot = samples[['r', 'u-g', 'g-r', 'r-i', 'i-z']]\n# phot.to_csv(name+lett+'photometry.csv', index=False)\n\n# posteriors = flow.posterior(samples, column=\"redshift\", grid=grid)\n# with open(name+lett+'posteriors.csv', 'wb') as fn:\n# jnp.save(fn, posteriors)\n```\n\n### Emulating $p'(z, \\vec{d})$ from $p(z, \\vec{d})$ using `rail.creation`\n\nWhile one can build $p(z, \\vec{d})$ from an input data set, more systematic investigation can be conducted by creating many training, validation, and test set combinations that are incremental variations on one another.\nAs one of RAIL's purposes is to conduct one such experiment, the `rail.creation` subpackage not only wraps `pzflow` (the above example can be executed just as easily through the RAIL interface) but also includes physically motivated forms of systematic discrepancy between training and test sets that can be applied to a tunable degree to create \"degraded\" versions of an original $p(z, \\vec{d})$ space.\nSo, for completeness, let's demonstrate how to create a new $p'(z, \\vec{d})$ from an existing $p'(z, \\vec{d})$ using `rail.creation`.\n\n_This content is taken directly from RAIL's [degradation demo](), written by John Franklin Crenshaw (UW)._\n\n\n```python\nfrom pzflow.examples import example_flow\nfrom rail.creation import Creator, engines\nfrom rail.creation.degradation import InvRedshiftIncompleteness, LineConfusion\n```\n\nWe can create a new normalizing flow model of the $p(z, \\vec{d})$ space based on an existing one.\nLet's start with one that emulates redshift incompleteness.\n\n\n```python\nflow = engines.FlowEngine(example_flow())\ncreator = Creator(flow)\ndegraded_creator = Creator(flow, degrader=InvRedshiftIncompleteness(0.8))\n```\n\n\n```python\nsamples = creator.sample(100000)\ndegraded_samples = degraded_creator.sample(100000)\n```\n\n\n```python\nfig, ax = plt.subplots(figsize=(4.5,4.5), dpi=100)\nax.hist(samples['redshift'], bins=20, range=(0,2.3), histtype='step', label=\"Unbiased samples\")\nax.hist(degraded_samples['redshift'], bins=20, range=(0,2.3), histtype='step', label=\"Degraded samples\")\nax.legend()\nax.set(xlabel=\"Redshift\", ylabel=\"Number of galaxies\", xlim=(0,2.3))\nplt.show()\n```\n\nAs expected, the \"degraded\" model has a different redshift distribution than the original one.\nNext, we can try to emulate errors in the spectroscopic catalog that can arise from misidentified emission lines.\n\n\n```python\ndef OxygenLineConfusion(data, seed=None):\n OII = 3727\n OIII = 5007\n \n data = LineConfusion(true_wavelen=OII, wrong_wavelen=OIII, frac_wrong=0.02)(data, seed)\n data = LineConfusion(true_wavelen=OIII, wrong_wavelen=OII, frac_wrong=0.01)(data, seed)\n return data\n```\n\n\n```python\nflow = engines.FlowEngine(example_flow())\ncreator = Creator(flow)\ndegraded_creator = Creator(flow, degrader=OxygenLineConfusion)\n```\n\n\n```python\nsamples = creator.sample(100000, seed=0)\ndegraded_samples = degraded_creator.sample(100000, seed=0)\n```\n\n\n```python\nfig, ax = plt.subplots(figsize=(4.5,4.5), dpi=100)\nax.scatter(samples[\"redshift\"], degraded_samples[\"redshift\"], s=0.1)\nax.set(xlabel=\"True spec-z\", ylabel=\"Erroneous spec-z\")\nplt.show()\n```\n\n### Your turn!\n\nThese are just two ways to create a probability space $p(z, \\vec{d})$ that can forward model redshifts, photometry, and photo-$z$ posteriors.\nNext, we'll use the samples drawn from these systematically different models as training, validation, and test sets for estimators of photo-$z$ posteriors.\n\n**CHALLENGE**: Try modeling $p(z, \\vec{d})$ with different starting data sets.\n\n**CHALLENGE**: How would you incorporate the notion of measurement errors ($\\vec{d}_{meas} \\sim p(\\vec{d}_{meas} | \\vec{d}_{true})$) into the normalizing flow model for the data?\n\n**CHALLENGE**: Make systematically different sample data sets to use as training, validation, and test sets, varying them in controlled ways.\n\n**CHALLENGE**: Devise and implement another creator of a joint probability space that can encompass realistic complexity of photometric data.\n\n**CHALLENGE**: Extend the probability space to $p(z, SED)$ to draw redshifts, full spectra, and redshift posteriors.\n\n## 2. Estimating photo-z posterior PDFs\n\nThere are many estimators of photo-$z$ posteriors, and many of those are compared to one another in [Schmidt & Malz, et al. 2020](https://arxiv.org/abs/2001.03621). \nOf the tested estimators, including ML and non-ML methods, the most promising was [`FlexCode`](https://github.com/tpospisi/FlexCode) ([Izbicki & Lee, 2017](https://arxiv.org/abs/1704.08095)), which also happens to be one of the easiest to install and apply, so we'll demonstrate it as an example of an estimator of photo-$z$ posteriors.\n\n### Estimating photo-$z$ posterior PDFs with FlexCode\n\nA demonstration of `FlexCode` in the context of photo-$z$s can be found in [Dalmasso, et al 2019](https://arxiv.org/abs/1908.11523), with demos in `R` published on [GitHub](https://github.com/Mr8ND/cdetools_applications).\nWe'll demonstrate it on the pzflow-based samples generated from the Happy/Teddy data sets.*italicized text*\n\n_This content is adapted from FlexCode's [Teddy tutorial](https://github.com/tpospisi/FlexCode/blob/master/tutorial/Flexcode-tutorial-teddy.ipynb), written by Nic Dalmasso (CMU)._\n_The same functionality can also be accessed through a `rail.Estimator()` object; see [tutorial](https://github.com/LSSTDESC/RAIL/blob/master/examples/estimation/RAIL_estimation_demo.ipynb) written by Sam Schmidt (UC Davis)._\n\n\n```python\nn_grid = granularity\n\n# Select regression method\nfrom flexcode.regression_models import NN\n\n# Parameters\nbasis_system = \"cosine\" # Basis system\nmax_basis = 31 # Maximum number of basis. If the model is not tuned,\n # max_basis is set as number of basis\n\n# Regression Parameters \n# If a list is passed for any parameter automatic 5-fold CV is used to\n# determine the best parameter combination.\nparams = {\"k\": 5}#[5, 10, 15, 20]} # A dictionary with method-specific regression parameters.\n```\n\nLet's try first with a representative training/validation set.\n\n\n```python\nx_orig = pd.read_csv('test_set_photometry.csv')[['r', 'u-g', 'g-r', 'r-i', 'i-z']].to_numpy()\ny_orig = pd.read_csv('test_set_redshifts.csv')[['redshift']].to_numpy()\nposteriors_orig = pd.DataFrame(np.load('test_set_posteriors.csv')).to_numpy()\n\n# n_samp = 10000\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test, posteriors_train, posteriors_test = train_test_split(x_orig, y_orig, posteriors_orig, \n train_size=2000, random_state=42)\nx_train, x_validation, y_train, y_validation, posteriors_train, posteriors_validation = train_test_split(x_train, y_train, posteriors_train, \n train_size=1000, random_state=42)\n```\n\n\n```python\n# Parameterize model\nmodel = flexcode.FlexCodeModel(NN, max_basis, basis_system, regression_params=params)\n\n# Fit model - this will also choose the optimal number of neighbors `k`\nmodel.fit(x_train, y_train)\n\n# Tune model - Select the best number of basis\nmodel.tune(x_validation, y_validation)\n\n# Predict new densities on grid\ncde_test, y_grid = model.predict(x_test, n_grid=n_grid)\n```\n\nWe can examine one of the photo-$z$ posteriors estimated with the perfectly representative training/validation set.\n\n\n```python\nchosen = 9\n\nplt.plot(y_grid, cde_test[chosen], label='Estimated posterior')\nplt.plot(grid, posteriors_test[chosen], label='True posterior')\nplt.axvline(y_test[chosen], 0, 1, c='C3', label='True redshift')\nplt.legend()\nplt.xlabel(\"redshift\")\nplt.show()\n```\n\nIt looks pretty good!\nNow let's try training and validating with some Happy/Teddy data but estimating posteriors on the test set from the pzflow demo.\n\n\n```python\ny_train = pd.read_csv('teddyAredshifts.csv')['redshift'].to_numpy()\nx_train = pd.read_csv('teddyAphotometry.csv')[['r', 'u-g', 'g-r', 'r-i', 'i-z']].to_numpy()\n\ny_validation = pd.read_csv('teddyBredshifts.csv')['redshift'].to_numpy()\nx_validation = pd.read_csv('teddyBphotometry.csv')[['r', 'u-g', 'g-r', 'r-i', 'i-z']].to_numpy()\n```\n\n\n```python\n# Parameterize model\nmodel = flexcode.FlexCodeModel(NN, max_basis, basis_system, regression_params=params)\n\n# Fit model - this will also choose the optimal number of neighbors `k`\nmodel.fit(x_train, y_train)\n\n# # # Tune model - Select the best number of basis\nmodel.tune(x_validation, y_validation)\n\n# # Predict new densities on grid\ncde_test_bias, y_grid_bias = model.predict(x_test, n_grid=n_grid)\n```\n\n\n```python\nplt.plot(y_grid_bias, cde_test_bias[chosen], label='Estimated posterior (biased training set)')\nplt.plot(y_grid, cde_test[chosen], label='Estimated posterior (unbiased training set)')\nplt.plot(grid, posteriors_test[chosen], label='True posterior')\nplt.axvline(y_test[chosen], 0, 1, c='C3', label='True redshift')\nplt.legend()\nplt.xlabel(\"redshift\")\nplt.show()\n```\n\nAs expected, the biased training and validation sets worsen the estimated posterior PDFs.\n\n### Your turn!\n\nAI is underutilized in estimating photo-$z$ posteriors, so the most exciting aspect of this challenge is to improve upon existing estimators.\n\n**CHALLENGE**: Implement another estimator of photo-$z$ posteriors; consider those used in [Brian Nord's data challenge](https://github.com/deepskies/DeeplyUncertain-Public) for inspiration.\n\n**CHALLENGE**: Devise and implement a way to obtain likelihoods $p(\\vec{d} | z, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)$ rather than posteriors $p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)$ .\n\n## 3. Evaluating the performance of estimated photo-$z$ posterior PDFs\n\nOnce we have estimated photo-$z$ posterior PDFs, we need a way to determine if they're actually any good.\nSince the tutorial has only one method but multiple training/validation sets, that's all we can compare for now.\n\n### Metrics of estimated photo-$z$ posteriors and true redshifts\n\nFirst, let's try out a couple metrics of estimated photo-$z$ posteriors that do not require knowledge of the true photo-$z$ posteriors.\nThere's additional functionality for the case of having true redshifts but not true posteriors in [cdetools](https://github.com/tpospisi/cdetools) and [cde-diagnostics](https://github.com/zhao-david/CDE-diagnostics), but this should give a general idea.\n\n\n```python\nfrom cdetools import cde_loss, cdf_coverage, hpd_coverage\n```\n\nThe Probability Integral Transform (PIT) is defined as \n\\begin{equation}\nPIT = \\int_{-\\infty}^{z_{true}} p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi) dz .\n\\end{equation}\nA histogram of PIT values is commonly used to assess how consistent a population of photo-$z$ PDFs are with the true redshifts.\nIdeally, it would be a uniform distribution, meaning N% of galaxies have their true redshift within the Nth percentile of their estimated photo-$z$ posterior PDF.\n\n\n```python\npit_values = cdf_coverage.cdf_coverage(cde_test, y_grid, y_test)\npit_values_bias = cdf_coverage.cdf_coverage(cde_test_bias, y_grid_bias, y_test)\n\nplt.hist(pit_values, alpha=0.5, bins=100, label='representative')\nplt.hist(pit_values_bias, alpha=0.5, bins=100, label='biased')\nplt.ylim(0, 100)\nplt.legend()\nplt.xlabel('PIT')\n```\n\nThe Highest Predictive Density (HPD) \n\\begin{equation}\nHPD = \\int_{z': p(z' | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi) \\geq p(z | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)} p(z' | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi) dz\n\\end{equation}\nis like the area of the PDF where it exceeds a given value.\nOver a population, it would ideally be flat, like the PIT.\n[A talk by David Zhao (CMU)](https://drive.google.com/file/d/1uvPtK_RcTUHEwt0ZYld41VKEPHnehWbN/view) has a lovely visualization of the HPD.\n\n\n```python\nhpd_cov = hpd_coverage.hpd_coverage(cde_test, y_grid, y_test)\nhpd_cov_bias = hpd_coverage.hpd_coverage(cde_test_bias, y_grid_bias, y_test)\n\nplt.hist(hpd_cov, alpha=0.5, bins=100, label='representative')\nplt.hist(hpd_cov_bias, alpha=0.5, bins=100, label='biased')\nplt.ylim(0, 100)\nplt.legend()\nplt.xlabel('HPD')\n```\n\nThe CDE loss \n\\begin{equation}\n\\hat{L} = \\frac{1}{K} \\sum_{i=1}^{K} \\int \\left(p(z | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)\\right)^{2} dz - \\frac{2}{K} \\sum_{i=1}^{K} p(z_{i} | \\vec{d}_{i}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)\n\\end{equation}\napproximates the true posterior from the estimated posterior evaluated at the true redshift.\nIt's explained quite well in [a talk by Nic Dalmasso (CMU)](https://www.dropbox.com/s/2r4tl4qv0iyqo9b/STAMPS_LSST_CDE_Tools_Presentation.pdf?dl=0).\nA lower value indicates a better estimator.\n\n\n```python\nprint(cde_loss.cde_loss(cde_test, y_grid, y_test))\nprint(cde_loss.cde_loss(cde_test_bias, y_grid_bias, y_test))\n```\n\n### Comparison of estimated and true photo-$z$ posterior PDFs\n\nThere are two categories of metrics of approximated and true PDF: \nthose that either rely upon or force the normalization condition $\\int p(z) dz = 1$and those that evaluate differences between arbitrary functions.\n`qp` [(Malz, et al 2018)](https://arxiv.org/abs/1806.00014) is a package for manipulating univariate PDFs under many parameterizations and includes a few comparison metrics.\n\nThe [original version](https://github.com/aimalz/qp) consistently enforced normalization but had limited functionality, whereas the [new version](https://github.com/LSSTDESC/qp) includes many more parameterizations whose usage is \"at your own risk\" in terms of possibly violating normalization.\nWe'll use the new version for the sake of speed but evaluating metrics using simplified functions ported from the old version due to a (hopefully transient) bug in the handling of large sets of posteriors.\nThe first step is to get both the true posteriors and the approximations evaluated on the same grid of redshifts.\n\n_This content is adapted from the [qp demo](https://github.com/LSSTDESC/qp/blob/master/docs/notebooks/demo.ipynb), written by Alex Malz (GCCL@RUB), Phil Marshall (SLAC), and Eric Charles (SLAC), and [qp metrics demo](https://github.com/LSSTDESC/qp/blob/master/docs/notebooks/kld.ipynb), written by Alex Malz (GCCL@RUB) and Phil Marshall (SLAC)._\n\n\n```python\n# P = qp.Ensemble(qp.interp, data=dict(xvals=grid.reshape(grid.shape[0]), yvals=posteriors_test))\nQ = qp.Ensemble(qp.interp, data=dict(xvals=y_grid.reshape(y_grid.shape[0]), yvals=cde_test))\nQ_bias = qp.Ensemble(qp.interp, data=dict(xvals=y_grid.reshape(y_grid_bias.shape[0]), yvals=cde_test_bias))\ngrid, approx_pdf_on_grid = Q.gridded(grid)\ngrid, approx_pdf_on_grid_bias = Q_bias.gridded(grid)\n```\n\nThe Kullback Leibler Divergence (KLD)\n\\begin{equation}\nKLD = \\int_{-\\infty}^{\\infty} p(z | \\vec{d}) \\log\\left[\\frac{p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)}{p(z | \\vec{d})}\\right] dz\n\\end{equation}\nis a directional measure of how much information is lost by using the estimated $p(z | \\vec{d}, \\{z_{n}, \\vec{d}_{n}\\}_{N}, \\pi)$ instead of the true $p(z | \\vec{d})$.\nWe want the KLD for each galaxy to be low.\n\n\n```python\nKLDs = np.array([qp.metrics.quick_kld(p, q, dx=np.mean(grid[1:] - grid[:-1])) for p, q in zip(posteriors_test, approx_pdf_on_grid)])\nKLDs_bias = np.array([qp.metrics.quick_kld(p, q, dx=np.mean(grid[1:] - grid[:-1])) for p, q in zip(posteriors_test, approx_pdf_on_grid_bias)])\n\nplt.hist(np.log(KLDs), alpha=0.5, bins=100, label='representative', density=True)\nplt.hist(np.log(KLDs_bias), alpha=0.5, bins=100, label='biased', density=True)\nplt.xlabel('KLD')\nplt.legend()\nplt.semilogy()\n```\n\nThe root-mean-square-error (RMSE) is a symmetric measure commonly used to compare 1D functions.\n**TODO: write it out?** Similarly, a lower value corresponds to a more closely approximating posterior PDF.\n\n\n```python\nRMSEs = np.array([qp.metrics.quick_rmse(p, q, N=granularity) for p, q in zip(posteriors_test, approx_pdf_on_grid)])\nRMSEs_bias = np.array([qp.metrics.quick_rmse(p, q, N=granularity) for p, q in zip(posteriors_test, approx_pdf_on_grid_bias)])\n\nplt.hist(np.log(RMSEs), alpha=0.5, bins=100, label='representative', density=True)\nplt.hist(np.log(RMSEs_bias), alpha=0.5, bins=100, label='biased', density=True)\nplt.xlabel('RMSE')\nplt.legend()\n```\n\n### Your turn!\n\nHow else can we quantify the performance of estimators of aleatoric uncertainty?\n\n**CHALLENGE**: Apply and visualize the local metrics of [Zhao, Dalmasso, Izbicki & Lee, 2021](https://arxiv.org/abs/2102.10473), or any other metrics not included in this demo; the [cde-diagnostics tutorial](https://github.com/zhao-david/CDE-diagnostics/blob/main/tutorial/tutorial-cde-diagnostics.ipynb), written by David Zhao (CMU), may be a good starting point.\n\n**CHALLENGE**: Use the differences between estimated and true photo-$z$ posterior PDFs as a function of photometry to isolate the implicit prior of epistemic uncertainty from the aleatoric uncertainty.\n\n# Your turn: How to participate in this challenge tl;dr\n\nThe organizers have identified three hack-able aspects to this data challenge:\n- Quantify sensitivity of ML photo-z posterior estimators to training set non-representativity\n- Implement and test additional AI methods for photo-z posterior estimation\n- Implement/interpret additional metrics of posterior precision\n\nOf course, there are many other possibilities for what to investigate based on this starting material!\n\nTo participate, clone this tutorial's [GitHub repo](https://github.com/aimalz/qtc2021), make or comment on [an issue](https://github.com/aimalz/qtc2021/issues) saying what you'd like to hack on, and work in a branch corresponding to that issue.\nThe only rule is that if your hack leads to a publication, you cite the repo (and, of course, invite those who contributed to your solution to be authors).\n\n\n```python\n\n```\n", "meta": {"hexsha": "6d8f6bed26eaf698f95d83524e382e2a6ec7a8da", "size": 51982, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "intro.ipynb", "max_stars_repo_name": "biprateep/qtc2021", "max_stars_repo_head_hexsha": "2cf09c39bb6a3393b9c9a95f6f064c25d0c94fef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "intro.ipynb", "max_issues_repo_name": "biprateep/qtc2021", "max_issues_repo_head_hexsha": "2cf09c39bb6a3393b9c9a95f6f064c25d0c94fef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intro.ipynb", "max_forks_repo_name": "biprateep/qtc2021", "max_forks_repo_head_hexsha": "2cf09c39bb6a3393b9c9a95f6f064c25d0c94fef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.65064836, "max_line_length": 477, "alphanum_fraction": 0.6157900812, "converted": true, "num_tokens": 9663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.325509124817436}} {"text": "```python\n# This cell is added by sphinx-gallery\n!pip install mrsimulator --quiet\n\n\n%matplotlib inline\n\nimport mrsimulator\nprint(f'You are using mrsimulator v{mrsimulator.__version__}')\n```\n\n\n# Writing Custom methods (HahnEcho)\n\nWriting custom methods using the Event objects.\n\n\nImport the relevant modules\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom mrsimulator import Simulator, SpinSystem, Site, Coupling\nfrom mrsimulator.methods import Method1D\nfrom mrsimulator.method.event import MixingEvent, SpectralEvent\n```\n\nFor demonstration, we will create two spin systems, one with a single site and other\nwith two spin 1/2 sites.\n\n\n\n\n```python\nS1 = Site(\n isotope=\"1H\",\n isotropic_chemical_shift=10, # in ppm\n shielding_symmetric={\"zeta\": -80, \"eta\": 0.25}, # zeta in ppm\n)\nS2 = Site(isotope=\"1H\", isotropic_chemical_shift=-10)\nS12 = Coupling(\n site_index=[0, 1], isotropic_j=100, dipolar={\"D\": 2000, \"eta\": 0, \"alpha\": 0}\n)\n\nspin_system_1 = SpinSystem(sites=[S1], label=\"Uncoupled system\")\nspin_system_2 = SpinSystem(sites=[S1, S2], couplings=[S12], label=\"Coupled system\")\n```\n\n**Create a custom method**\n\nWriting a custom method is simply specifying an appropriate list of event objects per\nspectral dimension. In this example, we are interested in a one-dimensional Hahnecho\nmethod, and we use the generic `Method1D` class as a template. For a Hahnecho, we will\nuse two types of Event objects---SpectralEvent and MixingEvent.\n\nA SpectralEvent object is where we sample the frequency contributions. The net\nfrequency along a given spectral dimension is a weighted average of the frequencies\nfrom all SpectralEvent objects within a given SpectralDimension, i.e.,\n\n\\begin{align}f = \\sum_j w_j \\times \\nu_j,\\end{align}\n\nwhere $f$ is the net averaged frequency along a spectral dimension, $w_j$\nis the weight (the attribute ``fraction``), and $\\nu_j$ is the frequency from\nthe $j^\\text{th}$ SpectralEvent. The index $j$ runs over all spectral\nevents within a spectral dimension.\n\nIn the case of a one-dimensional Hahnecho method, the frequency is equally averaged\nover two spectral events, corresponding to the symmetry pathway,\n\n\\begin{align}p = 1 \\rightarrow -1.\\end{align}\n\nIn the following code, we define the two SpectralEvent objects with fraction 0.5 and\nthe transition_query on channel-1 of P=[1] and P=[-1], respectively. Notice, the value\nfor the ``P`` attribute is a list. Here, it is a list with a single integer. The list\nnotation, ``[1]``, implies that the query selects all transitions where exactly one\nspin is undergoing a $p=+1$ transition with the remaining spin at $p=0$.\nA similar argument holds for ``[-1]`` query. By implementing query objects, we\ndecouple the method from the spin system, i.e., once a method is defined, it can be\nused to simulate spectra from any given spin system. We will demonstrate this\nmomentarily by simulating a Hahnecho spectrum from single and two-site spin systems.\n\nBesides the SpectralEvent, you may also notice a MixingEvent sandwitched in-between\nthe two SpectralEvent. A MixingEvent does not directly contribute to the frequencies.\nAs the name suggests, a mixing event is used for the mixing of transitions in a\nmulti-event method such as HahnEcho. In the following code, we define a mixing query\non channel-1 by setting the attributes ``tip_angle`` and ``phase`` to $\\pi$ and\n0, respectively. There two parameters are analogous to the pulse angle and phase.\n\n\n\n\n```python\nhahn_echo = Method1D(\n channels=[\"1H\"],\n magnetic_flux_density=9.4, # in T\n spectral_dimensions=[\n {\n \"count\": 512,\n \"spectral_width\": 2e4, # in Hz\n \"events\": [\n SpectralEvent(fraction=0.5, transition_query=[{\"ch1\": {\"P\": [1]}}]),\n MixingEvent(mixing_query={\"ch1\": {\"tip_angle\": np.pi, \"phase\": 0}}),\n SpectralEvent(fraction=0.5, transition_query=[{\"ch1\": {\"P\": [-1]}}]),\n ],\n }\n ],\n)\n```\n\nYou may also visualize the method using the `plot` function.\nhahn_echo.plot()\n\n\n\nAs mentioned before, a method object is decoupled from the spin system object. Notice,\nwhen we get the transition pathways from this method for a single-site spin system, we\nget a single transition pathway.\n\n\n\n\n```python\nprint(hahn_echo.get_transition_pathways(spin_system_1))\n```\n\nIn the case of a homonuclear two-site spin 1/2 spin system, the same method returns\nfour transition pathways.\n\n\n\n\n```python\nprint(hahn_echo.get_transition_pathways(spin_system_2))\n```\n\nCreate the Simulator object, add the method and spin system objects, and run the\nsimulation.\n\n\n\n\n```python\nsim = Simulator()\nsim.spin_systems = [spin_system_1, spin_system_2] # add the spin systems\nsim.methods = [hahn_echo] # add the method\nsim.config.decompose_spectrum = \"spin_system\"\n\nsim.run()\n```\n\nThe simulation from each spin system is stored as a dependent variable within the\nCSDM object. Use the `split` function to split the list of the dependent variables\ninto a list of CSDM objects.\n\n\n\n\n```python\nsimulation_results = sim.methods[0].simulation.split()\n\n# The plot of the two simulations.\nfig, ax = plt.subplots(1, 2, figsize=(8.0, 3.0), subplot_kw={\"projection\": \"csdm\"})\nfor i in range(2):\n ax[i].plot(simulation_results[i].real, color=\"black\", linewidth=1)\n ax[i].invert_xaxis()\nplt.tight_layout()\nplt.show()\n```\n\nNotice, in the single-site spin system, the hahn echo refocuses the isotropic chemical\nshits and chemical shift anisotropies. The end result is a resonance at zero\nfrequency. In the case of the two homonuclear spin 1/2 coupled spin system, the Hahn\necho refocuses the isotropic chemical shits and chemical shift anisotropies, but not\nthe dipolar and `J` couplings.\n\n\n", "meta": {"hexsha": "eb8dabe9146adbfb729c7d02c5608691ad541fb0", "size": 8761, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/notebooks/examples/1D_simulation(crystalline)/plot_9_custom_method_Hahnecho.ipynb", "max_stars_repo_name": "pjgrandinetti/mrsimulator", "max_stars_repo_head_hexsha": "e603395e52ad162d4a9051a0741651c9030c3459", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14, "max_stars_repo_stars_event_min_datetime": "2019-05-28T20:06:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-27T01:37:16.000Z", "max_issues_repo_path": "docs/notebooks/examples/1D_simulation(crystalline)/plot_9_custom_method_Hahnecho.ipynb", "max_issues_repo_name": "pjgrandinetti/mrsimulator", "max_issues_repo_head_hexsha": "e603395e52ad162d4a9051a0741651c9030c3459", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74, "max_issues_repo_issues_event_min_datetime": "2021-06-07T15:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:09:19.000Z", "max_forks_repo_path": "docs/notebooks/examples/1D_simulation(crystalline)/plot_9_custom_method_Hahnecho.ipynb", "max_forks_repo_name": "pjgrandinetti/mrsimulator", "max_forks_repo_head_hexsha": "e603395e52ad162d4a9051a0741651c9030c3459", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-05-28T20:19:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T18:48:24.000Z", "avg_line_length": 47.8743169399, "max_line_length": 2397, "alphanum_fraction": 0.6141992923, "converted": true, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.325509124817436}} {"text": "```python\nfrom IPython.display import Image\n```\n\n# CNTK 203: Reinforcement Learning Basics\n\n\nReinforcement learning (RL) is an area of machine learning inspired by behaviorist psychology, concerned with how [software agents](https://en.wikipedia.org/wiki/Software_agent) ought to take [actions](https://en.wikipedia.org/wiki/Action_selection) in an environment so as to maximize some notion of cumulative reward. In machine learning, the environment is typically formulated as a [Markov decision process](https://en.wikipedia.org/wiki/Markov_decision_process) (MDP) as many reinforcement learning algorithms for this context utilize [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) techniques.\n\nIn some machine learning settings, we do not have immediate access to labels, so we cannot rely on supervised learning techniques. If, however, there is something we can interact with and thereby get some feedback that tells us occasionally, whether our previous behavior was good or not, we can use RL to learn how to improve our behavior.\n\nUnlike in supervised learning, in RL, labeled correct input/output pairs are never presented and sub-optimal actions are never explicitly corrected. This mimics many of the online learning paradigms which involves finding a balance between exploration (of conditions or actions never learnt before) and exploitation (of already learnt conditions or actions from previous encounters). Multi-arm bandit problems is one of the category of RL algorithms where exploration vs. exploitation trade-off have been thoroughly studied. See figure below for [reference](http://www.simongrant.org/pubs/thesis/3/2.html).\n\n\n```python\n# Figure 1\nImage(url=\"https://cntk.ai/jup/polecart.gif\", width=300, height=300)\n```\n\n\n\n\n\n\n\n\n**Problem**\n\nWe will use the [CartPole](https://gym.openai.com/envs/CartPole-v0) environment from OpenAI's [gym](https://github.com/openai/gym) simulator to teach a cart to balance a pole. As described in the link above, in the CartPole example, a pole is attached by an un-actuated joint to a cart, which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. See figure below for reference.\n\n**Goal**\nOur goal is to prevent the pole from falling over as the cart moves with the pole in upright position (perpendicular to the cart) as the starting state. More specifically if the pole is less than 15 degrees from vertical while the cart is within 2.4 units of the center we will collect reward. In this tutorial, we will train till we learn a set of actions (policies) that lead to an average reward of 200 or more over last 50 batches.\n\nIn, RL terminology, the goal is to find _policies_ $a$, that maximize the _reward_ $r$ (feedback) through interaction with some environment (in this case the pole being balanced on the cart). So given a series of experiences $$s \\xrightarrow{a} r, s'$$ we then can learn how to choose action $a$ in a given state $s$ to maximize the accumulated reward $r$ over time:\n\\begin{align}\nQ(s,a) &= r_0 + \\gamma r_1 + \\gamma^2 r_2 + \\ldots \\newline\n&= r_0 + \\gamma \\max_a Q^*(s',a)\n\\end{align}\nwhere $\\gamma \\in [0,1)$ is the discount factor that controls how much we should value reward that is further away. This is called the [*Bellmann*-equation](https://en.wikipedia.org/wiki/Bellman_equation).\n\nIn this tutorial we will show how to model the state space, how to use the received reward to figure out which action yields the highest future reward.\n\nWe present two different popular approaches here:\n\n**Deep Q-Networks**: DQNs have become famous in 2015 when they were successfully used to train how to play Atari just form raw pixels. We train neural network to learn the $Q(s,a)$ values (thus _Q-Network _). From these $Q$ functions values we choose the best action.\n\n**Policy gradient**: This method directly estimates the policy (set of actions) in the network. The outcome is a learning of an ordered set of actions which leads to maximize reward by probabilistically choosing a subset of actions. In this tutorial, we learn the actions using a gradient descent approach to learn the policies.\n\nIn this tutorial, we focus how to implement RL in CNTK. We choose a straight forward shallow network. One can extend the approaches by replacing our shallow model with deeper networks that are introduced in other CNTK tutorials.\n\nAdditionally, this tutorial is in its early stages and will be evolving in future updates.\n\n## Before we start...\nPlease run the following cell from the menu above or select the cell below and hit `Shift + Enter` to ensure the environment is ready. Verify that the following imports work in your notebook.\n\n\n```python\nfrom __future__ import print_function\nfrom __future__ import division\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\nstyle.use('ggplot')\n%matplotlib inline\n```\n\nWe use the following construct to install the OpenAI gym package if it is not installed. For users new to Jupyter environment, this construct can be used to install any python package. \n\n\n```python\ntry:\n import gym\nexcept:\n !pip install gym\n import gym\n```\n\n### Select the notebook run mode\n\nThere are two run modes:\n- *Fast mode*: `isFast` is set to `True`. This is the default mode for the notebooks, which means we train for fewer iterations or train / test on limited data. This ensures functional correctness of the notebook though the models produced are far from what a completed training would produce.\n\n- *Slow mode*: We recommend the user to set this flag to `False` once the user has gained familiarity with the notebook content and wants to gain insight from running the notebooks for a longer period with different parameters for training. \n\n\n```python\nisFast = True\n```\n\n# CartPole: Data and Environment\n\nWe will use the [CartPole](https://gym.openai.com/envs/CartPole-v0) environment from OpenAI's [gym](https://github.com/openai/gym) simulator to teach a cart to balance a pole. Please follow the links to get more details.\n\nIn every time step, the agent\n * gets an observation $(x, \\dot{x}, \\theta, \\dot{\\theta})$, corresponding to *cart position*, *cart velocity*, *pole angle with the vertical*, *pole angular velocity*,\n * performs an action `LEFT` or `RIGHT`, and\n * receives\n * a reward of +1 for having survived another time step, and\n * a new state $(x', \\dot{x}', \\theta', \\dot{\\theta}')$\n\nThe episode ends, if\n * the pole is more than 15 degrees from vertical and/or\n * the cart is moving more than 2.4 units from center.\n\nThe task is considered done, if\n * the agent achieved and averaged reward of 200 over the last 50 episodes (if you manage to get a reward of 200 averaged over the last 100 episode you can consider submitting it to OpenAI).\n\nIn fast mode these targets are relaxed.\n\n# Part 1: DQN\n\nAfter a transition $(s,a,r,s')$, we are trying to move our value function $Q(s,a)$ closer to our target $r+\\gamma \\max_{a'}Q(s',a')$, where $\\gamma$ is a discount factor for future rewards and ranges in value between 0 and 1.\n\nDQNs\n * learn the _Q-function_ that maps observation (state, action) to a `score`\n * use memory replay (previously recorded $Q$ values corresponding to different $(s,a)$ to decorrelate experiences (sequence state transitions)\n * use a second network to stabilize learning (*not* part of this tutorial)\n\n### Setting up the model\n\\begin{equation}\nl_1 = relu( x W_1 + b_1) \\\\\nQ(s,a) = l_1 W_2 + b_2 \\\\\n\\end{equation}\n\nWe will start with a slightly modified version for Keras, https://github.com/jaara/AI-blog/blob/master/CartPole-basic.py, published by Jaromír Janisch in his [AI blog](https://jaromiru.com/2016/09/27/lets-make-a-dqn-theory/), and will then incrementally convert it to use CNTK.\n\nWe use a simple two-layer densely connected network, for simpler illustrations. More advance networks can be substituted.\n\n**CNTK** concepts: The commented out code is meant to be an illustration of the similarity of concepts between CNTK API/abstractions against Keras. \n\n\n```python\nimport numpy\nimport math \nimport os \nimport random\n\nimport cntk as C\n```\n\nIn the block below, we check if we are running this notebook in the CNTK internal test machines by looking for environment variables defined there. We then select the right target device (GPU vs CPU) to test this notebook. In other cases, we use CNTK's default policy to use the best available device (GPU, if available, else CPU).\n\n\n```python\n# Select the right target device when this notebook is being tested:\nif 'TEST_DEVICE' in os.environ:\n if os.environ['TEST_DEVICE'] == 'cpu':\n C.device.try_set_default_device(C.device.cpu())\n else:\n C.device.try_set_default_device(C.device.gpu(0))\n```\n\nSTATE_COUNT = 4 (corresponding to $(x, \\dot{x}, \\theta, \\dot{\\theta})$),\n\nACTION_COUNT = 2 (corresponding to `LEFT` or `RIGHT`)\n\n\n```python\nenv = gym.make('CartPole-v0')\n\nSTATE_COUNT = env.observation_space.shape[0]\nACTION_COUNT = env.action_space.n\n\nSTATE_COUNT, ACTION_COUNT\n```\n\n [2017-05-16 20:19:32,618] Making new env: CartPole-v0\n\n\n\n\n\n (4, 2)\n\n\n\nNote: in the cell below we highlight how one would do it in Keras. And a marked similarity with CNTK. While CNTK allows for more compact representation, we present a slightly verbose illustration for ease of learning.\n\nAdditionally, you will note that, CNTK model doesn't need to be compiled explicitly and is implicitly done when data is processed during training.\n\nCNTK effectively uses available memory on the system between minibatch execution. Thus the learning rates are stated as **rates per sample** instead of **rates per minibatch** (as with other toolkits).\n\n\n```python\n# Targetted reward\nREWARD_TARGET = 30 if isFast else 200\n# Averaged over these these many episodes\nBATCH_SIZE_BASELINE = 20 if isFast else 50\n\nH = 64 # hidden layer size\n\nclass Brain:\n def __init__(self):\n self.params = {}\n self.model, self.trainer, self.loss = self._create()\n # self.model.load_weights(\"cartpole-basic.h5\")\n\n def _create(self):\n observation = C.sequence.input_variable(STATE_COUNT, np.float32, name=\"s\")\n q_target = C.sequence.input_variable(ACTION_COUNT, np.float32, name=\"q\")\n\n # Following a style similar to Keras\n l1 = C.layers.Dense(H, activation=C.relu)\n l2 = C.layers.Dense(ACTION_COUNT)\n unbound_model = C.layers.Sequential([l1, l2])\n model = unbound_model(observation)\n\n self.params = dict(W1=l1.W, b1=l1.b, W2=l2.W, b2=l2.b)\n\n # loss='mse'\n loss = C.reduce_mean(C.square(model - q_target), axis=0)\n meas = C.reduce_mean(C.square(model - q_target), axis=0)\n\n # optimizer\n lr = 0.00025\n lr_schedule = C.learning_rate_schedule(lr, C.UnitType.minibatch)\n learner = C.sgd(model.parameters, lr_schedule, gradient_clipping_threshold_per_sample=10)\n trainer = C.Trainer(model, (loss, meas), learner)\n\n # CNTK: return trainer and loss as well\n return model, trainer, loss\n\n def train(self, x, y, epoch=1, verbose=0):\n #self.model.fit(x, y, batch_size=64, nb_epoch=epoch, verbose=verbose)\n arguments = dict(zip(self.loss.arguments, [x,y]))\n updated, results =self.trainer.train_minibatch(arguments, outputs=[self.loss.output])\n\n def predict(self, s):\n return self.model.eval([s])\n```\n\nThe `Memory` class stores the different states, actions and rewards.\n\n\n```python\nclass Memory: # stored as ( s, a, r, s_ )\n samples = []\n\n def __init__(self, capacity):\n self.capacity = capacity\n\n def add(self, sample):\n self.samples.append(sample)\n\n if len(self.samples) > self.capacity:\n self.samples.pop(0)\n\n def sample(self, n):\n n = min(n, len(self.samples))\n return random.sample(self.samples, n)\n```\n\nThe `Agent` uses the `Brain` and `Memory` to replay the past actions to choose optimal set of actions that maximize the rewards.\n\n\n```python\nMEMORY_CAPACITY = 100000\nBATCH_SIZE = 64\n\nGAMMA = 0.99 # discount factor\n\nMAX_EPSILON = 1\nMIN_EPSILON = 0.01 # stay a bit curious even when getting old\nLAMBDA = 0.0001 # speed of decay\n\nclass Agent:\n steps = 0\n epsilon = MAX_EPSILON\n\n def __init__(self):\n self.brain = Brain()\n self.memory = Memory(MEMORY_CAPACITY)\n\n def act(self, s):\n if random.random() < self.epsilon:\n return random.randint(0, ACTION_COUNT-1)\n else:\n return numpy.argmax(self.brain.predict(s))\n\n def observe(self, sample): # in (s, a, r, s_) format\n self.memory.add(sample)\n\n # slowly decrease Epsilon based on our eperience\n self.steps += 1\n self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps)\n\n def replay(self):\n batch = self.memory.sample(BATCH_SIZE)\n batchLen = len(batch)\n\n no_state = numpy.zeros(STATE_COUNT)\n\n\n # CNTK: explicitly setting to float32\n states = numpy.array([ o[0] for o in batch ], dtype=np.float32)\n states_ = numpy.array([(no_state if o[3] is None else o[3]) for o in batch ], dtype=np.float32)\n\n p = agent.brain.predict(states)\n p_ = agent.brain.predict(states_)\n\n # CNTK: explicitly setting to float32\n x = numpy.zeros((batchLen, STATE_COUNT)).astype(np.float32)\n y = numpy.zeros((batchLen, ACTION_COUNT)).astype(np.float32)\n\n for i in range(batchLen):\n s, a, r, s_ = batch[i]\n\n # CNTK: [0] because of sequence dimension\n t = p[0][i]\n if s_ is None:\n t[a] = r\n else:\n t[a] = r + GAMMA * numpy.amax(p_[0][i])\n\n x[i] = s\n y[i] = t\n\n self.brain.train(x, y)\n```\n\n### Brain surgery\n\nAs any learning experiences, we expect to see the initial state of actions to be wild exploratory and over the iterations the system learns the range of actions that yield longer runs and collect more rewards. The tutorial below implements the [$\\epsilon$-greedy](https://en.wikipedia.org/wiki/Reinforcement_learning) approach. \n\n\n```python\ndef plot_weights(weights, figsize=(7,5)):\n '''Heat map of weights to see which neurons play which role'''\n sns.set(style=\"white\")\n f, ax = plt.subplots(len(weights), figsize=figsize)\n cmap = sns.diverging_palette(220, 10, as_cmap=True)\n \n for i, data in enumerate(weights):\n axi = ax if len(weights)==1 else ax[i]\n if isinstance(data, tuple):\n w, title = data\n axi.set_title(title)\n else:\n w = data\n \n sns.heatmap(w.asarray(), cmap=cmap, square=True, center=True, #annot=True,\n linewidths=.5, cbar_kws={\"shrink\": .25}, ax=axi)\n```\n\n### Exploration - exploitation trade-off\n\nNote that the initial $\\epsilon$ is set to 1 which implies we are entirely exploring but as steps increase we reduce exploration and start leveraging the learnt space to collect rewards (a.k.a. exploitation) as well.\n\n\n```python\ndef epsilon(steps):\n return MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * np.exp(-LAMBDA * steps)\nplt.plot(range(10000), [epsilon(x) for x in range(10000)], 'r')\nplt.xlabel('step');plt.ylabel('$\\epsilon$')\n```\n\nWe are now ready to train our agent using **DQN**. Note this would take anywhere between 2-10 min and we stop whenever the learner hits the average reward of 200 over past 50 batches. One would get better results if they could train the learner until say one hits a reward of 200 or higher for say larger number of runs. This is left as an exercise.\n\n\n```python\nTOTAL_EPISODES = 2000 if isFast else 3000\n\ndef run(agent):\n s = env.reset()\n R = 0\n\n while True:\n # Uncomment the line below to visualize the cartpole\n # env.render()\n\n # CNTK: explicitly setting to float32\n a = agent.act(s.astype(np.float32))\n\n s_, r, done, info = env.step(a)\n\n if done: # terminal state\n s_ = None\n\n agent.observe((s, a, r, s_))\n agent.replay()\n\n s = s_\n R += r\n\n if done:\n return R\n\nagent = Agent()\n\nepisode_number = 0\nreward_sum = 0\nwhile episode_number < TOTAL_EPISODES:\n reward_sum += run(agent)\n episode_number += 1\n if episode_number % BATCH_SIZE_BASELINE == 0:\n print('Episode: %d, Average reward for episode %f.' % (episode_number,\n reward_sum / BATCH_SIZE_BASELINE))\n if episode_number%200==0:\n plot_weights([(agent.brain.params['W1'], 'Episode %i $W_1$'%episode_number)], figsize=(14,5))\n if reward_sum / BATCH_SIZE_BASELINE > REWARD_TARGET:\n print('Task solved in %d episodes' % episode_number)\n plot_weights([(agent.brain.params['W1'], 'Episode %i $W_1$'%episode_number)], figsize=(14,5))\n break\n reward_sum = 0\nagent.brain.model.save('dqn.mod')\n```\n\nIf you run it, you should see something like\n```\nEpisode: 20, Average reward for episode 20.700000.\nEpisode: 40, Average reward for episode 20.150000.\nEpisode: 60, Average reward for episode 21.100000.\n...\nEpisode: 960, Average reward for episode 20.150000.\nEpisode: 980, Average reward for episode 26.700000.\nEpisode: 1000, Average reward for episode 32.900000.\nTask solved in 1000 episodes\n```\n\n#### Task 1.1\nRewrite the model without using the layer lib.\n#### Task 1.2\nPlay with different [learners](https://cntk.ai/pythondocs/cntk.learner.html#module-cntk.learner). Which one works better? Worse? Think about which parameters you would need to adapt when switching from one learner to the other.\n\n### Running the DQN model\n\n\n```python\nenv = gym.make('CartPole-v0')\n\nnum_episodes = 10 # number of episodes to run\n\nmodelPath = 'dqn.mod'\nroot = C.load_model(modelPath)\n\nfor i_episode in range(num_episodes):\n print(i_episode)\n observation = env.reset() # reset environment for new episode\n done = False\n while not done: \n if not 'TEST_DEVICE' in os.environ:\n env.render()\n action = np.argmax(root.eval([observation.astype(np.float32)]))\n observation, reward, done, info = env.step(action) \n```\n\n [2017-05-16 20:21:24,188] Making new env: CartPole-v0\n\n\n 0\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n\n\n# Part 2: Policy gradient\n**Goal:**\n\\begin{equation}\\text{maximize } E [R | \\pi_\\theta]\n\\end{equation}\n\n**Approach:**\n1. Collect experience (sample a bunch of trajectories through $(s,a)$ space)\n2. Update the policy so that _good_ experiences become more probable\n\n**Difference to DQN: **\n * we don't consider single $(s,a,r,s')$ transitions, but rather use whole episodes for the gradient updates\n * our parameters directly model the policy (output is an action probability), whereas in DQN they model the value function (output is raw score)\n\n#### Rewards:\nRemember, we get +1 reward for every time step, in which we still were in the game.\n\nThe problem: we normally do not know, which action led to a continuation of the game, and which was actually a bad one. Our simple heuristic: actions in the beginning of the episode are good, and those towards the end are likely bad (they led to losing the game after all).\n\n\n```python\ndef discount_rewards(r, gamma=0.999):\n \"\"\"Take 1D float array of rewards and compute discounted reward \"\"\"\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, r.size)):\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n```\n\n\n```python\ndiscounted_epr = discount_rewards(np.ones(10))\nf, ax = plt.subplots(1, figsize=(5,2))\nsns.barplot(list(range(10)), discounted_epr, color=\"steelblue\")\n```\n\nWe normalize the rewards so that they tank below zero towards the end. gamma controls how late the rewards tank.\n\n\n```python\ndiscounted_epr_cent = discounted_epr - np.mean(discounted_epr)\ndiscounted_epr_norm = discounted_epr_cent/np.std(discounted_epr_cent)\nf, ax = plt.subplots(1, figsize=(5,2))\nsns.barplot(list(range(10)), discounted_epr_norm, color=\"steelblue\")\n```\n\n\n```python\ndiscounted_epr = discount_rewards(np.ones(10), gamma=0.5)\ndiscounted_epr_cent = discounted_epr - np.mean(discounted_epr)\ndiscounted_epr_norm = discounted_epr_cent/np.std(discounted_epr_cent)\nf, ax = plt.subplots(2, figsize=(5,3))\nsns.barplot(list(range(10)), discounted_epr, color=\"steelblue\", ax=ax[0])\nsns.barplot(list(range(10)), discounted_epr_norm, color=\"steelblue\", ax=ax[1])\n```\n\n### Setting up the model\n\\begin{equation}\nl_1 = relu( x W_1 + b_1) \\\\\nl_2 = l_1 W_2 + b_2 \\\\\n\\pi(a|s) = sigmoid(l_2)\n\\end{equation}\n\nNote: in policy gradient approach, the output of the dense layer is mapped into to a 0-1 range via the sigmoid function.\n\n\n```python\nTOTAL_EPISODES = 2000 if isFast else 10000\n\nD = 4 # input dimensionality\nH = 10 # number of hidden layer neurons\n\nobservations = C.sequence.input_variable(STATE_COUNT, np.float32, name=\"obs\")\n\nW1 = C.parameter(shape=(STATE_COUNT, H), init=C.glorot_uniform(), name=\"W1\")\nb1 = C.parameter(shape=H, name=\"b1\")\nlayer1 = C.relu(C.times(observations, W1) + b1)\n\nW2 = C.parameter(shape=(H, ACTION_COUNT), init=C.glorot_uniform(), name=\"W2\")\nb2 = C.parameter(shape=ACTION_COUNT, name=\"b2\")\nscore = C.times(layer1, W2) + b2\n# Until here it was similar to DQN\n\nprobability = C.sigmoid(score, name=\"prob\")\n```\n\n**Policy Search**: The optimal policy search can be carried out with either gradient free approaches or by computing gradients over the policy space ($\\pi_\\theta$) which is parameterized by $\\theta$. In this tutorial, we use the classic forward (`loss.forward`) and back (`loss.backward`) propagation of errors over the parameterized space $\\theta$. In this case, $\\theta = \\{W_1, b_1, W_2, b_2\\}$, our model parameters. \n\n\n```python\ninput_y = C.sequence.input_variable(1, np.float32, name=\"input_y\")\nadvantages = C.sequence.input_variable(1, np.float32, name=\"advt\")\n\nloss = -C.reduce_mean(C.log(C.square(input_y - probability) + 1e-4) * advantages, axis=0, name='loss')\n\nlr = 0.001\nlr_schedule = C.learning_rate_schedule(lr, C.UnitType.sample)\nsgd = C.sgd([W1, W2], lr_schedule)\n\ngradBuffer = dict((var.name, np.zeros(shape=var.shape)) for var in loss.parameters if var.name in ['W1', 'W2', 'b1', 'b2'])\n\nxs, hs, label, drs = [], [], [], []\nrunning_reward = None\nreward_sum = 0\nepisode_number = 1\n\nobservation = env.reset()\n\nwhile episode_number <= TOTAL_EPISODES:\n x = np.reshape(observation, [1, STATE_COUNT]).astype(np.float32)\n\n # Run the policy network and get an action to take.\n prob = probability.eval(arguments={observations: x})[0][0][0]\n action = 1 if np.random.uniform() < prob else 0\n\n xs.append(x) # observation\n # grad that encourages the action that was taken to be taken\n\n y = 1 if action == 0 else 0 # a \"fake label\"\n label.append(y)\n\n # step the environment and get new measurements\n observation, reward, done, info = env.step(action)\n reward_sum += float(reward)\n\n # Record reward (has to be done after we call step() to get reward for previous action)\n drs.append(float(reward))\n\n if done:\n # Stack together all inputs, hidden states, action gradients, and rewards for this episode\n epx = np.vstack(xs)\n epl = np.vstack(label).astype(np.float32)\n epr = np.vstack(drs).astype(np.float32)\n xs, label, drs = [], [], [] # reset array memory\n\n # Compute the discounted reward backwards through time.\n discounted_epr = discount_rewards(epr)\n # Size the rewards to be unit normal (helps control the gradient estimator variance)\n discounted_epr -= np.mean(discounted_epr)\n discounted_epr /= np.std(discounted_epr)\n\n # Forward pass\n arguments = {observations: epx, input_y: epl, advantages: discounted_epr}\n state, outputs_map = loss.forward(arguments, outputs=loss.outputs,\n keep_for_backward=loss.outputs)\n\n # Backward psas\n root_gradients = {v: np.ones_like(o) for v, o in outputs_map.items()}\n vargrads_map = loss.backward(state, root_gradients, variables=set([W1, W2]))\n\n for var, grad in vargrads_map.items():\n gradBuffer[var.name] += grad\n\n # Wait for some batches to finish to reduce noise\n if episode_number % BATCH_SIZE_BASELINE == 0:\n grads = {W1: gradBuffer['W1'].astype(np.float32),\n W2: gradBuffer['W2'].astype(np.float32)}\n updated = sgd.update(grads, BATCH_SIZE_BASELINE)\n\n # reset the gradBuffer\n gradBuffer = dict((var.name, np.zeros(shape=var.shape))\n for var in loss.parameters if var.name in ['W1', 'W2', 'b1', 'b2'])\n\n print('Episode: %d. Average reward for episode %f.' % (episode_number, reward_sum / BATCH_SIZE_BASELINE))\n\n if reward_sum / BATCH_SIZE_BASELINE > REWARD_TARGET:\n print('Task solved in: %d ' % episode_number)\n break\n\n reward_sum = 0\n\n observation = env.reset() # reset env\n episode_number += 1\nprobability.save('pg.mod')\n```\n\n Episode: 20. Average reward for episode 21.800000.\n Episode: 40. Average reward for episode 23.450000.\n Episode: 60. Average reward for episode 20.650000.\n Episode: 80. Average reward for episode 23.900000.\n Episode: 100. Average reward for episode 17.750000.\n Episode: 120. Average reward for episode 27.550000.\n Episode: 140. Average reward for episode 20.300000.\n Episode: 160. Average reward for episode 20.450000.\n Episode: 180. Average reward for episode 14.700000.\n Episode: 200. Average reward for episode 18.900000.\n Episode: 220. Average reward for episode 18.350000.\n Episode: 240. Average reward for episode 20.050000.\n Episode: 260. Average reward for episode 19.600000.\n Episode: 280. Average reward for episode 22.150000.\n Episode: 300. Average reward for episode 16.000000.\n Episode: 320. Average reward for episode 21.300000.\n Episode: 340. Average reward for episode 19.250000.\n Episode: 360. Average reward for episode 17.550000.\n Episode: 380. Average reward for episode 20.050000.\n Episode: 400. Average reward for episode 20.250000.\n Episode: 420. Average reward for episode 20.200000.\n Episode: 440. Average reward for episode 21.100000.\n Episode: 460. Average reward for episode 23.400000.\n Episode: 480. Average reward for episode 20.100000.\n Episode: 500. Average reward for episode 18.400000.\n Episode: 520. Average reward for episode 15.550000.\n Episode: 540. Average reward for episode 16.850000.\n Episode: 560. Average reward for episode 18.000000.\n Episode: 580. Average reward for episode 23.650000.\n Episode: 600. Average reward for episode 16.550000.\n Episode: 620. Average reward for episode 21.200000.\n Episode: 640. Average reward for episode 19.100000.\n Episode: 660. Average reward for episode 25.150000.\n Episode: 680. Average reward for episode 22.400000.\n Episode: 700. Average reward for episode 19.150000.\n Episode: 720. Average reward for episode 19.900000.\n Episode: 740. Average reward for episode 26.500000.\n Episode: 760. Average reward for episode 20.500000.\n Episode: 780. Average reward for episode 19.300000.\n Episode: 800. Average reward for episode 21.250000.\n Episode: 820. Average reward for episode 27.900000.\n Episode: 840. Average reward for episode 25.600000.\n Episode: 860. Average reward for episode 27.250000.\n Episode: 880. Average reward for episode 27.000000.\n Episode: 900. Average reward for episode 29.900000.\n Episode: 920. Average reward for episode 28.900000.\n Episode: 940. Average reward for episode 30.200000.\n Task solved in: 940 \n\n\n# Solutions\n#### Solution 1.1\n\n\n```python\nobservation = C.sequence.input_variable(STATE_COUNT, np.float32, name=\"s\")\n\nW1 = C.parameter(shape=(STATE_COUNT, H), init=C.glorot_uniform(), name=\"W1\")\nb1 = C.parameter(shape=H, name=\"b1\")\nlayer1 = C.relu(C.times(observation, W1) + b1)\n\nW2 = C.parameter(shape=(H, ACTION_COUNT), init=C.glorot_uniform(), name=\"W2\")\nb2 = C.parameter(shape=ACTION_COUNT, name=\"b2\")\nmodel = C.times(layer1, W2) + b2\nW1.shape, b1.shape, W2.shape, b2.shape, model.shape\n```\n\n\n\n\n ((4, 10), (10,), (10, 2), (2,), (2,))\n\n\n\n\n```python\n# Correspoding layers implementation - Preferred solution\ndef create_model(input):\n with C.layers.default_options(init=C.glorot_uniform()):\n z = C.layers.Sequential([C.layers.Dense(H, name=\"layer1\"),\n C.layers.Dense(ACTION_COUNT, name=\"layer2\")])\n return z(input)\n \nmodel = create_model(observation)\n\nmodel.layer1.W.shape, model.layer1.b.shape, model.layer2.W.shape, model.layer2.b.shape, model.shape\n```\n\n\n\n\n ((4, 10), (10,), (10, 2), (2,), (2,))\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "c7ef39fe0cc7a947569acfbddb09888dc909af98", "size": 170114, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Tutorials/CNTK_203_Reinforcement_Learning_Basics.ipynb", "max_stars_repo_name": "rickyHong/MS-CNTK", "max_stars_repo_head_hexsha": "2bcdc9dff6dc6393813f6043d80e167fb31aed72", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-11-10T18:05:58.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T18:05:58.000Z", "max_issues_repo_path": "Tutorials/CNTK_203_Reinforcement_Learning_Basics.ipynb", "max_issues_repo_name": "rickyHong/MS-CNTK", "max_issues_repo_head_hexsha": "2bcdc9dff6dc6393813f6043d80e167fb31aed72", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tutorials/CNTK_203_Reinforcement_Learning_Basics.ipynb", "max_forks_repo_name": "rickyHong/MS-CNTK", "max_forks_repo_head_hexsha": "2bcdc9dff6dc6393813f6043d80e167fb31aed72", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-11-07T23:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-07T23:05:19.000Z", "avg_line_length": 133.6323644933, "max_line_length": 14806, "alphanum_fraction": 0.8525929671, "converted": true, "num_tokens": 7465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3255091171329785}} {"text": "```R\n# Part of Bootstraping\n## loading the data\nlibrary(boot)\nPenn <- as.data.frame(read.table(\"../data/penn_jae.dat\", header=T ))\nn <- dim(Penn)[1]\np_1 <- dim(Penn)[2]\nPenn<- subset(Penn, tg== 4| tg==0)\nattach(Penn)\n```\n\n The following objects are masked from Penn (pos = 3):\n \n abdt, agegt54, agelt35, black, dep, durable, female, hispanic,\n husd, inuidur1, inuidur2, lusd, muld, nondurable, othrace, q1, q2,\n q3, q4, q5, q6, recall, tg\n \n The following objects are masked from Penn (pos = 5):\n \n abdt, agegt54, agelt35, black, dep, durable, female, hispanic,\n husd, inuidur1, inuidur2, lusd, muld, nondurable, othrace, q1, q2,\n q3, q4, q5, q6, recall, tg\n \n The following objects are masked from Penn (pos = 6):\n \n abdt, agegt54, agelt35, black, dep, durable, female, hispanic,\n husd, inuidur1, inuidur2, lusd, muld, nondurable, othrace, q1, q2,\n q3, q4, q5, q6, recall, tg\n \n The following objects are masked from Penn (pos = 7):\n \n abdt, agegt54, agelt35, black, dep, durable, female, hispanic,\n husd, inuidur1, inuidur2, lusd, muld, nondurable, othrace, q1, q2,\n q3, q4, q5, q6, recall, tg\n \n\n\n\n```R\nlibrary(ISLR2)\nset.seed(1)\nlibrary(boot)\n```\n\n\n```R\nT4<- (tg==4)|\nsummary(T4)\n```\n\n\n```R\n# Here we define the structure of our regression:\nregresion <- log(inuidur1)~T4+ (female+black+othrace+factor(dep)+q2+q3+q4+q5+q6+agelt35+agegt54+durable+lusd+husd\n \n \n```\n\n\n```R\nboot.fn <- function(data, index) {\n coef(lm(log(inuidur1)~T4+ (female+black+othrace+factor(dep)+q2+q3+q4+q5+q6+agelt35+agegt54+durable+lusd+husd), data = data, subset = index)) } \n```\n\n\n```R\n# Finally, here we define our bootstapping proccess: \nexample <- boot(Penn, boot.fn , 1000)\nexample\n\n```\n\n\n \n ORDINARY NONPARAMETRIC BOOTSTRAP\n \n \n Call:\n boot(data = Penn, statistic = boot.fn, R = 1000)\n \n \n Bootstrap Statistics :\n original bias std. error\n t1* 2.178462326 0.0052223099 0.15609830\n t2* -0.071692484 0.0002443722 0.03633901\n t3* 0.126368328 -0.0005970869 0.03548195\n t4* -0.293767980 -0.0023950938 0.05902701\n t5* -0.472445058 -0.0009669991 0.23662611\n t6* 0.029866899 -0.0015803274 0.05316184\n t7* 0.096186517 0.0001454218 0.04751720\n t8* 0.073678072 -0.0047203080 0.15280807\n t9* -0.038506537 -0.0029706659 0.15249683\n t10* -0.054949195 -0.0046900884 0.15342405\n t11* -0.144177912 -0.0042572281 0.15104799\n t12* 0.003361318 -0.0024182498 0.16165529\n t13* -0.162772168 -0.0000218298 0.03768461\n t14* 0.229666708 -0.0001082586 0.05800139\n t15* 0.126557359 -0.0024061924 0.04917096\n t16* -0.175352572 -0.0007373578 0.04123540\n t17* -0.105224727 -0.0003037563 0.04271973\n\n\n\n```R\n# We do this to know which is the orden of our coefficents.\nsummary(lm(name, data = Penn))$coef\n```\n\n\n```R\nplot(example)\n```\n\n# HTE I: Binary treatment\n\n## Analysis\n\n\n```R\ninstall.packages(\"devtools\") # if you don't have this installed yet.\n\n```\n\n\n```R\ndevtools::install_github('susanathey/causalTree')\n```\n\n\n```R\n# The causalTree package is not in CRAN, the most common R repository.\n# To install it, uncomment the next lines as appropriate.\ninstall.packages(\"devtools\") # if you don't have this installed yet.\ndevtools::install_github('susanathey/causalTree') \nlibrary(causalTree)\n\n# use e.g., install.packages(\"grf\") to install any of the following packages.\nlibrary(grf)\nlibrary(rpart)\nlibrary(glmnet)\nlibrary(splines)\nlibrary(MASS)\nlibrary(lmtest)\nlibrary(sandwich)\nlibrary(ggplot2)\n```\n\nAs with other chapters in this tutorial, the code below should still work by replacing the next snippet of code with a different dataset, provided that you update the key variables `treatment`, `outcome`, and `covariates` below. Also, please make sure to read the comments as they may be subtle differences depending on whether your dataset was created in a randomized or observational setting.\n\n\n```R\n# Read in data\ndata <- as.data.frame(read.table(\"../data/penn_jae.dat\", header=T ))\nn <- nrow(data)\ndata<- subset(data, tg== 4| tg==0)\nattach(data)\nT4<- (tg==4)\nsummary(T4)\ntreatment <- \"tg\"\n\noutcome <- \"inuidur1\"\n\n# Additional covariates\ncovariates <- c(\"female\",\"black\",\"othrace\",\"factor\",\"dep\",\"q2\",\"q3\",\"q4\",\"q5\",\"q6\",\"agelt35\",\"agegt54\",\"durable\",\"lusd\",\"husd\")\n```\n\n## Pre-specified hypotheses\n\nWe will begin by learning how to test pre-specified null hypotheses of the form\n\\begin{equation} \n\\label{eq:1}\nH_{0}: E[Y(1) - Y(0) | G_i = 1] = E[Y(1) - Y(0) | G_i = 0] \n\\end{equation}\n\nThat is, that the treatment effect is the same regardless of membership to some group\n$G_i$. Importantly, for now we’ll assume that the group $G_i$ was **pre-specified** -- it was decided _before_ looking at the data.\n\nIn a randomized setting, if the both the treatment $W_i$ and group membership $G_i$ are binary, we can write\n\\begin{equation}\n E[Y_i(W_i)|G_i] = E[Y_i|W_i, G_i] = \\beta_0 + \\beta_w W_i + \\beta_g G_i + \\beta_{wg} W_i G_i\n\\end{equation}\n\n\nWhen $W_i$ and $G_i$ are binary, this decomposition is true without loss of generality. Why?\n\n\nThis allows us to write the average effects of $W_i$ and $G_i$ on $Y_i$ as\n\\begin{equation}\n \\begin{aligned}\n E[Y(1) | G_i=1] &= \\beta_0 + \\beta_w W_i + \\beta_g G_i + \\beta_{wg} W_i G_i, \\\\\n E[Y(1) | G_i=0] &= \\beta_0 + \\beta_w W_i, \\\\\n E[Y(0) | G_i=1] &= \\beta_0 + \\beta_g G_i, \\\\\n E[Y(0) | G_i=0] &= \\beta_0.\n \\end{aligned}\n\\end{equation}\n\nRewriting the null hypothesis \\ref{eq:1} in terms of the decomposition \\@ref(eq:decomp), we see that it boils down to a test about the coefficient in the interaction: $\\beta_{xw} = 0$\n\n\n```R\n# Only valid in randomized settings\n\n# Suppose this his group was defined prior to collecting the data\n# Recall from last chapter -- this is equivalent to running a t-test\nfmla <- log(inuidur1)~T4+ (female+black+othrace+factor(dep)+q2+q3+q4+q5+q6+agelt35+agegt54+durable+lusd+husd)\nols <- lm(fmla, data=data)\ncoeftest(ols, vcov=vcovHC(ols, type='HC2'))\n```\n\n## Data-driven hypotheses\n\nPre-specifying hypotheses prior to looking at the data is in general good practice to avoid \"p-hacking\" (e.g., slicing the data into different subgroups until a significant result is found). However, valid tests can also be attained if by **sample splitting**: we can use a subset of the sample to find promising subgroups, then test hypotheses about these subgroups in the remaining sample. This kind of sample splitting for hypothesis testing is called **honesty**.\n\n### Via causal trees\n\n**Causal trees** [(Athey and Imbens)](PNAS, 2016)](https://www.pnas.org/content/pnas/113/27/7353.full.pdf) are an intuitive algorithm that is available in the randomized setting to discover subgroups with different treatment effects.\n\nAt a high level, the idea is to divide the sample into three subsets (not necessarily of equal size). The `splitting` subset is used to fit a decision tree whose objective is modified to maximize heterogeneity in treatment effect estimates across leaves. The `estimation` subset is then used to produce a valid estimate of the treatment effect at each leaf of the fitted tree. Finally, a `test` subset can be used to validate the tree estimates.\n\nThe next snippet uses `honest.causalTree` function from the [`causalTree`](https://github.com/susanathey/causalTree) package. For more details, see the [causalTree documentation](https://github.com/susanathey/causalTree/blob/master/briefintro.pdf).\n\n\n```R\n# Only valid for randomized data!\nfmla <- paste(outcome, \" ~\", paste(covariates, collapse = \" + \"))\nfmla\n```\n\n\n```R\n# Dividing data into three subsets\nindices <- split(seq(nrow(data)), sort(seq(nrow(data)) %% 3))\nnames(indices) <- c('split', 'est', 'test')\n```\n\n\n```R\n# Fitting the forest\nct.unpruned <- honest.causalTree(\n formula=fmla, # Define the model\n data=data[indices$split,],\n treatment=data[indices$split, treatment],\n est_data=data[indices$est,],\n est_treatment=data[indices$est, treatment],\n minsize=1, # Min. number of treatment and control cases in each leaf\n HonestSampleSize=length(indices$est), # Num obs used in estimation after splitting\n \n # We recommend not changing the parameters below\n split.Rule=\"CT\", # Define the splitting option\n cv.option=\"TOT\", # Cross validation options\n cp=0, # Complexity parameter\n split.Honest=TRUE, # Use honesty when splitting\n cv.Honest=TRUE # Use honesty when performing cross-validation\n)\n```\n\n\n```R\n# Table of cross-validated values by tuning parameter.\nct.cptable <- as.data.frame(ct.unpruned$cptable)\n```\n\n\n```R\n# Obtain optimal complexity parameter to prune tree.\ncp.selected <- which.min(ct.cptable$xerror)\n```\n\n\n```R\ncp.optimal <- ct.cptable[cp.selected, \"CP\"]\n\n# Prune the tree at optimal complexity parameter.\nct.pruned <- prune(tree=ct.unpruned, cp=cp.optimal)\n```\n\n\n```R\n# Predict point estimates (on estimation sample)\ntau.hat.est <- predict(ct.pruned, newdata=data[indices$est,])\n\n# Create a factor column 'leaf' indicating leaf assignment in the estimation set\nnum.leaves <- length(unique(tau.hat.est))\nleaf <- factor(tau.hat.est, levels=sort(unique(tau.hat.est)), labels = seq(num.leaves))\n```\n\nNote: if your tree is not splitting at all, try decreasing the parameter `minsize` that controls the minimum size of each leaf. The next snippet plots the learned tree. The values in the cell are the estimated treatment effect and an estimate of the fraction of the population that falls within each leaf. Both are estimated using the `estimation` sample.\n\n\n```R\nrpart.plot(\n x=ct.pruned, # Pruned tree\n type=3, # Draw separate split labels for the left and right directions\n fallen=TRUE, # Position the leaf nodes at the bottom of the graph\n leaf.round=1, # Rounding of the corners of the leaf node boxes\n extra=100, # Display the percentage of observations in the node\n branch=.1, # Shape of the branch lines\n box.palette=\"RdBu\") # Palette for coloring the node\n```\n\n\nInterpret the heatmap above. What describes the subgroups with strongest and weakest estimated treatment effect?\n\n\n\n### Via grf\n\nThe function `causal_forest` from the package `grf` allows us to get estimates of the CATE \\@ref(eq:cate). \n\n\n```R\n# Get predictions from forest fitted above.\ntau.hat <- predict(forest.tau)$predictions # tau(X) estimates\n```\n\nHaving fit a non-parametric method such as a causal forest, a researcher may (incorrectly) start by looking at the distribution of its predictions of the treatment effect. One might be tempted to think: \"if the histogram is concentrated at a point, then there is no heterogeneity; if the histogram is spread out, then our estimator has found interesting heterogeneity.\" However, this may be false.\n\n\n```R\n# Do not use this for assessing heterogeneity. See text above.\nhist(tau.hat, main=\"CATE estimates\", freq=F)\n```\n\nIf the histogram is concentrated at a point, we may simply be underpowered: our method was not able to detect any heterogeneity, but maybe it would detect it if we had more data. If the histogram is spread out, we may be overfitting: our model is producing very noisy estimates $\\widehat{\\tau}(x)$, but in fact the true $\\tau(x)$ can be much smoother as a function of $x$.\n\nThe `grf` package also produces a measure of variable importance that indicates how often a variable was used in a tree split. Again, much like the histogram above, this can be a rough diagnostic, but it should not be interpreted as indicating that, for example, variable with low importance is not related to heterogeneity. The reasoning is the same as the one presented in the causal trees section: if two covariates are highly correlated, the trees might split on one covariate but not the other, even though both (or maybe neither) are relevant in the true data-generating process.\n\n\n```R\nvar_imp <- c(variable_importance(forest.tau))\nnames(var_imp) <- covariates\nsorted_var_imp <- sort(var_imp, decreasing = TRUE)\nsorted_var_imp[1:5] # showing only first few\n```\n\n#### Data-driven subgroups\n\nJust as with causal trees, we can use causal forests to divide our observations into subgroups. In place of leaves, we'll rank observation into (say) quintiles according to their estimated CATE prediction; see, e.g., [Chernozhukov, Demirer, Duflo, Fernández-Val (2020)](https://arxiv.org/abs/1712.04802) for similar ideas.\n\nThere's a subtle but important point that needs to be addressed here. As we have mentioned before, when predicting the conditional average treatment effect $\\tau(X_i)$ for observation $i$ we should in general avoid using a model that was fitted using observation $i$. This sort of sample splitting (which we called **honesty** above) is one of the required ingredients to get unbiased estimates of the CATE using the methods described here. However, when ranking estimates of two observations $i$ and $j$, we need something a little stronger: we must ensure that the model was not fit using _either_ $i$ _or_ $j$'s data. \n\nOne way of overcoming this obstacle is simple. First, divide the data into $K$ folds (subsets). Then, cycle through the folds, fitting a CATE model on $K-1$ folds. Next, for each held-out fold, _separately_ rank the unseen observations into $Q$ groups based on their prediction (i.e., if $Q=5$, then we rank observations by estimated CATE into \"top quintile\", \"second quintile\", and so on). After concatenating the independent rankings together, we can study the differences in observations in each rank-group. \n\n[This gist](https://gist.github.com/halflearned/bea4e5137c0c81fd18a75f682da466c8) computes the above for `grf`, and it should not be hard to modify it so as to replace forests by any other non-parametric method. However, for `grf` specifically, there's a small trick that allows us to obtain a valid ranking: we can pass a vector of fold indices to the argument `clusters` and rank observations within each fold. This works because estimates for each fold (\"cluster\") trees are computed using trees that were not fit using observations from that fold. Here's how to do it. \n\n\n\n```R\n# Valid randomized data and observational data with unconfoundedness+overlap.\n# Note: read the comments below carefully. \n# In randomized settings, do not estimate forest.e and e.hat; use known assignment probs.\n\n# Prepare dataset\nfmla <- formula(paste0(\"~ 0 + \", paste0(covariates, collapse=\"+\")))\nX <- model.matrix(fmla, data)\nW <- data[,treatment]\nY <- data[,outcome]\n\n# Number of rankings that the predictions will be ranking on \n# (e.g., 2 for above/below median estimated CATE, 5 for estimated CATE quintiles, etc.)\nnum.rankings <- 5 \n\n# Prepare for data.splitting\n# Assign a fold number to each observation.\n# The argument 'clusters' in the next step will mimick K-fold cross-fitting.\nnum.folds <- 10\nfolds <- sort(seq(n) %% num.folds) + 1\n\n# Comment or uncomment depending on your setting.\n# Observational setting with unconfoundedness+overlap (unknown assignment probs):\n# forest <- causal_forest(X, Y, W, clusters = folds)\n# Randomized settings with fixed and known probabilities (here: 0.5).\nforest <- causal_forest(X, Y, W, W.hat=.5, clusters = folds)\n\n# Retrieve out-of-bag predictions.\n# Predictions for observation in fold k will be computed using \n# trees that were not trained using observations for that fold.\ntau.hat <- predict(forest)$predictions\n\n# Rank observations *within each fold* into quintiles according to their CATE predictions.\nranking <- rep(NA, n)\nfor (fold in seq(num.folds)) {\n tau.hat.quantiles <- quantile(tau.hat[folds == fold], probs = seq(0, 1, by=1/num.rankings))\n ranking[folds == fold] <- cut(tau.hat[folds == fold], tau.hat.quantiles, include.lowest=TRUE,labels=seq(num.rankings))\n}\n```\n\nThe next snippet computes the average treatment effect within each group defined above, i.e., $\\E[Y_i(1) - Y_i(0)|G_i = g]$. This can done in two ways. First, by computing a simple difference-in-means estimate of the ATE based on observations within each group. This is valid only in randomized settings.\n\n\n```R\n# Valid only in randomized settings.\n# Average difference-in-means within each ranking\n\n# Formula y ~ 0 + ranking + ranking:w\nfmla <- paste0(outcome, \" ~ 0 + ranking + ranking:\", treatment)\nols.ate <- lm(fmla, data=transform(data, ranking=factor(ranking)))\nols.ate <- coeftest(ols.ate, vcov=vcovHC(ols.ate, type='HC2'))\ninteract <- which(grepl(\":\", rownames(ols.ate)))\nols.ate <- data.frame(\"ols\", paste0(\"Q\", seq(num.rankings)), ols.ate[interact, 1:2])\nrownames(ols.ate) <- NULL # just for display\ncolnames(ols.ate) <- c(\"method\", \"ranking\", \"estimate\", \"std.err\")\nols.ate\n```\n\nAnother option is to average the AIPW scores within each group. This valid for both randomized settings and observational settings with unconfoundedness and overlap. Moreover, AIPW-based estimators should produce estimates with tighter confidence intervals in large samples.\n\n\n```R\n\n```\n\n\n```R\n# HTE I: Binary treatment\n\n## Analysis\n\ninstall.packages(\"devtools\") # if you don't have this installed yet.\n\n\ndevtools::install_github('susanathey/causalTree')\n\n# The causalTree package is not in CRAN, the most common R repository.\n# To install it, uncomment the next lines as appropriate.\ninstall.packages(\"devtools\") # if you don't have this installed yet.\ndevtools::install_github('susanathey/causalTree') \nlibrary(causalTree)\n\n# use e.g., install.packages(\"grf\") to install any of the following packages.\nlibrary(grf)\nlibrary(rpart)\nlibrary(glmnet)\nlibrary(splines)\nlibrary(MASS)\nlibrary(lmtest)\nlibrary(sandwich)\nlibrary(ggplot2)\n\nAs with other chapters in this tutorial, the code below should still work by replacing the next snippet of code with a different dataset, provided that you update the key variables `treatment`, `outcome`, and `covariates` below. Also, please make sure to read the comments as they may be subtle differences depending on whether your dataset was created in a randomized or observational setting.\n\n# Read in data\ndata <- as.data.frame(read.table(\"../data/penn_jae.dat\", header=T ))\nn <- nrow(data)\ndata<- subset(data, tg== 4| tg==0)\nattach(data)\nT4<- (tg==4)\nsummary(T4)\ntreatment <- \"tg\"\n\noutcome <- \"inuidur1\"\n\n# Additional covariates\ncovariates <- c(\"female\",\"black\",\"othrace\",\"factor\",\"dep\",\"q2\",\"q3\",\"q4\",\"q5\",\"q6\",\"agelt35\",\"agegt54\",\"durable\",\"lusd\",\"husd\")\n\n## Pre-specified hypotheses\n\nWe will begin by learning how to test pre-specified null hypotheses of the form\n\\begin{equation} \n\\label{eq:1}\nH_{0}: E[Y(1) - Y(0) | G_i = 1] = E[Y(1) - Y(0) | G_i = 0] \n\\end{equation}\n\nThat is, that the treatment effect is the same regardless of membership to some group\n$G_i$. Importantly, for now we’ll assume that the group $G_i$ was **pre-specified** -- it was decided _before_ looking at the data.\n\nIn a randomized setting, if the both the treatment $W_i$ and group membership $G_i$ are binary, we can write\n\\begin{equation}\n E[Y_i(W_i)|G_i] = E[Y_i|W_i, G_i] = \\beta_0 + \\beta_w W_i + \\beta_g G_i + \\beta_{wg} W_i G_i\n\\end{equation}\n\n\nWhen $W_i$ and $G_i$ are binary, this decomposition is true without loss of generality. Why?\n\n\nThis allows us to write the average effects of $W_i$ and $G_i$ on $Y_i$ as\n\\begin{equation}\n \\begin{aligned}\n E[Y(1) | G_i=1] &= \\beta_0 + \\beta_w W_i + \\beta_g G_i + \\beta_{wg} W_i G_i, \\\\\n E[Y(1) | G_i=0] &= \\beta_0 + \\beta_w W_i, \\\\\n E[Y(0) | G_i=1] &= \\beta_0 + \\beta_g G_i, \\\\\n E[Y(0) | G_i=0] &= \\beta_0.\n \\end{aligned}\n\\end{equation}\n\nRewriting the null hypothesis \\ref{eq:1} in terms of the decomposition \\@ref(eq:decomp), we see that it boils down to a test about the coefficient in the interaction: $\\beta_{xw} = 0$\n\n# Only valid in randomized settings\n\n# Suppose this his group was defined prior to collecting the data\n# Recall from last chapter -- this is equivalent to running a t-test\nfmla <- log(inuidur1)~T4+ (female+black+othrace+factor(dep)+q2+q3+q4+q5+q6+agelt35+agegt54+durable+lusd+husd)\nols <- lm(fmla, data=data)\ncoeftest(ols, vcov=vcovHC(ols, type='HC2'))\n\n## Data-driven hypotheses\n\nPre-specifying hypotheses prior to looking at the data is in general good practice to avoid \"p-hacking\" (e.g., slicing the data into different subgroups until a significant result is found). However, valid tests can also be attained if by **sample splitting**: we can use a subset of the sample to find promising subgroups, then test hypotheses about these subgroups in the remaining sample. This kind of sample splitting for hypothesis testing is called **honesty**.\n\n### Via causal trees\n\n**Causal trees** [(Athey and Imbens)](PNAS, 2016)](https://www.pnas.org/content/pnas/113/27/7353.full.pdf) are an intuitive algorithm that is available in the randomized setting to discover subgroups with different treatment effects.\n\nAt a high level, the idea is to divide the sample into three subsets (not necessarily of equal size). The `splitting` subset is used to fit a decision tree whose objective is modified to maximize heterogeneity in treatment effect estimates across leaves. The `estimation` subset is then used to produce a valid estimate of the treatment effect at each leaf of the fitted tree. Finally, a `test` subset can be used to validate the tree estimates.\n\nThe next snippet uses `honest.causalTree` function from the [`causalTree`](https://github.com/susanathey/causalTree) package. For more details, see the [causalTree documentation](https://github.com/susanathey/causalTree/blob/master/briefintro.pdf).\n\n# Only valid for randomized data!\nfmla <- paste(outcome, \" ~\", paste(covariates, collapse = \" + \"))\nfmla\n\n# Dividing data into three subsets\nindices <- split(seq(nrow(data)), sort(seq(nrow(data)) %% 3))\nnames(indices) <- c('split', 'est', 'test')\n\n# Fitting the forest\nct.unpruned <- honest.causalTree(\n formula=fmla, # Define the model\n data=data[indices$split,],\n treatment=data[indices$split, treatment],\n est_data=data[indices$est,],\n est_treatment=data[indices$est, treatment],\n minsize=1, # Min. number of treatment and control cases in each leaf\n HonestSampleSize=length(indices$est), # Num obs used in estimation after splitting\n \n # We recommend not changing the parameters below\n split.Rule=\"CT\", # Define the splitting option\n cv.option=\"TOT\", # Cross validation options\n cp=0, # Complexity parameter\n split.Honest=TRUE, # Use honesty when splitting\n cv.Honest=TRUE # Use honesty when performing cross-validation\n)\n\n# Table of cross-validated values by tuning parameter.\nct.cptable <- as.data.frame(ct.unpruned$cptable)\n\n# Obtain optimal complexity parameter to prune tree.\ncp.selected <- which.min(ct.cptable$xerror)\n\ncp.optimal <- ct.cptable[cp.selected, \"CP\"]\n\n# Prune the tree at optimal complexity parameter.\nct.pruned <- prune(tree=ct.unpruned, cp=cp.optimal)\n\n# Predict point estimates (on estimation sample)\ntau.hat.est <- predict(ct.pruned, newdata=data[indices$est,])\n\n# Create a factor column 'leaf' indicating leaf assignment in the estimation set\nnum.leaves <- length(unique(tau.hat.est))\nleaf <- factor(tau.hat.est, levels=sort(unique(tau.hat.est)), labels = seq(num.leaves))\n\nNote: if your tree is not splitting at all, try decreasing the parameter `minsize` that controls the minimum size of each leaf. The next snippet plots the learned tree. The values in the cell are the estimated treatment effect and an estimate of the fraction of the population that falls within each leaf. Both are estimated using the `estimation` sample.\n\nrpart.plot(\n x=ct.pruned, # Pruned tree\n type=3, # Draw separate split labels for the left and right directions\n fallen=TRUE, # Position the leaf nodes at the bottom of the graph\n leaf.round=1, # Rounding of the corners of the leaf node boxes\n extra=100, # Display the percentage of observations in the node\n branch=.1, # Shape of the branch lines\n box.palette=\"RdBu\") # Palette for coloring the node\n\n\nInterpret the heatmap above. What describes the subgroups with strongest and weakest estimated treatment effect?\n\n\n\n### Via grf\n\nThe function `causal_forest` from the package `grf` allows us to get estimates of the CATE \\@ref(eq:cate). \n\n# Get predictions from forest fitted above.\ntau.hat <- predict(forest.tau)$predictions # tau(X) estimates\n\nHaving fit a non-parametric method such as a causal forest, a researcher may (incorrectly) start by looking at the distribution of its predictions of the treatment effect. One might be tempted to think: \"if the histogram is concentrated at a point, then there is no heterogeneity; if the histogram is spread out, then our estimator has found interesting heterogeneity.\" However, this may be false.\n\n# Do not use this for assessing heterogeneity. See text above.\nhist(tau.hat, main=\"CATE estimates\", freq=F)\n\nIf the histogram is concentrated at a point, we may simply be underpowered: our method was not able to detect any heterogeneity, but maybe it would detect it if we had more data. If the histogram is spread out, we may be overfitting: our model is producing very noisy estimates $\\widehat{\\tau}(x)$, but in fact the true $\\tau(x)$ can be much smoother as a function of $x$.\n\nThe `grf` package also produces a measure of variable importance that indicates how often a variable was used in a tree split. Again, much like the histogram above, this can be a rough diagnostic, but it should not be interpreted as indicating that, for example, variable with low importance is not related to heterogeneity. The reasoning is the same as the one presented in the causal trees section: if two covariates are highly correlated, the trees might split on one covariate but not the other, even though both (or maybe neither) are relevant in the true data-generating process.\n\nvar_imp <- c(variable_importance(forest.tau))\nnames(var_imp) <- covariates\nsorted_var_imp <- sort(var_imp, decreasing = TRUE)\nsorted_var_imp[1:5] # showing only first few\n\n#### Data-driven subgroups\n\nJust as with causal trees, we can use causal forests to divide our observations into subgroups. In place of leaves, we'll rank observation into (say) quintiles according to their estimated CATE prediction; see, e.g., [Chernozhukov, Demirer, Duflo, Fernández-Val (2020)](https://arxiv.org/abs/1712.04802) for similar ideas.\n\nThere's a subtle but important point that needs to be addressed here. As we have mentioned before, when predicting the conditional average treatment effect $\\tau(X_i)$ for observation $i$ we should in general avoid using a model that was fitted using observation $i$. This sort of sample splitting (which we called **honesty** above) is one of the required ingredients to get unbiased estimates of the CATE using the methods described here. However, when ranking estimates of two observations $i$ and $j$, we need something a little stronger: we must ensure that the model was not fit using _either_ $i$ _or_ $j$'s data. \n\nOne way of overcoming this obstacle is simple. First, divide the data into $K$ folds (subsets). Then, cycle through the folds, fitting a CATE model on $K-1$ folds. Next, for each held-out fold, _separately_ rank the unseen observations into $Q$ groups based on their prediction (i.e., if $Q=5$, then we rank observations by estimated CATE into \"top quintile\", \"second quintile\", and so on). After concatenating the independent rankings together, we can study the differences in observations in each rank-group. \n\n[This gist](https://gist.github.com/halflearned/bea4e5137c0c81fd18a75f682da466c8) computes the above for `grf`, and it should not be hard to modify it so as to replace forests by any other non-parametric method. However, for `grf` specifically, there's a small trick that allows us to obtain a valid ranking: we can pass a vector of fold indices to the argument `clusters` and rank observations within each fold. This works because estimates for each fold (\"cluster\") trees are computed using trees that were not fit using observations from that fold. Here's how to do it. \n\n\n# Valid randomized data and observational data with unconfoundedness+overlap.\n# Note: read the comments below carefully. \n# In randomized settings, do not estimate forest.e and e.hat; use known assignment probs.\n\n# Prepare dataset\nfmla <- formula(paste0(\"~ 0 + \", paste0(covariates, collapse=\"+\")))\nX <- model.matrix(fmla, data)\nW <- data[,treatment]\nY <- data[,outcome]\n\n# Number of rankings that the predictions will be ranking on \n# (e.g., 2 for above/below median estimated CATE, 5 for estimated CATE quintiles, etc.)\nnum.rankings <- 5 \n\n# Prepare for data.splitting\n# Assign a fold number to each observation.\n# The argument 'clusters' in the next step will mimick K-fold cross-fitting.\nnum.folds <- 10\nfolds <- sort(seq(n) %% num.folds) + 1\n\n# Comment or uncomment depending on your setting.\n# Observational setting with unconfoundedness+overlap (unknown assignment probs):\n# forest <- causal_forest(X, Y, W, clusters = folds)\n# Randomized settings with fixed and known probabilities (here: 0.5).\nforest <- causal_forest(X, Y, W, W.hat=.5, clusters = folds)\n\n# Retrieve out-of-bag predictions.\n# Predictions for observation in fold k will be computed using \n# trees that were not trained using observations for that fold.\ntau.hat <- predict(forest)$predictions\n\n# Rank observations *within each fold* into quintiles according to their CATE predictions.\nranking <- rep(NA, n)\nfor (fold in seq(num.folds)) {\n tau.hat.quantiles <- quantile(tau.hat[folds == fold], probs = seq(0, 1, by=1/num.rankings))\n ranking[folds == fold] <- cut(tau.hat[folds == fold], tau.hat.quantiles, include.lowest=TRUE,labels=seq(num.rankings))\n}\n\nThe next snippet computes the average treatment effect within each group defined above, i.e., $\\E[Y_i(1) - Y_i(0)|G_i = g]$. This can done in two ways. First, by computing a simple difference-in-means estimate of the ATE based on observations within each group. This is valid only in randomized settings.\n\n# Valid only in randomized settings.\n# Average difference-in-means within each ranking\n\n# Formula y ~ 0 + ranking + ranking:w\nfmla <- paste0(outcome, \" ~ 0 + ranking + ranking:\", treatment)\nols.ate <- lm(fmla, data=transform(data, ranking=factor(ranking)))\nols.ate <- coeftest(ols.ate, vcov=vcovHC(ols.ate, type='HC2'))\ninteract <- which(grepl(\":\", rownames(ols.ate)))\nols.ate <- data.frame(\"ols\", paste0(\"Q\", seq(num.rankings)), ols.ate[interact, 1:2])\nrownames(ols.ate) <- NULL # just for display\ncolnames(ols.ate) <- c(\"method\", \"ranking\", \"estimate\", \"std.err\")\nols.ate\n\nAnother option is to average the AIPW scores within each group. This valid for both randomized settings and observational settings with unconfoundedness and overlap. Moreover, AIPW-based estimators should produce estimates with tighter confidence intervals in large samples.\n\n\n```\n", "meta": {"hexsha": "f16c034ed6f6a594e2468af2d8fe65bc08eb3344", "size": 59931, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "markdown_generator/Group3_lab5_rscript.ipynb", "max_stars_repo_name": "carlosgonzalez26/carlosgonzalez26.github.io", "max_stars_repo_head_hexsha": "8403c78d82b69c750047c06c59e148fd1d068fe9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "markdown_generator/Group3_lab5_rscript.ipynb", "max_issues_repo_name": "carlosgonzalez26/carlosgonzalez26.github.io", "max_issues_repo_head_hexsha": "8403c78d82b69c750047c06c59e148fd1d068fe9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "markdown_generator/Group3_lab5_rscript.ipynb", "max_forks_repo_name": "carlosgonzalez26/carlosgonzalez26.github.io", "max_forks_repo_head_hexsha": "8403c78d82b69c750047c06c59e148fd1d068fe9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.9527310924, "max_line_length": 16980, "alphanum_fraction": 0.7130533447, "converted": true, "num_tokens": 8491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.32550911587285486}} {"text": "

\n \n\n

\n\n## Subsurface Data Analytics \n\n## Introduction to Spacial Bias: Cell Size's Effect on Declustering Biased Spacial Data\n\n#### Jesse Riedel, Undergraduate Student, The University of Texas at Austin\n\n##### [LinkedIn](https://www.linkedin.com/in/jesse-riedel-12b311163/)\n\n#### Supervised by:\n\n#### Michael Pyrcz, Associate Professor, University of Texas at Austin \n\n##### [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1) | [GeostatsPy](https://github.com/GeostatsGuy/GeostatsPy)\n\n\n### PGE 383 Exercise: Cell Size Manipulation for Declustering Biased Data\n\nHere's a simple workflow that demonstrates first, the concept of declustering in an effort to mitigate the potential bias of spacial data, and second, the effect that the choice of cell size can have on this concept of declustering.\n\n\n#### Real Life Application\n\nThe concept of declustering can be very applicable in the oil and gas industry, or in general, any time there is a bias in gathered data over space. Some examples of use cases for declustering are:\n\n* 3-D declustering data for horizontal or highly deviated wells\n* Performing areal 2-D declustering for wells that are vertical or near vertical\n* Declustering unconventional well data considering the fact that representativity can be an issue even with large datasets and relatively good coverage\n\n#### Workflow Goals\n\nLearn the basics of declustering and how cell size effects declustering. This includes:\n\n* Loading and visualizing sample data\n* Developing a basic understanding of declustering as a strategy to mitigate spatial bias\n* Understanding the importance of cell size on declustered weights of spatial data\n\n#### Getting Started\n\nHere's the steps to get setup in Python with the GeostatsPy package:\n\n1. Install Anaconda 3 on your machine (https://www.anaconda.com/download/). \n2. From Anaconda Navigator (within Anaconda3 group), go to the environment tab, click on base (root) green arrow and open a terminal. \n3. In the terminal type: pip install geostatspy. \n4. Open Jupyter and in the top block get started by copy and pasting the code block below from this Jupyter Notebook to start using the geostatspy functionality. \n\nYou will need to copy the data file to your working directory. They are available here:\n\n* Tabular data - sample_data_biased.csv at https://git.io/fh0CW\n\nThere are exampled below with these functions. You can go here to see a list of the available functions, https://git.io/fh4eX, other example workflows and source code. \n\n\n```python\nimport geostatspy.GSLIB as GSLIB # GSLIB utilies, visualization and wrapper\nimport geostatspy.geostats as geostats # GSLIB methods convert to Python\n```\n\nWe will also need some standard packages. These should have been installed with Anaconda.\n\n\n```python\nimport numpy as np # ndarrys for gridded data\nimport pandas as pd # DataFrames for tabular data\nimport os # set working directory, run executables\nimport matplotlib.pyplot as plt # for plotting\nfrom scipy import stats # summary statistics\n```\n\nLastly, we need to import some packages that will allow us to create interactive functionality.\n\n\n```python\nimport ipywidgets as widgets\nfrom IPython.display import display\nfrom ipywidgets import interact, interactive, fixed, interact_manual\n```\n\n#### Loading Tabular Data\n\nHere's the command to load our comma delimited data file in to a Pandas' DataFrame object. \n\n\n```python\ndf = pd.read_csv('sample_data_biased.csv') # load our data table (wrong name!)\n```\n\nNo error now! It worked, we loaded our file into our DataFrame called 'df'. But how do you really know that it worked? Visualizing the DataFrame would be useful and we already leard about these methods in this demo (https://git.io/fNgRW). \n\nWe can preview the DataFrame by printing a slice or by utilizing the 'head' DataFrame member function (with a nice and clean format, see below). With the slice we could look at any subset of the data table and with the head command, add parameter 'n=13' to see the first 13 rows of the dataset. \n\n\n```python\nprint(df.iloc[0:5,:]) # display first 4 samples in the table as a preview\ndf.head(n=13) # we could also use this command for a table preview\n```\n\n X Y Facies Porosity Perm\n 0 100 900 1 0.115359 5.736104\n 1 100 800 1 0.136425 17.211462\n 2 100 600 1 0.135810 43.724752\n 3 100 500 0 0.094414 1.609942\n 4 100 100 0 0.113049 10.886001\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
XYFaciesPorosityPerm
010090010.1153595.736104
110080010.13642517.211462
210060010.13581043.724752
310050000.0944141.609942
410010000.11304910.886001
520080010.154648106.491795
620070010.153113140.976324
720050010.12616712.548074
820040000.0947501.208561
920010010.15096144.687430
1030080010.1992271079.709291
1130070010.154220179.491695
1230050010.13750238.164911
\n
\n\n\n\n#### Summary Statistics for Tabular Data\n\nThe table includes X and Y coordinates (meters), Facies 1 and 2 (1 is sandstone and 0 interbedded sand and mudstone), Porosity (fraction), and permeability as Perm (mDarcy). \n\nThere are a lot of efficient methods to calculate summary statistics from tabular data in DataFrames. The describe command provides count, mean, minimum, maximum, and quartiles all in a nice data table. We use transpose just to flip the table so that features are on the rows and the statistics are on the columns.\n\n\n```python\ndf.describe().transpose()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countmeanstdmin25%50%75%max
X289.0475.813149254.2775300.000000300.000000430.000000670.000000990.000000
Y289.0529.692042300.8953749.000000269.000000549.000000819.000000999.000000
Facies289.00.8131490.3904680.0000001.0000001.0000001.0000001.000000
Porosity289.00.1347440.0377450.0585480.1063180.1261670.1542200.228790
Perm289.0207.832368559.3593500.0758193.63408614.90897071.4544245308.842566
\n
\n\n\n\n#### Specify the Area of Interest\n\nIt is natural to set the x and y coordinate and feature ranges manually. e.g. do you want your color bar to go from 0.05887 to 0.24230 exactly? Also, let's pick a color map for display. I heard that plasma is known to be friendly to the color blind as the color and intensity vary together (hope I got that right, it was an interesting Twitter conversation started by Matt Hall from Agile if I recall correctly). We will assume a study area of 0 to 1,000m in x and y and omit any data outside this area.\n\n\n```python\nxmin = 0.0; xmax = 1000.0 # range of x values\nymin = 0.0; ymax = 1000.0 # range of y values\npormin = 0.05; pormax = 0.25; # range of porosity values\ncmap = plt.cm.plasma \n```\n\n#### Declustering Biased Data\n\nDeclustering involves assigning a weight to each datum based on closeness to surrounding data. The first step of this process is to divide the volume of interest into a grid of cells, count the occupied cells and the number of datum in each cell. This can be illustrated through the following equation:\n\n## \\begin{equation}\nw(u_j) = \\frac{1}{n_l} \\frac{n}{L_0}\n\\end{equation}\n\nWhere:\n\nw = weight
\nL0 = number of occupied cells
\nn = total number of data points
\nnl = number of data in each cell
\n\nThe following cell contains an augmented version of the declus (declustering) function from the geostats module of GeostatsPy\n\n\n```python\ndef declus(df, xcol, ycol, vcol, iminmax, noff, ncell, cmin, cmax):\n \"\"\"GSLIB's DECLUS program (Deutsch and Journel, 1998) converted from the\n original Fortran to Python by Michael Pyrcz, the University of Texas at\n Austin (Jan, 2019).\n Note this was simplified to 2D only.\n :param df: pandas DataFrame with the spatial data\n :param xcol: name of the x coordinate column\n :param ycol: name of the y coordinate column\n :param vcol: name of the property column\n :param iminmax: 1 / True: for use cell size with max decluster mean\n 0 / False: for declustered mean minimizing cell size\n :param noff: number of offsets\n :param ncell: number of cell sizes\n :param cmin: min cell size\n :param cmax: max cell size\n :return: TODO\n \"\"\"\n # Load data and set up arrays\n #print(ncell)\n nd = len(df)\n x = df[xcol].values\n y = df[ycol].values\n v = df[vcol].values\n wt = np.zeros(nd)\n wtopt = np.ones(nd)\n index = np.zeros(nd, np.int32)\n xcs_mat = np.zeros(ncell + 2) # we use 1,...,n for this array\n vrcr_mat = np.zeros(ncell + 2) # we use 1,...,n for this array\n anisy = 1.0 # hard code the cells to 2D isotropic\n roff = float(noff)\n \n # Calculate extents\n xmin = np.min(x)\n xmax = np.max(x)\n ymin = np.min(y)\n ymax = np.max(y)\n \n # Calculate summary statistics\n vmean = np.mean(v)\n vstdev = np.std(v)\n vmin = np.min(v)\n vmax = np.max(v)\n xcs_mat[0] = 0.0\n vrcr_mat[0] = vmean\n vrop = vmean # include the naive case\n \n print(f\"There are {nd} data with:\")\n print(f\" mean of {vmean} \")\n print(f\" min and max {vmin} and {vmax}\")\n print(f\" standard dev {vstdev} \")\n \n # Define a \"lower\" origin to use for the cell sizes\n xo1 = xmin - 0.01\n yo1 = ymin - 0.01\n \n # Define the increment for the cell size\n xinc = (cmax - cmin) / ncell\n yinc = xinc\n \n # Loop over \"ncell+1\" cell sizes in the grid network\n ncellx = int((xmax - (xo1 - cmin)) / cmin) + 1\n ncelly = int((ymax - (yo1 - cmin * anisy)) / cmin) + 1\n #print(ncellx,ncelly)\n ncellt = ncellx * ncelly\n cellwt = np.zeros(ncellt)\n xcs = cmin - xinc\n ycs = (cmin * anisy) - yinc\n \n # Main loop over cell sizes\n # 0 index is the 0.0 cell, note n + 1 in Fortran\n add_cell = 2\n# if ncell > 1:\n# add_cell = 2\n \n for lp in range(1, ncell + add_cell):\n xcs = xcs + xinc\n ycs = ycs + yinc\n \n# print(xcs,ycs)\n \n # Initialize the weights to zero\n wt.fill(0.0)\n \n # Determine the maximum number of grid cells in the network\n ncellx = int((xmax - (xo1 - xcs)) / xcs) + 1\n ncelly = int((ymax - (yo1 - ycs)) / ycs) + 1\n ncellt = float(ncellx * ncelly) # TODO: not used\n \n # Loop over all the origin offsets selected\n xfac = min((xcs / roff), (0.5 * (xmax - xmin)))\n yfac = min((ycs / roff), (0.5 * (ymax - ymin)))\n for kp in range(1, noff + 1):\n xo = xo1 - (float(kp) - 1.0) * xfac\n yo = yo1 - (float(kp) - 1.0) * yfac\n \n # Initialize the cumulative weight indicators\n cellwt.fill(0.0)\n \n # Determine which cell each datum is in\n for i in range(0, nd):\n icellx = int((x[i] - xo) / xcs) + 1\n icelly = int((y[i] - yo) / ycs) + 1\n icell = icellx + (icelly - 1) * ncellx - 1 # -1 for fortran to python\n index[i] = icell\n #print(i,x[i],y[i],icell)\n cellwt[icell] = cellwt[icell] + 1.0\n \n # The weight assigned to each datum is inversely proportional to the\n # number of data in the cell. We first need to get the sum of\n # weights so that we can normalize the weights to sum to one\n sumw = 0.0\n for i in range(0, nd):\n ipoint = index[i]\n sumw = sumw + (1.0 / cellwt[ipoint])\n sumw = 1.0 / sumw\n \n # Accumulate the array of weights (that now sum to one)\n for i in range(0, nd):\n ipoint = index[i]\n wt[i] = wt[i] + (1.0 / cellwt[ipoint]) * sumw\n \n # End loop over all offsets\n \n # Compute the weighted average for this cell size\n sumw = 0.0\n sumwg = 0.0\n for i in range(0, nd):\n sumw = sumw + wt[i]\n sumwg = sumwg + wt[i] * v[i]\n vrcr = sumwg / sumw\n vrcr_mat[lp] = vrcr\n xcs_mat[lp] = xcs\n \n # See if this weighting is optimal\n if iminmax and vrcr < vrop or not iminmax and vrcr > vrop or ncell == 1:\n best = xcs # TODO: not used\n vrop = vrcr\n wtopt = wt.copy() # deep copy\n \n # End main loop over all cell sizes\n \n # Get the optimal weights\n sumw = 0.0\n for i in range(0, nd):\n sumw = sumw + wtopt[i]\n wtmin = np.min(wtopt) # TODO: not used\n wtmax = np.max(wtopt) # TODO: not used\n facto = float(nd) / sumw\n wtopt = wtopt * facto\n return wtopt, xcs_mat, vrcr_mat\n```\n\n#### Changing Cell Size in Declustering\n\nNow that the we have an implementation for declustering our biased data, we want to see the effect that the cell size parameter has on declustering the data.\n\nIn order to do this, we will be using ipywidgets. Ipywidgets offers interactive user interface elements like sliders, dropdown menus, and more. For this interactive workflow, we will be using a slider to change the cell size parameter of the declus (declustering) function.\n\nLastly, the @interact tag that is given to the interactive_cell_size function below is what allows the cell size slider to change the cell size parameter in the declus function call. This can be also be seen through the parameter of the interactive function being the instance of the slider itself.\n\nThe rest of the function below after the declus function call involves creating two plots, the left colored by the actual porosity data, and the right covered by the declustered weights, and how they are adjusted when the user changes the cell size.\n\n\n```python\n@interact\ndef interactive_cell_size(cell_size = widgets.IntSlider(min = 10, max = 2000, step = 10, description='Cell Size:')):\n wts, cell_sizes, dmeans = declus(df,'X','Y','Porosity',iminmax = 1, noff= 10, ncell=1,cmin=cell_size,cmax=cell_size)\n \n df['Wts'] = wts\n \n f = plt.figure()\n \n f.set_figwidth(16)\n f.set_figheight(6)\n \n plt.subplot(1,2,1)\n GSLIB.locmap_st(df,'X','Y','Porosity',xmin,xmax,ymin,ymax,pormin,pormax,'Well Data - Porosity','X(m)','Y(m)','Porosity (fraction)',cmap)\n plt.subplot(1,2,2) \n GSLIB.locmap_st(df,'X','Y','Wts',xmin,xmax,ymin,ymax,0.5,2.5,'Well Data Weights','X(m)','Y(m)','Weights',cmap)\n \n \n plt.tight_layout()\n```\n\n\n interactive(children=(IntSlider(value=10, description='Cell Size:', max=2000, min=10, step=10), Output()), _do…\n\n\nAs can be seen by the Well Data Weights plot on the right, when the cell size is adjusted, the weights of data points, illustrated by the color gradient shown on the right axis, change heavily.\n\n#### Declustered Porosity Mean vs. Cell Size\n\nThe following portion of the workflow will give another perspective of the effect of declustering spatial data.\n\nWe will first call the declus function again, but this time we will set the cell sizes to vary between a wide range from 10m to 2,000m. This will allow the geostats.declus function to take the cell size that minimizes the declustered mean, denoted by the 'iminmax' parameter being set to 1 (setting this parameter will maximize the declustered mean).\n\n\n```python\ndf = pd.read_csv('sample_data_biased.csv') # load our data table (wrong name!)\ndf['Wts'] = wts # add weights to the sample data DataFrame\nwts, cell_sizes, dmeans = geostats.declus(df,'X','Y','Porosity',iminmax = 1, noff= 10, ncell=100,cmin=10,cmax=2000)\n```\n\n There are 289 data with:\n mean of 0.13474387540138408 \n min and max 0.058547873 and 0.228790002\n standard dev 0.03767982164385207 \n\n\nWe can now see the porosity mean pre-declustering and post-declustering, as well as the summary statistics as a result of the declustering:\n\n\n```python\npor_mean = np.average(df['Porosity'].values)\npor_dmean = np.average(df['Porosity'].values,weights=df['Wts'].values)\nprint('Porosity naive mean is ' + str(round(por_mean,3))+'.')\nprint('Porosity declustered mean is ' + str(round(por_dmean,3))+'.')\ncor = (por_mean-por_dmean)/por_mean\nprint('Correction of ' + str(round(cor,4)) +'.')\n\nprint('\\nSummary statistics of the declsutering weights:')\nprint(stats.describe(wts))\n```\n\n Porosity naive mean is 0.135.\n Porosity declustered mean is 0.121.\n Correction of 0.1002.\n \n Summary statistics of the declsutering weights:\n DescribeResult(nobs=289, minmax=(0.2819756671865989, 3.984325446814365), mean=0.9999999999999996, variance=0.40927076480664726, skewness=1.9395015754905447, kurtosis=4.287460624778004)\n\n\n\nLastly, we can look at a plot of the declustered porosity mean vs. the declustering cell size. It can be noted that at very large cell sizes the declustered mean is the naive mean.\n\n\n```python\nplt.subplot(111)\nplt.scatter(cell_sizes,dmeans, s=30, alpha = 0.2, edgecolors = \"black\", facecolors = 'red')\nplt.xlabel('Cell Size (m)')\nplt.ylabel('Declustered Porosity Mean (fraction)')\nplt.title('Declustered Porosity Mean vs. Cell Size')\nplt.plot([0,2000],[por_mean,por_mean],color = 'black')\nplt.plot([200,200],[0.10,0.16],color = 'black',linestyle='dashed')\nplt.text(300., 0.136, r'Naive Porosity Mean')\nplt.text(500., 0.118, r'Declustered Porosity Mean')\nplt.text(230., 0.154, r'Minimizing')\nplt.text(230., 0.150, r'Cell Size')\nplt.ylim(0.10,0.16)\nplt.xlim(0,2000)\nplt.subplots_adjust(left=0.0, bottom=0.0, right=1.2, top=1.2, wspace=0.2, hspace=0.2)\nplt.show()\n```\n\n#### Comments\n\nThis was an interactive workflow covering the basics cell size's effect on declustering spatially biased data. \n\nThe Texas Center for Geostatistics has many other demonstrations on the basics of working with DataFrames, ndarrays, univariate statistics, plotting data, data transformations, trend modeling and many other workflows available [here](https://github.com/GeostatsGuy/PythonNumericalDemos), along with a package for geostatistics in Python called [GeostatsPy](https://github.com/GeostatsGuy/GeostatsPy). \n \nWe hope this was helpful,\n\n*Jesse* and *Michael*\n\n***\n\n#### More on Michael Pyrcz and the Texas Center for Data Analytics and Geostatistics:\n\n### Michael Pyrcz, Associate Professor, University of Texas at Austin \n*Novel Data Analytics, Geostatistics and Machine Learning Subsurface Solutions*\n\nWith over 17 years of experience in subsurface consulting, research and development, Michael has returned to academia driven by his passion for teaching and enthusiasm for enhancing engineers' and geoscientists' impact in subsurface resource development. \n\nFor more about Michael check out these links:\n\n#### [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1)\n\n#### Want to Work Together?\n\nI hope this content is helpful to those that want to learn more about subsurface modeling, data analytics and machine learning. Students and working professionals are welcome to participate.\n\n* Want to invite me to visit your company for training, mentoring, project review, workflow design and / or consulting? I'd be happy to drop by and work with you! \n\n* Interested in partnering, supporting my graduate student research or my Subsurface Data Analytics and Machine Learning consortium (co-PIs including Profs. Foster, Torres-Verdin and van Oort)? My research combines data analytics, stochastic modeling and machine learning theory with practice to develop novel methods and workflows to add value. We are solving challenging subsurface problems!\n\n* I can be reached at mpyrcz@austin.utexas.edu.\n\nI'm always happy to discuss,\n\n*Michael*\n\nMichael Pyrcz, Ph.D., P.Eng. Associate Professor The Hildebrand Department of Petroleum and Geosystems Engineering, Bureau of Economic Geology, The Jackson School of Geosciences, The University of Texas at Austin\n\n#### More Resources Available at: [Twitter](https://twitter.com/geostatsguy) | [GitHub](https://github.com/GeostatsGuy) | [Website](http://michaelpyrcz.com) | [GoogleScholar](https://scholar.google.com/citations?user=QVZ20eQAAAAJ&hl=en&oi=ao) | [Book](https://www.amazon.com/Geostatistical-Reservoir-Modeling-Michael-Pyrcz/dp/0199731446) | [YouTube](https://www.youtube.com/channel/UCLqEr-xV-ceHdXXXrTId5ig) | [LinkedIn](https://www.linkedin.com/in/michael-pyrcz-61a648a1)\n\n\n```python\n\n```\n", "meta": {"hexsha": "c7d97b0815edbc17b3953bc2eb26a78bc4d4e3b0", "size": 65519, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Spring2021/DeclusteringCellSize.ipynb", "max_stars_repo_name": "GeostatsGuy/Undergraduate_Research", "max_stars_repo_head_hexsha": "8c6f0d7799b266e9e29d42dd64e229b9df4f7def", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-24T18:37:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T17:58:09.000Z", "max_issues_repo_path": "Spring2021/DeclusteringCellSize.ipynb", "max_issues_repo_name": "GeostatsGuy/Undergraduate_Research", "max_issues_repo_head_hexsha": "8c6f0d7799b266e9e29d42dd64e229b9df4f7def", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spring2021/DeclusteringCellSize.ipynb", "max_forks_repo_name": "GeostatsGuy/Undergraduate_Research", "max_forks_repo_head_hexsha": "8c6f0d7799b266e9e29d42dd64e229b9df4f7def", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-15T13:17:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-15T13:17:20.000Z", "avg_line_length": 71.9198682766, "max_line_length": 29716, "alphanum_fraction": 0.7248279125, "converted": true, "num_tokens": 7247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.3247718349255966}} {"text": "```\n##### Copyright 2021 The Cirq Developers\n```\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Toric Code Ground State\n\n\n \n \n \n \n
\n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nBefore beginning, we will import the necessary modules into the colab.\n\n\n```\ntry:\n import recirq\nexcept ImportError:\n !pip install --quiet git+https://github.com/quantumlib/ReCirq\n import recirq\n\ntry:\n import qsimcirq\nexcept ImportError:\n !pip install qsimcirq --quiet\n import qsimcirq\n\nimport cirq\nimport matplotlib.pyplot as plt\n\nimport recirq.toric_code.toric_code_plaquettes as tcp\nimport recirq.toric_code.toric_code_plotter as tcplot\nimport recirq.toric_code.toric_code_rectangle as tcr\nimport recirq.toric_code.toric_code_state_prep as tcsp\n\nplt.rcParams['figure.dpi'] = 144\n```\n\n### Toric code Hamiltonian\n\nThe toric code Hamiltonian\n\n\\begin{equation}\nH = -\\sum_s A_s - \\sum_p B_p\n\\end{equation}\n\ninvolves local four-qubit parity operators, where each qubit lives on an edge in a square lattice. Here, the \"star\" operators $A_s$ are products of Pauli $Z$ operators around a vertex, while the \"plaquette\" operators $B_p$ are products of $X$ operators around a square, for example,\n\n\\begin{equation}\nA_s = Z_i \\otimes Z_j \\otimes Z_k \\otimes Z_l \n\\end{equation}\n\\begin{equation}\nB_p = X_a \\otimes X_b \\otimes X_c \\otimes X_d.\n\\end{equation}\n\nThese local parity operators all commute with each other: all $A_s$ commute, all $B_p$ commute, and $A_s$ and $B_p$ commute with each other because they overlap on an even number of qubits. They can thus all be simultaneously diagonalized, and those shared eigenstates are also the eigenstates of $H$.\n\n\n\n\n\nIn our paper, we mostly work with the 31-qubit lattice above. With these boundary conditions, there is a _unique_ ground state that has a $+1$ eigenvalue for all $A_s$ and $B_p$. Note for different boundary conditions, we can have _degeneracies_ that are locally-indistinguishable (for example on a torus, or with the \"surface code\" logical qubits we explore in Figure 4 of our paper).\n\nIn this module, we will primarily work with the smaller 22-qubit to avoid time and memory constraints associated with the larger rectangle.\n\n### Understanding the ground state\n\nIn this example, we focus on reproducing our first figure, where we create this unique ground state $|G\\rangle$ using a shallow unitary circuit. The general idea is to start out with $|0\\rangle^{\\otimes 22}$, so all $\\langle A_s \\rangle = +1$. We then apply projection operators $\\mathbb{I} + B_p$ which project the state into a $+1$ eigenstate of $B_p$, after which all the local parities are $+1$:\n\n\\begin{equation}\n|G\\rangle \\propto \\prod_p (\\mathbb{I} + B_p)|0\\rangle^{\\otimes 22}.\n\\end{equation}\n\nTo create this state, we assign a \"team captain\" qubit to each plaquette $B_p$. Starting from $|0\\rangle^{\\otimes n}$, we perform a Hadamard on each team captain, and then each team captain is responsible for performing a CNOT to each of its team mates. We have to be careful with the ordering to keep things efficient and avoid the captains stepping on each other's toes. This is easier to visualize for a smaller system, for example the 12-qubit version in Figure S2, reproduced below. Note the superposition of $2^4$ states, as there are four plaquettes $B_p$.\n\n\n\n### Creating $|G\\rangle$ with ReCirq\n\n#### Basics: 22-qubit circuit\n\nFirst, we can create a example 22-qubit grid by instantiate it using a `ToricCodeRectangle` object and then plot a visualization using a `ToricCodePlotter` object, both found in the ReCirq repository.\n\n\n```\nshort_rectangle = tcr.ToricCodeRectangle(\n origin_qubit=cirq.GridQubit(3, 0), row_vector=(1, 1), rows=2, cols=4\n)\nplotter = tcplot.ToricCodePlotter()\nplotter.plot_code(short_rectangle)\n```\n\nWe can also see the full circuit of how to create this code (using CNOT gates) using these objects as well. By printing out the circuit moment by moment, we can see the gates lined up in a visual manner.\n\n\n```\nfull_circuit = tcsp.toric_code_cnot_circuit(short_rectangle)\nfor idx, moment in enumerate(full_circuit):\n print(f'moment {idx}\\n{moment}\\n')\n```\n\n#### Simulating the parities\n\nFor a given circuit, we can determine all the parity expectation values $\\langle A_s\\rangle$ by sampling 22-qubit bitstrings and then computing each expectation value. We do the same thing with for $\\langle B_p \\rangle$, but we include a layer of Hadamards before measurement to effectively \"measure in $X$ basis.\"\n\n\n```\ndef partial_circuit(\n n_moments_to_include: int, *, x_basis: bool\n) -> cirq.Circuit:\n \"\"\"Create the first N moments of a toric in Z or X basis.\n \n Args:\n n_moments_to_include: number of moments to include\n x_basis: If True, add Hadamards to effectively measure in the X basis.\n If False, measure in the computational (Z) basis.\n\n Returns: First N moments of a toric code circuit plus an optional\n layer of Hadamard gates to effectively measure in the X basis.\n This circuit also includes measurement gates.\n \"\"\"\n sliced_circuit = full_circuit[:n_moments_to_include]\n qubits = sorted(short_rectangle.qubits)\n if x_basis:\n sliced_circuit += cirq.Moment(cirq.H.on_each(*qubits))\n return sliced_circuit + cirq.measure(*qubits)\n\n\ndef get_plaquettes(\n n_moment_to_include: int, repetitions: int = 1000,\n sampler: cirq.Sampler = qsimcirq.QSimSimulator()\n) -> tcp.ToricCodePlaquettes:\n \"\"\"Simulates the results in both bases and determine plaquette values.\n\n Args:\n n_moments_to_include: number of moments to include\n repetitions: number of repetitions (shots) to sample\n sampler: Sampler (simulator) to execute circuits. Defaults to qsim.\n \"\"\"\n x_data = sampler.run(\n partial_circuit(n_moment_to_include, x_basis=True), repetitions=repetitions\n )\n z_data = sampler.run(\n partial_circuit(n_moment_to_include, x_basis=False), repetitions=repetitions\n )\n return tcp.ToricCodePlaquettes.from_global_measurements(\n short_rectangle, x_data.data, z_data.data\n )\n```\n\nWe can step through the circuit one moment at a time to see how the parities $A_s$ and $B_p$ evolve through the circuit. This is similar to Figure 1B in paper (but simulating instead of using experimental data). We begin with $|0\\rangle^{\\otimes 22}$, which corresponds to `n_moments_to_include=0`. There, all $\\langle A_s \\rangle = +1$ but $\\langle B_p \\rangle = 0$ (see colorbars below). The subsequent moments apply Hadamard and CNOT gates to stitch entanglement across the device and create $|G\\rangle$.\n\n\n```\nfor n in range(len(tcsp.toric_code_cnot_circuit(short_rectangle)) + 1):\n p = get_plaquettes(n)\n ax = plotter.plot_expectation_values(p)\n ax.set_title(f'n_moments_to_include={n}')\n plt.pause(0.001)\n```\n\nAfter the final step, all the parities are $+1$ (see colorbars below), indicating we have successfully created $|G\\rangle$.\n\n\n```\nax_z = plotter.make_colorbar(x_basis=False, orientation='horizontal')\nax_z.set_label(r'Z parity, $\\langle A\\rangle$')\n\nax_x = plotter.make_colorbar(x_basis=True, orientation='horizontal')\nax_x.set_label(r'X parity, $\\langle B\\rangle$')\n```\n", "meta": {"hexsha": "1ceba2bf8538af5257963efcc35191397c159a62", "size": 12966, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/toric_code/toric_code_ground_state.ipynb", "max_stars_repo_name": "kevinsung/ReCirq", "max_stars_repo_head_hexsha": "e3031c3b9327d884f7a5b18b265d54db16ed9296", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/toric_code/toric_code_ground_state.ipynb", "max_issues_repo_name": "kevinsung/ReCirq", "max_issues_repo_head_hexsha": "e3031c3b9327d884f7a5b18b265d54db16ed9296", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/toric_code/toric_code_ground_state.ipynb", "max_forks_repo_name": "kevinsung/ReCirq", "max_forks_repo_head_hexsha": "e3031c3b9327d884f7a5b18b265d54db16ed9296", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.523943662, "max_line_length": 576, "alphanum_fraction": 0.614915934, "converted": true, "num_tokens": 2206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3245572159415192}} {"text": "# KVLCC2 prediction woth Simplified ikedas method \n\n# Purpose\nState the purpose of the notebook.\n\n# Methodology\nQuickly describe assumptions and processing steps.\n\n# WIP - improvements\n(WORK IN PROGRESS)\nUse this section only if the notebook is not final.\n\nNotable TODOs:\n* todo 1\n* todo 2\n* todo 3\n\n## Results\nDescribe and comment the most important results.\n\n# Suggested next steps\nState suggested next steps, based on results obtained in this notebook.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\n\n```\n\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 461 ('figure.figsize : 5, 3 ## figure size in inches')\n Duplicate key in file WindowsPath('C:/Users/maa/.matplotlib/stylelib/paper.mplstyle'), line 462 ('figure.dpi : 100 ## figure dots per inch')\n\n\n\n```python\nfrom rolldecayestimators.simplified_ikeda_class import SimplifiedIkeda\nimport rolldecayestimators\n```\n\n\n```python\ndb = database.get_db()\n```\n\n\n```python\nsql = \"\"\"\nSELECT * from run\nWHERE model_number='M5057-01-A' and test_type='roll decay' and project_number=40178362;\n\"\"\"\ndf_rolldecays = pd.read_sql(sql=sql, con=db.engine, index_col='id')\n\ndf_rolldecays['ship_speed'].fillna(0, inplace=True)\n\n```\n\n\n```python\ndf_rolldecays[['date','ship_speed']]\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
dateship_speed
id
213372018-04-030.0
213382018-04-030.0
213392018-11-280.0
213402018-04-0415.5
\n
\n\n\n\n\n```python\ndf_rolldecays=df_rolldecays.loc[[21337,21338]].copy()\n```\n\n\n```python\nlowpass_filter = LowpassFilterDerivatorTransformer(cutoff=1, minimum_score=0.999)\ncutter = CutTransformer(phi_max=np.deg2rad(15), phi_min=np.deg2rad(2), phi1d_start_tolerance=0.015)\noffset_transformer = OffsetTransformer()\n```\n\n\n```python\nsteps = [\n ('filter',lowpass_filter),\n ('cutter', cutter), \n# ('offset_transformer',offset_transformer),\n]\n\n\npreprosessor = Pipeline(steps=steps)\n```\n\n\n```python\ndef prepare_inputs(run):\n\n data = {}\n scale_factor=run.model.scale_factor\n rho=1000\n g=9.81\n data['rho']=rho\n data['g']=g\n \n data['lpp']=run.ship.lpp/scale_factor\n data['TA']=run.loading_condition.TA/scale_factor\n data['TF']=run.loading_condition.TF/scale_factor\n data['beam']=run.ship.beam/scale_factor\n \n if not run.ship.BKL:\n data['BKL']=0\n else:\n data['BKL']=run.ship.BKL/scale_factor\n \n if not run.ship.BKB:\n data['BKB']=0\n else:\n data['BKB']=run.ship.BKB/scale_factor\n \n \n data['kg']=run.loading_condition.kg/scale_factor\n data['Volume']=run.loading_condition.Volume/scale_factor**3\n data['gm']=run.loading_condition.gm/scale_factor\n \n if pd.isnull(run.ship_speed):\n data['V']=0\n else:\n data['V']=run.ship_speed*1.852/3.6/np.sqrt(scale_factor) #[m/s]\n \n \n data['KXX']=run.loading_condition.KXX/scale_factor\n data['A0']=run.loading_condition.A0\n \n return data\n \n```\n\n\n```python\nmodels = OrderedDict()\n\nfor id,row in df_rolldecays.iterrows():\n run = db.session.query(Run).get(int(row.name))\n run = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n \n data = prepare_inputs(run=run)\n \n estimator_ikeda_quadratic = IkedaQuadraticEstimator(**data,\n verify_input=False, limit_inputs=False)\n \n preprosessor.fit(X=run.df[['phi']])\n X = preprosessor.transform(run.df[['phi']])\n\n estimator_ikeda_quadratic.fit(X=X)\n models[id] = estimator_ikeda_quadratic\n \n```\n\n c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n df_.units = units\n c:\\dev\\evaluation\\signal_lab\\mdl_to_evaluation.py:106: UserWarning: Pandas doesn't allow columns to be created via a new attribute name - see https://pandas.pydata.org/pandas-docs/stable/indexing.html#attribute-access\n df_.units = units\n\n\n\n```python\nfor id,model in models.items():\n model.plot_fit()\n```\n\n\n```python\nfig,ax=plt.subplots()\n\nfor id,model in models.items():\n \n model.plot_damping(ax=ax)\n```\n\n\n```python\ndf_models = pd.DataFrame()\n\nfor id,model in models.items():\n \n s = pd.Series(data=model.result_for_database(),name=id)\n s['score']=model.score()\n df_models = df_models.append(s)\n \n```\n\n\n```python\ndf_models\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
B_1B_2B_44_1B_44_2B_BK_1B_BK_2B_E_1B_E_2B_F_1B_F_2B_L_1B_L_2B_W_1B_W_2B_edomega0omega0_fftphi_startphi_stopscorezeta
213373.62314418.6627766.7836429.9441390.00.03.1604986.3209951.0251371.0251370.00.02.5980072.5980079.9441390.1391482.4755752.4755750.1611810.0630060.9162150.005456
213383.56292218.6627766.98317610.4034300.00.03.4202546.8405081.0225321.0225320.00.02.5403902.54039010.4034300.1377392.4630092.4630090.1753180.0347320.8287740.005338
\n
\n\n\n\n\n```python\ninteresting = ['B_1','B_2','omega0','score']\ndf_models[interesting].transpose().plot(kind='bar')\n```\n\n\n```python\nphi_a = np.deg2rad(10)\n\nB_e = lambdas.B_e_lambda(B_1=df_models['B_1'],\n B_2=df_models['B_2'],\n omega0=df_models['omega0'],\n phi_a = phi_a)\n```\n\n\n```python\ng=9.81\nrho=1000\nscale_factor=run.model.scale_factor\nVolume = run.loading_condition.Volume/(scale_factor**3)\nbeam = run.ship.beam/scale_factor\nlambdas.B_hat_lambda(B=B_e, Disp=Volume, beam=beam,g=g, rho=rho)\n```\n\n\n\n\n 21337 0.003017\n 21338 0.002990\n dtype: float64\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "744ac79e49a678f2c8d7f825f5b7807e3dff31fc", "size": 334330, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/03.1_KVLCC2_SI_method.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/03.1_KVLCC2_SI_method.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/03.1_KVLCC2_SI_method.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 507.3292867982, "max_line_length": 128144, "alphanum_fraction": 0.9396853408, "converted": true, "num_tokens": 2782, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6150878414043816, "lm_q1q2_score": 0.32434598210240106}} {"text": "# Variational Quantum Eigensolver\n\n Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. \n\n## Overview\n\nIt is widely believed that one of the most promising applications of quantum computing in the near future is solving quantum chemistry problems [1-2]. **Variational Quantum Eigensolver** (VQE) is a strong proof to this possibility of studying quantum chemistry with **Noisy Intermediate-Scale Quantum** (NISQ) devices [1-4]. The core task is to solve the ground state of any molecular Hamiltonian $\\hat{H}$ by preparing a parametrized wave function ansatz $|\\Psi(\\boldsymbol\\theta)\\rangle$ on a quantum computer and adopt classical optimization methods (e.g. gradient descent) to adjust the parameters $\\boldsymbol\\theta$ to minimize the expectation value $\\langle \\Psi(\\boldsymbol\\theta)|\\hat{H}|\\Psi(\\boldsymbol\\theta)\\rangle$. This approach is based on the **Rayleigh-Ritz variational principle**. \n\n$$\nE_0 = \\min_{\\boldsymbol\\theta} \\langle \\Psi(\\boldsymbol\\theta)|\\hat{H}|\\Psi(\\boldsymbol\\theta)\\rangle.\n\\tag{1}\n$$\n\nwhere $E_0$ denotes the ground state energy. Numerically, it can be understood as finding the smallest eigenvalue $\\lambda_{\\min}$ of a **discretized** Hamiltonian $H$ (hermitian matrix) and its corresponding eigenvector $|\\Psi_0\\rangle$. How such a discretization can be done on a classical computer belongs to the art of quantum chemistry and is far beyond the scope of this tutorial. We will discuss this part with a few words in the background section. In general, such a Hamiltonian $H$ is expressed as a weighted sum of Pauli spin operators $\\{X,Y,Z\\}$ (native to quantum devices) such that this information can be processed on a quantum computer.\n\n$$\nH = \\sum_k c_k ~ \\bigg( \\bigotimes_{j=0}^{M-1} \\sigma_j^{(k)} \\bigg),\n\\tag{2}\n$$\n\nwhere $\\sigma_j^{(k)} \\in \\{I,X,Y,Z\\}$ and $M$ stands for qubit number. We refer this form of Hamiltonian as **Pauli strings**. For example, \n\n$$\nH= 0.12~Y_0 \\otimes I_1-0.04~X_0\\otimes Z_1.\n\\tag{3}\n$$\n\nIn the next section, we will provide a brief review on the electronic structure problem which essentially tells us where does the Hamiltonian $H$ come from. For those who are already familiar with this topic or only interested in how to implement VQE on Paddle Quantum, please skip this part and jump into the illustrative example of hydrogen molecule $H_2$.\n\n## Background: the electronic structure problem\n\nIn this section, we focus on one of the fundamental problems in quantum chemistry -- **the electronic structure problem**. To be more specific, we are interested in the low lying energy eigenstates of any given molecule. These knowledge could help predict reaction rates and location of stable structures [5]. Suppose a molecule consists of $N_n$ nuclei and $N_e$ electrons, the first quantized (canonical quantization) Hamiltonian operator $\\hat{H}_{mol}$ describing the total energy of this molecular system can be written as\n\n$$\n\\begin{align}\n\\hat{H}_{\\text{mol}} & = -\\sum_{i}\\frac{\\nabla_{R_i}^2}{2M_i} - \\sum_{i} \\frac{\\nabla_{r_i}^2}{2} -\\sum_{i,j}\\frac{Z_i}{\\lvert R_i - r_j\\lvert} + \\sum_{i,j>i}\\frac{Z_iZ_j}{\\lvert R_i - R_j\\lvert} + \\sum_{i, j>i}\\frac{1}{\\lvert r_i - r_j\\lvert}, \n\\tag{4}\n\\end{align}\n$$\n\nwhere $R_i, M_i,$ and $Z_i$ denote the position, mass and atomic number (the number of protons) of the $i^{th}$ nucleus, and the positions of electrons are $r_i$. The first two sums describe the kinetic energy of nuclei and electrons, respectively. The third sum describes the attractive Coulomb interaction between the positively charged nuclei and the negatively charged electrons. The last two terms represent the repulsive nuclei-nuclei and electron-electron interactions. Here, the molecular Hamiltonian $\\hat{H}_\\text{mol}$ is already in atomic units of energy, **Hartree**. 1 Hartree is $[\\hbar^2/(m_ee^2a_0^2)] = 27.2$ eV or 630 kcal/mol, where $m_e, e,$ and $a_0$ stand for the mass of electron, charge of electron, and Bohr radius. \n\n\n**Note:** The spin-orbit interaction and hyperfine interaction are not considered in this picture. They can be treated as perturbations if necessary. \n\n### Born-Oppenheimer approximation\n\nSince the nuclei are much heavier than electrons, the electrons will move much faster than the nuclei. It is reasonable to treat the positions of nuclei as fixed, $R_i =$ constants. This is known as the Born-Oppenheimer approximation by decoupling the behavior of nuclei and electrons in time scale. Consequently, the kinetic energy term of nuclei will disappear and the nuclei-nuclei repulsive interaction term can be viewed as an energy shift (independent of electron positions $r_i$). We could derive the electronic Hamiltonian $\\hat{H}_{\\text{electron}}$ as\n\n$$\n\\begin{align}\n\\hat{H}_{\\text{electron}} & = - \\sum_{i} \\frac{\\nabla_{r_i}^2}{2} -\\sum_{i,j}\\frac{Z_i}{\\lvert R_i - r_j\\lvert} + \\sum_{i, j>i}\\frac{1}{\\lvert r_i - r_j\\lvert} \n\\tag{5},\n\\end{align}\n$$\n\nThe energy levels of the electrons in the molecule can be found by solving the time independent Schrödinger equation\n\n$$\n\\hat{H}_{\\text{electron}} |\\Psi_n \\rangle = E_n |\\Psi_n \\rangle,\n\\tag{6}\n$$\n\nwhere $n$ stands for the energy level. Notice the electron repulsion terms scale as $N_e(N_e-1)/2$ which means for the Oxygen molecule $O_2$ carrying 16 electrons there will be 120 electron repulsion terms in total! In general, this problem cannot be solved analytically. As Dirac concluded in [Quantum mechanics of many-electron systems](https://royalsocietypublishing.org/doi/10.1098/rspa.1929.0094) [6],\n\n> *The underlying physical laws necessary for the mathematical theory of a large part of physics and the whole of chemistry are thus completely known, and the difficulty is only that the exact application of these laws leads to equations much too complicated to be soluble.* \n>\n> ​\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-- Paul Dirac (1929)\n\nA straightforward numerical approach is discretizing the infinite-dimensional Hilbert space into equidistant grid points where linear algebra guides the whole calculation. Suppose each axis of space is discretized into $k$ points, the $N$-electron (drop the subscript e for simplicity) wave function can be written as [2]\n\n$$\n|\\Psi \\rangle = \\sum_{\\mathbf{x_1}, \\ldots, \\mathbf{x_N}} \\psi(\\mathbf{x_1}, \\ldots, \\mathbf{x_N}) \\mathcal{A}(|\\mathbf{x_1}, \\ldots, \\mathbf{x_N}\\rangle).\n\\tag{7}\n$$\n\nwhere coordinate $|\\mathbf{x_j}\\rangle = |r_j\\rangle |\\sigma_j\\rangle$ records the spatial location and spin of the $j^{th}$ electron, $|r_j\\rangle = |x_j,y_j,z_j\\rangle$ for $j\\in \\{1,2,\\cdots,N\\}$, $x_j,y_j,z_j \\in \\{0,1,\\cdots,k-1\\}$ and $\\sigma_j \\in \\{\\downarrow,\\uparrow\\}$ for spin down or up. There will be $k^{3N}\\times 2^{N}$ complex amplitudes in total. Here, $\\mathcal{A}$ denotes anti-symmetrization and a consequence of the Pauli exclusion principle (electrons are fermion), and $\\psi(\\mathbf{x_1}, \\mathbf{x_2}, \\ldots, \\mathbf{x_N})=\\langle\\mathbf{x_1}, \\mathbf{x_2}, \\ldots, \\mathbf{x_N}|\\Psi\\rangle$. One can see that storing such a wave function already requires **exponentially growing memory** with respect to the number of electrons $N$. This would make classical simulation methods based on this naive numerical approach intractable for systems size larger than few tens of electrons. Now, the question becomes can we prepare such a wave function $|\\Psi\\rangle$ directly on a quantum computer and measure the expectation value $E_0$? In the next section, let's take the simplest molecular system -- hydrogen molecule $H_2$ as a concrete example.\n\n\n\n**Note:** A detailed review on quantum chemistry and existing classical computational methods are far beyond the scope of this tutorial, we refer the enthusiastic readers to the standard textbooks *'Molecular Electronic-Structure Theory'* [5] by Helgaker and *'Modern Quantum Chemistry: Introduction to Advanced Electronic Structure Theory'* [7] by Szabo & Ostlund. To bridge to knowledge gap between quantum chemistry and quantum computing, please check the following review papers [Quantum computational chemistry](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.92.015003) [2] and [Quantum Chemistry in the Age of Quantum Computing](https://pubs.acs.org/doi/10.1021/acs.chemrev.8b00803) [1].\n\n**Note:** For energy calculation, it is desired to reach the **chemical accuracy** of $1.6\\times10^{-3}$ Hartree or 1 kcal/mol . \n\n## Ground state of the hydrogen molecule $H_2$\n\n### Building electronic Hamiltonian\n\nFirst of all, let us import the necessary libraries and packages.\n\n\n\n\n```python\nimport os\nimport platform\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\n\nimport numpy\nfrom numpy import concatenate\nfrom numpy import pi as PI\nfrom numpy import savez, zeros\n\nimport paddle\nfrom paddle_quantum.circuit import UAnsatz\nfrom paddle_quantum.utils import pauli_str_to_matrix\nfrom paddle_quantum.VQE.chemistrysub import H2_generator\n```\n\nTo analyze specific molecules, we need several key information such as **geometry**, **basis set** (such as STO-3G), **multiplicity**, and **charge** to obtain the discretized Hamiltonian $H$. Specifically, through our built-in quantum chemistry toolkit, fermion-to-qubit mapping technology can be used to output the qubit Hamiltonian of hydrogen molecule $H_2$,\n\n\n```python\nHamiltonian, N = H2_generator()\n```\n\nFor more advanced users, we provide a simple tutorial on how to generate such a Hamiltonian. Install the following two packages first (**only available for Mac/Linux users, not available to Windows users temporarily**):\n\n\n```python\n!pip install openfermion\nclear_output()\n```\n\n\n```python\n!pip install openfermionpyscf\nclear_output()\n```\n\n\n```python\n# Operating system information\nsysStr = platform.system()\n\n# Decide which operating system the user is using\nif sysStr in ('Linux', 'Darwin'):\n\n import openfermion \n import openfermionpyscf \n\n # Please check whether the geometric configuration file of h2 is downloaded correctly\n geometry = 'h2.xyz'\n # geometry = [('H', (0.0, 0.0, 0.0)), ('H', (0.0, 0.0, 0.74))]\n basis = 'sto-3g'\n charge = 0\n multiplicity = 1\n\n # Generate Hamiltonian\n molecular_hamiltonian = openfermionpyscf.generate_molecular_hamiltonian(geometry, basis, multiplicity, charge)\n qubit_op = openfermion.transforms.jordan_wigner(molecular_hamiltonian)\n \n # Print result\n print(\"The generated h2 Hamiltonian is \\n\", qubit_op)\n```\n\n The generated h2 Hamiltonian is \n -0.042078976477822494 [] +\n -0.04475014401535163 [X0 X1 Y2 Y3] +\n 0.04475014401535163 [X0 Y1 Y2 X3] +\n 0.04475014401535163 [Y0 X1 X2 Y3] +\n -0.04475014401535163 [Y0 Y1 X2 X3] +\n 0.17771287465139946 [Z0] +\n 0.17059738328801055 [Z0 Z1] +\n 0.12293305056183797 [Z0 Z2] +\n 0.1676831945771896 [Z0 Z3] +\n 0.17771287465139946 [Z1] +\n 0.1676831945771896 [Z1 Z2] +\n 0.12293305056183797 [Z1 Z3] +\n -0.24274280513140462 [Z2] +\n 0.1762764080431959 [Z2 Z3] +\n -0.24274280513140462 [Z3]\n\n\n**Note:** This Hamiltonian is generated with an interatomic distance of $d = 74$ pm. \n\nIn addition to hydrogen molecule $H_2$, we also provide the geometric configuration file of hydrogen fluoride (HF) molecule `hf.xyz`. If you need to test the geometric configuration of more molecules, please check out this [database](http://smart.sns.it/molecules/index.html). In addition, we also need to convert the Hamiltonian into the Pauli string format supported by Paddle Quantum. Here we provide this interface.\n\n\n\n\n```python\ndef Hamiltonian_str_convert(qubit_op):\n '''\n Convert the Hamiltonian information provided above into Pauli strings supported by Paddle Quantum\n\n H = [[1.0, \"z0,x1\"], [-1.0, \"y0,z1\"], ...]\n '''\n info_dic = qubit_op.terms\n \n def process_tuple(tup):\n if len(tup) == 0:\n return 'i0'\n else:\n res = ''\n for ele in tup:\n res += ele[1].lower()\n res += str(ele[0])\n res += ','\n return res[:-1]\n H_info = []\n \n for key, value in qubit_op.terms.items():\n H_info.append([value.real, process_tuple(key)])\n \n return H_info\n\nif sysStr in ('Linux', 'Darwin'):\n Hamiltonian = Hamiltonian_str_convert(qubit_op)\n```\n\n### Building QNN and trial wave function\n\nTo implement VQE, we firstly need to design a quantum neural network QNN to prepare the wave function ansatz $|\\Psi(\\boldsymbol\\theta)\\rangle$. Here, we provide a 4-qubit quantum circuit template with a depth of $D$ blocks. The dotted frame in the figure below denotes a single block:\n\n\n\n\nNext, we use the `UAnsatz` class and the built-in `real_entangled_layer(theta, D)` circuit template in Paddle Quantum to realize this QNN.\n\n\n\n\n```python\ndef U_theta(theta, Hamiltonian, N, D):\n \"\"\"\n Quantum Neural Network\n \"\"\"\n \n # Initialize the quantum neural network according to the number of qubits N\n cir = UAnsatz(N)\n \n # Built-in {R_y + CNOT} circuit template\n cir.real_entangled_layer(theta[:D], D)\n \n # Lay R_y gates in the last row\n for i in range(N):\n cir.ry(theta=theta[D][i][0], which_qubit=i)\n \n # The quantum neural network acts on the default initial state |0000>\n cir.run_state_vector()\n \n # Calculate the expected value of a given Hamiltonian\n expectation_val = cir.expecval(Hamiltonian)\n\n return expectation_val, cir\n```\n\n### Setting up the loss function and model\n\nNow that we have the target Hamiltonian and QNN, we will further define the training model and loss function. By applying the QNN $U(\\theta)$ on the initial state $|0..0\\rangle$, we get the output state $|\\psi(\\boldsymbol\\theta)\\rangle $. Then, the loss function to be minimized is the expectation value, \n\n\n$$\n\\min_{\\boldsymbol\\theta} \\mathcal{L}(\\boldsymbol \\theta) = \\min_{\\boldsymbol\\theta} \\langle \\Psi(\\boldsymbol\\theta)|H |\\Psi(\\boldsymbol\\theta)\\rangle\n= \\min_{\\boldsymbol\\theta} \\sum_k c_k~\\langle \\Psi(\\boldsymbol\\theta)| \\bigotimes_j \\sigma_j^{(k)}|\\Psi(\\boldsymbol\\theta)\\rangle.\n\\tag{8}\n$$\n\n\n```python\nclass StateNet(paddle.nn.Layer):\n\n def __init__(self, shape, dtype=\"float64\"):\n super(StateNet, self).__init__()\n \n # Initialize the theta parameter list and fill the initial value with a uniform distribution of [0, 2*pi]\n self.theta = self.create_parameter(shape=shape, \n default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2*PI),\n dtype=dtype, is_bias=False)\n \n # Define loss function and forward propagation mechanism\n def forward(self, N, D):\n \n # Calculate the loss function/expected value\n loss, cir = U_theta(self.theta, Hamiltonian, N, D)\n\n return loss, cir\n```\n\n### Hyper-parameters\n\nBefore training the QNN, we also need to set some training hyper-parameters, mainly the learning rate (LR), the number of iterations (ITR), and the depth (D) of repeated blocks. \n\n\n```python\nITR = 80 # Set the number of optimization iterations\nLR = 0.4 # Set the learning rate\nD = 2 # Set the depth of the repetitive calculation module in QNN\n```\n\n### Training\n\nAfter all the training model parameters are set, we convert the data into Tensor in the Paddle, and then train the quantum neural network. The results of the training process is stored in the summary_data file.\n\n\n\n```python\n# Determine the parameter dimension of the network\nnet = StateNet(shape=[D + 1, N, 1])\n\n\n# Generally speaking, we use Adam optimizer to obtain relatively good convergence,\n# You can change it to SGD or RMS prop.\nopt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n\n# Record optimization results\nsummary_iter, summary_loss = [], []\n\n# Optimization loop\nfor itr in range(1, ITR + 1):\n\n # Forward propagation to calculate loss function\n loss, cir = net(N, D)\n\n # Use back propagation to minimize the loss function\n loss.backward()\n opt.minimize(loss)\n opt.clear_grad()\n\n # Record optimization results\n summary_loss.append(loss.numpy())\n summary_iter.append(itr)\n\n # Print result\n if itr % 20 == 0:\n print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n print(\"iter:\", itr, \"Ground state energy:\", \"%.4f Ha\" \n % loss.numpy())\n if itr == ITR:\n print(\"\\nThe trained circuit:\")\n print(cir)\n\n# Save the training results to the output folder\nos.makedirs(\"output\", exist_ok=True)\nsavez(\"./output/summary_data\", iter = summary_iter, \n energy=summary_loss)\n```\n\n iter: 20 loss: -1.0687\n iter: 20 Ground state energy: -1.0687 Ha\n iter: 40 loss: -1.1313\n iter: 40 Ground state energy: -1.1313 Ha\n iter: 60 loss: -1.1355\n iter: 60 Ground state energy: -1.1355 Ha\n iter: 80 loss: -1.1360\n iter: 80 Ground state energy: -1.1360 Ha\n \n The trained circuit:\n --Ry(1.557)----*--------------X----Ry(1.578)----*--------------X----Ry(3.142)--\n | | | | \n --Ry(1.571)----X----*---------|----Ry(4.916)----X----*---------|----Ry(1.390)--\n | | | | \n --Ry(2.972)---------X----*----|----Ry(7.847)---------X----*----|----Ry(3.104)--\n | | | | \n --Ry(4.663)--------------X----*----Ry(1.577)--------------X----*----Ry(3.147)--\n \n\n\n### Benchmarking\nWe have now completed the training of the quantum neural network, and the estimated value of the ground state energy obtained is $E_0 \\approx -1.1361$ Hartree, we compare it with the theoretical value $E_0 = -1.13618$ to benchmark our model. The estimation obtained with VQE agree with a full configuration-interaction (FCI) calculation within chemical accuracy $\\varepsilon = 1.6 \\times 10^{-3}$ Hartree.\n\n\n\n\n```python\nresult = numpy.load('./output/summary_data.npz')\n\neig_val, eig_state = numpy.linalg.eig(\n pauli_str_to_matrix(Hamiltonian, N))\nmin_eig_H = numpy.min(eig_val.real)\nmin_loss = numpy.ones([len(result['iter'])]) * min_eig_H\n\nplt.figure(1)\nfunc1, = plt.plot(result['iter'], result['energy'], \n alpha=0.7, marker='', linestyle=\"-\", color='r')\nfunc_min, = plt.plot(result['iter'], min_loss, \n alpha=0.7, marker='', linestyle=\":\", color='b')\nplt.xlabel('Number of iteration')\nplt.ylabel('Energy (Ha)')\n\nplt.legend(handles=[\n func1,\n func_min\n],\n labels=[\n r'$\\left\\langle {\\psi \\left( {\\theta } \\right)} '\n r'\\right|H\\left| {\\psi \\left( {\\theta } \\right)} \\right\\rangle $',\n 'Ground-state energy',\n ], loc='best')\n\n#plt.savefig(\"vqe.png\", bbox_inches='tight', dpi=300)\nplt.show()\n```\n\n## Determining the interatomic distance\n\nRecall the above calculation is done with an interatomic distance $d = 74$ pm between two hydrogen atoms. Another interesting aspect we can try with VQE is determining the true interatomic distance by modifying the `h2.xyz` file. The results are summarize in figure below,\n\n\n\nThe lowest value is found around $d = 74$ pm (1 pm = $1\\times 10^{-12}$m), which is consistent with the [experimental data](https://cccbdb.nist.gov/exp2x.asp?casno=1333740&charge=0) $d_{exp} (H_2) = 74.14$ pm.\n\n_______\n\n## References\n\n[1] Cao, Yudong, et al. Quantum Chemistry in the Age of Quantum Computing. [Chemical reviews 119.19 (2019): 10856-10915.](https://pubs.acs.org/doi/10.1021/acs.chemrev.8b00803)\n\n[2] McArdle, Sam, et al. Quantum computational chemistry. [Reviews of Modern Physics 92.1 (2020): 015003.](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.92.015003)\n\n\n[3] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)\n\n[4] Moll, Nikolaj, et al. Quantum optimization using variational algorithms on near-term quantum devices. [Quantum Science and Technology 3.3 (2018): 030503.](https://iopscience.iop.org/article/10.1088/2058-9565/aab822)\n\n[5] Helgaker, Trygve, Poul Jorgensen, and Jeppe Olsen. Molecular electronic-structure theory. John Wiley & Sons, 2014.\n\n[6] Dirac, Paul Adrien Maurice. Quantum mechanics of many-electron systems. [Proceedings of the Royal Society of London. Series A, Containing Papers of a Mathematical and Physical Character 123.792 (1929): 714-733.](https://royalsocietypublishing.org/doi/10.1098/rspa.1929.0094)\n\n[7] Szabo, Attila, and Neil S. Ostlund. Modern quantum chemistry: introduction to advanced electronic structure theory. Courier Corporation, 2012.\n", "meta": {"hexsha": "1278c20659b6fa8ca1f4e210211beca13e3fe379", "size": 44547, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial/quantum_simulation/VQE_EN.ipynb", "max_stars_repo_name": "rickyHong/Quantum-1", "max_stars_repo_head_hexsha": "73973c92d540b9e83b50c66860537aef0590a1a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial/quantum_simulation/VQE_EN.ipynb", "max_issues_repo_name": "rickyHong/Quantum-1", "max_issues_repo_head_hexsha": "73973c92d540b9e83b50c66860537aef0590a1a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/quantum_simulation/VQE_EN.ipynb", "max_forks_repo_name": "rickyHong/Quantum-1", "max_forks_repo_head_hexsha": "73973c92d540b9e83b50c66860537aef0590a1a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 68.6394453005, "max_line_length": 15476, "alphanum_fraction": 0.7209239679, "converted": true, "num_tokens": 5611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.3243345632713044}} {"text": "# Deep Reinforcement Learning for the CartPole Environment\n\n\n\n```python\n# Install packages\nimport gym\nimport copy\nimport torch\nfrom torch.autograd import Variable\nimport random\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom IPython.display import clear_output\nimport math\nimport torchvision.transforms as T\nimport numpy as np\n\nimport time\n```\n\n## Environment\n\nThe CartPole environment consists of a pole which moves along a frictionless track. The system is controlled by applying a force of +1 or -1 to the cart. The pendulum starts upright, and the goal is to prevent it from falling over. The state space is represented by four values: cart position, cart velocity, pole angle, and the velocity of the tip of the pole. The action space consists of two actions: moving left or moving right. A reward of +1 is provided for every timestep that the pole remains upright. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. \n\nSource: [https://gym.openai.com/envs/CartPole-v1/](Open AI Gym). \n\nThe cell below plots a bunch of example frames from the environment.\n\n\n```python\nenv = gym.envs.make(\"CartPole-v1\")\n```\n\n\n```python\n# Demonstration\nenv = gym.envs.make(\"CartPole-v1\")\n\n\ndef get_screen():\n ''' Extract one step of the simulation.'''\n screen = env.render(mode='rgb_array').transpose((2, 0, 1))\n screen = np.ascontiguousarray(screen, dtype=np.float32) / 255.\n return torch.from_numpy(screen)\n\n# Speify the number of simulation steps\nnum_steps = 2\n\n# Show several steps\nfor i in range(num_steps):\n clear_output(wait=True)\n env.reset()\n plt.figure()\n plt.imshow(get_screen().cpu().permute(1, 2, 0).numpy(),\n interpolation='none')\n plt.title('CartPole-v0 Environment')\n plt.xticks([])\n plt.yticks([])\n plt.show()\n```\n\n## Plotting Function\n\nThis function will make it possible to analyze how the agent learns over time. The resulting plot consists of two subplots. The first one plots the total reward the agent accumulates over time, while the other plot shows a histogram of the agent's total rewards for the last 50 episodes. \n\n\n```python\ndef plot_res(values, title=''): \n ''' Plot the reward curve and histogram of results over time.'''\n # Update the window after each episode\n clear_output(wait=True)\n \n # Define the figure\n f, ax = plt.subplots(nrows=1, ncols=2, figsize=(12,5))\n f.suptitle(title)\n ax[0].plot(values, label='score per run')\n ax[0].axhline(195, c='red',ls='--', label='goal')\n ax[0].set_xlabel('Episodes')\n ax[0].set_ylabel('Reward')\n x = range(len(values))\n ax[0].legend()\n # Calculate the trend\n try:\n z = np.polyfit(x, values, 1)\n p = np.poly1d(z)\n ax[0].plot(x,p(x),\"--\", label='trend')\n except:\n print('')\n \n # Plot the histogram of results\n ax[1].hist(values[-50:])\n ax[1].axvline(195, c='red', label='goal')\n ax[1].set_xlabel('Scores per Last 50 Episodes')\n ax[1].set_ylabel('Frequency')\n ax[1].legend()\n plt.show()\n```\n\n## Random Search\n\nBefore implementing any deep learning approaches, I wrote a simple strategy where the action is sampled randomly from the action space. This approach will serve as a baseline for other strategies and will make it easier to understand how to work with the agent using the Open AI Gym environment.\n\n\n```python\ndef random_search(env, episodes, \n title='Random Strategy'):\n \"\"\" Random search strategy implementation.\"\"\"\n final = []\n for episode in range(episodes):\n state = env.reset()\n done = False\n total = 0\n while not done:\n # Sample random actions\n action = env.action_space.sample()\n # Take action and extract results\n next_state, reward, done, _ = env.step(action)\n # Update reward\n total += reward\n if done:\n break\n # Add to the final reward\n final.append(total)\n plot_res(final,title)\n return final\n```\n\n\n```python\n# Get random search results\nepisodes = 30\nrandom_s = random_search(env, episodes)\n```\n\nThe plot above presents the random strategy. As expected, it's impossible to solve the environment using this approach. The agent is not learning from their experience. Despite being lucky sometimes (getting a reward of almost 75), their average performance is as low as 10 steps.\n\n## Deep Q Learning\n\nThe main idea behind Q-learning is that we have a function $Q: State \\times Action \\rightarrow \\mathbb{R}$, which can tell the agent what actions will result in what rewards. If we know the value of Q, it is possible to construct a policy that maximizes rewards:\n\n\\begin{align}\\pi(s) = \\arg\\!\\max_a \\ Q(s, a)\\end{align}\n\nHowever, in the real world, we don't have access to full information, that's why we need to come up with ways of approximating Q. One traditional method is creating a lookup table where the values of Q are updated after each of the agent's actions. However, this approach is slow and does not scale to large action and state spaces. Since neural networks are universal function approximators, I will train a network that can approximate $Q$.\n\nThe DQL class implementation consists of a simple neural network implemented in PyTorch that has two main methods--predict and update. The network takes the agent's state as an input and returns the Q values for each of the actions. The maximum Q value is selected by the agent to perform the next action.\n\n\n\n```python\nclass DQN():\n ''' Deep Q Neural Network class. '''\n def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05):\n self.criterion = torch.nn.MSELoss()\n self.model = torch.nn.Sequential(\n torch.nn.Linear(state_dim, hidden_dim),\n torch.nn.LeakyReLU(),\n torch.nn.Linear(hidden_dim, hidden_dim*2),\n torch.nn.LeakyReLU(),\n torch.nn.Linear(hidden_dim*2, action_dim)\n )\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr)\n\n\n\n def update(self, state, y):\n \"\"\"Update the weights of the network given a training sample. \"\"\"\n y_pred = self.model(torch.Tensor(state))\n loss = self.criterion(y_pred, Variable(torch.Tensor(y)))\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n\n def predict(self, state):\n \"\"\" Compute Q values for all actions using the DQL. \"\"\"\n with torch.no_grad():\n return self.model(torch.Tensor(state))\n```\n\nThe q_learning function is the main loop for all the algorithms that follow. \nIt has many parameters, namely:\n\n- Env represents the Open Ai Gym environment that we want to solve (CartPole.)\n- Episodes stand for the number of games we want to play (from the beginning until the end.)\n- Gamma is a discounting factor that is multiplied by future rewards to dampen these rewards' effect on the agent. It is designed to make future rewards worth less than immediate rewards.\n- Epsilon represents the proportion of random actions relative to actions that are informed by existing \"knowledge\" that the agent accumulates during the episode. Before playing the game, the agent doesn't have any experience, so it is common to set epsilon to higher values and then gradually decrease its value.\n- Eps_decay parameter indicates the speed at which the epsilon decreases as the agent learns. 0.99 comes from the original DQN paper.\n\nI will explain other parameters later on when we will get to the corresponding agents.\nThe most straightforward agent updates its Q-values based on its most recent observation. It doesn't have any memory, but it learns by first exploring the environment and the gradually decreasing its epsilon value to make informed decisions:\n\n\n```python\ndef q_learning(env, model, episodes, gamma=0.9, \n epsilon=0.3, eps_decay=0.99,\n replay=False, replay_size=20, \n title = 'DQL', double=False, \n n_update=10, soft=False, verbose=True):\n \"\"\"Deep Q Learning algorithm using the DQN. \"\"\"\n final = []\n memory = []\n episode_i=0\n sum_total_replay_time=0\n\n _max = [0.0, 0.0, 0.0, 0.0]\n\n for episode in range(episodes):\n episode_i+=1\n if double and not soft:\n # Update target network every n_update steps\n if episode % n_update == 0:\n model.target_update()\n if double and soft:\n model.target_update()\n \n # Reset state\n state = env.reset()\n done = False\n total = 0\n \n while not done:\n # Implement greedy search policy to explore the state space\n if random.random() < epsilon:\n action = env.action_space.sample()\n else:\n q_values = model.predict(state)\n action = torch.argmax(q_values).item()\n \n # Take action and add reward to total\n next_state, reward, done, _ = env.step(action)\n \n # Update total and memory\n total += reward\n memory.append((state, action, next_state, reward, done))\n q_values = model.predict(state).tolist()\n \n if done:\n if not replay:\n q_values[action] = reward\n # Update network weights\n model.update(state, q_values)\n break\n\n if replay:\n t0=time.time()\n # Update network weights using replay memory\n model.replay(memory, replay_size, gamma)\n t1=time.time()\n sum_total_replay_time+=(t1-t0)\n else: \n # Update network weights using the last step only\n q_values_next = model.predict(next_state)\n q_values[action] = reward + gamma * torch.max(q_values_next).item()\n model.update(state, q_values)\n\n for _i in range(len(_max)):\n if np.abs(state[i]) > _max[i]:\n _max[i] = np.abs(state[i])\n\n\n state = next_state\n \n \n # Update epsilon\n epsilon = max(epsilon * eps_decay, 0.01)\n final.append(total)\n plot_res(final, title)\n \n if verbose:\n print(\"episode: {}, total reward: {}\".format(episode_i, total))\n if replay:\n print(\"Average replay time:\", sum_total_replay_time/episode_i)\n \n print(_max)\n return final\n```\n\n### Parameters\n\n\n```python\n# Number of states\nn_state = env.observation_space.shape[0]\n# Number of actions\nn_action = env.action_space.n\n# Number of episodes\nepisodes = 150\n# Number of hidden nodes in the DQN\nn_hidden = 50\n# Learning rate\nlr = 0.001\n```\n\n\n```python\n# Get DQN results\nsimple_dqn = DQN(n_state, n_action, n_hidden, lr)\nsimple = q_learning(env, simple_dqn, episodes, gamma=.9, epsilon=0.3)\n```\n\nThe graph above shows that the performance of the agent has significantly improved. It got to 175 steps, which, as we've seen before, is impossible for a random agent. The trend line is also positive, and we can see that the performance increases over time. At the same time, the agent didn't manage to get above the goal line after 150 epochs, and its average performance is still around 15 steps, so there is definitely enough room for improvement.\n\n## Replay\n\nThe approximation of Q using one sample at a time is not very effective. The graph above is a nice illustration of that. The network managed to achieve a much better performance compared to a random agent. However, it couldn't get to the threshold line of 195 steps. I implemented experience replay to improve network stability and make sure previous experiences are not discarded but used in training.\n\nExperience replay stores the agent's experiences in memory. Batches of experiences are randomly sampled from memory and are used to train the neural network. Such learning consists of two phases--gaining experience and updating the model. The size of the replay controls the number of experiences that are used for the network update. Memory is an array that stores the agent's state, reward, and action, as well as whether the action finished the game and the next state.\n\n\n```python\n# Expand DQL class with a replay function.\nclass DQN_replay(DQN):\n #old replay function\n #def replay(self, memory, size, gamma=0.9):\n #\"\"\" Add experience replay to the DQN network class. \"\"\"\n # Make sure the memory is big enough\n #if len(memory) >= size:\n #states = []\n #targets = []\n # Sample a batch of experiences from the agent's memory\n #batch = random.sample(memory, size)\n \n # Extract information from the data\n #for state, action, next_state, reward, done in batch:\n #states.append(state)\n # Predict q_values\n #q_values = self.predict(state).tolist()\n #if done:\n #q_values[action] = reward\n #else:\n #q_values_next = self.predict(next_state)\n #q_values[action] = reward + gamma * torch.max(q_values_next).item()\n \n #targets.append(q_values)\n\n #self.update(states, targets)\n \n #new replay function\n def replay(self, memory, size, gamma=0.9):\n \"\"\"New replay function\"\"\"\n #Try to improve replay speed\n if len(memory)>=size:\n batch = random.sample(memory,size)\n batch_t = list(map(list, zip(*batch))) #Transpose batch list\n states = batch_t[0]\n actions = batch_t[1]\n next_states = batch_t[2]\n rewards = batch_t[3]\n is_dones = batch_t[4]\n \n states = torch.Tensor(states)\n actions_tensor = torch.Tensor(actions)\n next_states = torch.Tensor(next_states)\n rewards = torch.Tensor(rewards)\n is_dones_tensor = torch.Tensor(is_dones)\n \n is_dones_indices = torch.where(is_dones_tensor==True)[0]\n \n all_q_values = self.model(states) # predicted q_values of all states\n all_q_values_next = self.model(next_states)\n #Update q values\n all_q_values[range(len(all_q_values)),actions]=rewards+gamma*torch.max(all_q_values_next, axis=1).values\n all_q_values[is_dones_indices.tolist(), actions_tensor[is_dones].tolist()]=rewards[is_dones_indices.tolist()]\n \n \n self.update(states.tolist(), all_q_values.tolist())\n```\n\n### replay using old replay function\n\n\n```python\n# Get replay results\ndqn_replay = DQN_replay(n_state, n_action, n_hidden, lr)\nreplay = q_learning(env, dqn_replay, \n episodes, gamma=.9, \n epsilon=0.2, replay=True, \n title='DQL with Replay')\n```\n\n### replay using new replay function\n\n\n```python\n# Get replay results\ndqn_replay = DQN_replay(n_state, n_action, n_hidden, lr)\nreplay = q_learning(env, dqn_replay, \n episodes, gamma=.9, \n epsilon=0.2, replay=True, \n title='DQL with Replay')\n```\n\nAs expected, the neural network with the replay seems to be much more robust and smart compared to its counterpart that only remembers the last action. After approximately 60 episodes, the agent managed to achieve the winning threshold and remain at this level. I also managed to achieve the highest reward possible--500.\n\n## Double Q Learning\n\nTraditional Deep Q Learning tends to overestimate the reward, which leads to unstable training and lower quality policy. Let's consider the equation for the Q value:\n\nThe last part of the equation takes the estimate of the maximum value. This procedure results in systematic overestimation, which introduces a maximization bias. Since Q-learning involves learning estimates from estimates, such overestimation is especially worrying.\n\nTo avoid such a situation, I will define a new target network. The Q values will be taken from this new network, which is meant to reflect the state of the main DQN. However, it doesn't have identical weights because it's only updated after a certain number of episodes. This idea has been first introduced in Hasselt et al., 2015.\nThe addition of the target network might slow down the training since the target network is not continuously updated. However, it should have a more robust performance over time.\n\nn_update parameter specifies the interval, after which the target network should be updated.\n\n\n```python\nclass DQN_double(DQN):\n def __init__(self, state_dim, action_dim, hidden_dim, lr):\n super().__init__(state_dim, action_dim, hidden_dim, lr)\n self.target = copy.deepcopy(self.model)\n \n def target_predict(self, s):\n ''' Use target network to make predicitons.'''\n with torch.no_grad():\n return self.target(torch.Tensor(s))\n \n def target_update(self):\n ''' Update target network with the model weights.'''\n self.target.load_state_dict(self.model.state_dict())\n \n def replay(self, memory, size, gamma=1.0):\n ''' Add experience replay to the DQL network class.'''\n if len(memory) >= size:\n # Sample experiences from the agent's memory\n data = random.sample(memory, size)\n states = []\n targets = []\n # Extract datapoints from the data\n for state, action, next_state, reward, done in data:\n states.append(state)\n q_values = self.predict(state).tolist()\n if done:\n q_values[action] = reward\n else:\n # The only difference between the simple replay is in this line\n # It ensures that next q values are predicted with the target network.\n q_values_next = self.target_predict(next_state)\n q_values[action] = reward + gamma * torch.max(q_values_next).item()\n\n targets.append(q_values)\n\n self.update(states, targets)\n```\n\n\n```python\n# Get replay results\ndqn_double = DQN_double(n_state, n_action, n_hidden, lr)\ndouble = q_learning(env, dqn_double, episodes, gamma=.9, \n epsilon=0.2, replay=True, double=True,\n title='Double DQL with Replay', n_update=10)\n\n```\n\nDouble DQL with replay has outperformed the previous version and has consistently performed above 300 steps. The performance also seems to be a bit more stable, thanks to the separation of action selection and evaluation. Finally, let's explore the last modification to the DQL agent.\n\n## Soft Target Update\nThe method used to update the target network implemented above was introduced in the original DQN paper. In this section, we will explore another well-established method of updating the target network weights. Instead of updating weights after a certain number of steps, we will incrementally update the target network after every run using the following formula:\n\ntarget_weights = target_weights * (1-TAU) + model_weights * TAU\n\nwhere 0 < TAU < 1\n\nThis method of updating the target network is known as “soft target network updates” and was introduced in Lillicrap et al., 2016. Method implementation is shown below:\n\n\n```python\nclass DQN_double_soft(DQN_double):\n def target_update(self, TAU=0.1):\n ''' Update the targer gradually. '''\n # Extract parameters \n model_params = self.model.named_parameters()\n target_params = self.target.named_parameters()\n \n updated_params = dict(target_params)\n\n for model_name, model_param in model_params:\n if model_name in target_params:\n # Update parameter\n updated_params[model_name].data.copy_((TAU)*model_param.data + (1-TAU)*target_params[model_param].data)\n\n self.target.load_state_dict(updated_params)\n```\n\n\n```python\ndqn_double_soft = DQN_double_soft(n_state, n_action, n_hidden, lr)\ndouble = q_learning(env, dqn_double_soft, episodes, gamma=.9, \n epsilon=0.2, replay=True, double=True,\n title='Double DQL with Replay', n_update=10, soft=True)\n```\n\nThe network with soft target updates performed quite well. However, it doesn't seem to be better than hard weight updates after a certain number of steps. \n\n## Conclusion\n\nThe implementation of the experience replay and the target network have significantly improved the performance of a Deep Q Learning agent in the Open AI CartPole environment. Some other modifications to the agent, such as Dueling Network Architectures (Wang et al., 2015), can be added to this implementation to improve the agent's performance. The algorithm is also generalizable to other environments. Thus, it's possible to test how well it performs on other tasks. \n\n## References:\n\n(1) Reinforcement Q-Learning from Scratch in Python with OpenAI Gym. (2019). Learndatasci.com. Retrieved 9 December 2019, from https://www.learndatasci.com/tutorials/reinforcement-q-learning-scratch-python-openai-gym/\n\n(2) Paszke, A., (2019). Reinforcement Learning (DQN) tutorial. Retrieved from: https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html\n\n(3) Lillicrap, T. P., Hunt, J. J., Pritzel, A., Heess, N., Erez, T., Tassa, Y., ... & Wierstra, D. (2015). Continuous control with deep reinforcement learning. arXiv preprint arXiv:1509.02971.\n\n(4) Van Hasselt, H., Guez, A., & Silver, D. (2016, March). Deep reinforcement learning with double q-learning. In Thirtieth AAAI conference on artificial intelligence.\n\n(5) Wang, Z., Schaul, T., Hessel, M., Van Hasselt, H., Lanctot, M., & De Freitas, N. (2015). Dueling network architectures for deep reinforcement learning. arXiv preprint arXiv:1511.06581.\n\n(6) Double DQN Implementation to Solve OpenAI Gym’s CartPole v-0. (2019). Medium. Retrieved 20 December 2019, from https://medium.com/@leosimmons/double-dqn-implementation-to-solve-openai-gyms-cartpole-v-0-df554cd0614d\n", "meta": {"hexsha": "0ea8f395ccd9362bc1d088600da261898563a510", "size": 622732, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "DQL_CartPole.ipynb", "max_stars_repo_name": "michelangelo21/QHack-open_hackaton-QUBIT", "max_stars_repo_head_hexsha": "49043e78892985877cea78e371bf989b25b833d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-15T21:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T21:07:07.000Z", "max_issues_repo_path": "DQL_CartPole.ipynb", "max_issues_repo_name": "michelangelo21/QHack-open_hackaton-QUBIT", "max_issues_repo_head_hexsha": "49043e78892985877cea78e371bf989b25b833d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DQL_CartPole.ipynb", "max_forks_repo_name": "michelangelo21/QHack-open_hackaton-QUBIT", "max_forks_repo_head_hexsha": "49043e78892985877cea78e371bf989b25b833d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 761.2860635697, "max_line_length": 58048, "alphanum_fraction": 0.793766821, "converted": true, "num_tokens": 4929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.32388227054517593}} {"text": "```python\n%load_ext Cython\n```\n\n /home/rotis/anaconda/envs/calphadpy3/lib/python3.5/site-packages/Cython/Distutils/old_build_ext.py:30: UserWarning: Cython.Distutils.old_build_ext does not properly handle dependencies and is deprecated.\n \"Cython.Distutils.old_build_ext does not properly handle dependencies \"\n\n\n\n```cython\n%%cython\nfrom pycalphad.core.rksum import RedlichKisterSum\nfrom pycalphad import Database\ncimport numpy as np\nimport numpy as np\nfrom tinydb import where\nfrom sympy import Symbol\n\ncdef np.ndarray[ndim=1, dtype=np.float64_t] _eval_rk_matrix_gradient(double[:,:] coef_mat, double[:,:] symbol_mat,\n double[:] eval_row, double[:] parameters):\n cdef np.ndarray[ndim=1, dtype=np.float64_t] out = np.zeros(eval_row.shape[0]-2)\n cdef double result = 0\n cdef double prod_result\n cdef int row_idx1 = 0\n cdef int row_idx2 = 0\n cdef int col_idx = 0\n cdef int dof_idx\n # eval_row order: P,T,ln(P),ln(T),y...\n # dof order: P,T,y...\n # coef_mat order: low_temp,high_temp,P,T,ln(P),ln(T),y...,constant_term,parameter_value\n for dof_idx in range(eval_row.shape[0]-2):\n if coef_mat.shape[1] > 0:\n for row_idx1 in range(coef_mat.shape[0]):\n if (eval_row[1] >= coef_mat[row_idx1, 0]) and (eval_row[1] < coef_mat[row_idx1, 1]):\n if dof_idx < 2:\n # special handling for state variables since they also can have a ln term\n if coef_mat[row_idx1, 2+dof_idx] != 0:\n prod_result = coef_mat[row_idx1, coef_mat.shape[1]-2] * coef_mat[row_idx1, coef_mat.shape[1]-1]\n for col_idx in range(coef_mat.shape[1]-4):\n if col_idx == dof_idx:\n prod_result *= (eval_row[col_idx]**(coef_mat[row_idx1, 2+col_idx]-1) * eval_row[2+col_idx]**(coef_mat[row_idx1, 4+col_idx]-1) * (coef_mat[row_idx1, 4+col_idx]+coef_mat[row_idx1, 2+col_idx]*(eval_row[2+col_idx])))\n else:\n prod_result *= (eval_row[col_idx] ** coef_mat[row_idx1, 2+col_idx])\n out[dof_idx] += prod_result\n else:\n if coef_mat[row_idx1, 4+dof_idx] != 0:\n prod_result = coef_mat[row_idx1, coef_mat.shape[1]-2] * coef_mat[row_idx1, coef_mat.shape[1]-1]\n for col_idx in range(coef_mat.shape[1]-4):\n if col_idx == 2+dof_idx:\n prod_result *= (coef_mat[row_idx1, 4+dof_idx] * eval_row[col_idx] ** (coef_mat[row_idx1, 2+col_idx] - 1))\n else:\n prod_result *= (eval_row[col_idx] ** coef_mat[row_idx1, 2+col_idx])\n out[dof_idx] += prod_result\n if symbol_mat.shape[1] > 0:\n for row_idx2 in range(symbol_mat.shape[0]):\n if (eval_row[1] >= symbol_mat[row_idx2, 0]) and (eval_row[1] < symbol_mat[row_idx2, 1]):\n if dof_idx < 2:\n # special handling for state variables since they also can have a ln term\n if coef_mat[row_idx2, 2+dof_idx] != 0:\n prod_result = coef_mat[row_idx2, coef_mat.shape[1]-2] * parameters[symbol_mat[row_idx2, symbol_mat.shape[1]-1]]\n for col_idx in range(coef_mat.shape[1]-4):\n if col_idx == dof_idx:\n prod_result *= (eval_row[col_idx]**(coef_mat[row_idx1, 2+col_idx]-1) * eval_row[2+col_idx]**(coef_mat[row_idx1, 4+col_idx]-1) * (coef_mat[row_idx1, 4+col_idx]+coef_mat[row_idx1, 2+col_idx]*(eval_row[2+col_idx])))\n else:\n prod_result *= (eval_row[col_idx] ** coef_mat[row_idx1, 2+col_idx])\n out[dof_idx] += prod_result\n else:\n if coef_mat[row_idx1, 4+dof_idx] != 0:\n prod_result = coef_mat[row_idx2, coef_mat.shape[1]-2] * parameters[symbol_mat[row_idx2, symbol_mat.shape[1]-1]]\n for col_idx in range(coef_mat.shape[1]-4):\n if col_idx == 2+dof_idx:\n prod_result *= (coef_mat[row_idx2, 4+dof_idx] * eval_row[col_idx] ** (coef_mat[row_idx2, 2+col_idx] - 1))\n else:\n prod_result *= (eval_row[col_idx] ** coef_mat[row_idx2, 2+col_idx])\n out[dof_idx] += prod_result\n return out\n\ndbf = Database('alcocr-sandbox.tdb')\nparam_query = (\n (where('phase_name') == 'LIQUID') & \\\n (where('parameter_type') == \"G\")\n)\nparameters = {}\nall_symbols = dbf.symbols.copy()\n# Convert string symbol names to sympy Symbol objects\n# This makes xreplace work with the symbols dict\nall_symbols = dict([(Symbol(s), val) for s, val in all_symbols.items()])\nfor param in parameters.keys():\n all_symbols.pop(param, None)\nrks = RedlichKisterSum(['AL','CO','CR','VA'], dbf.phases['LIQUID'], dbf.search, param_query, list(parameters.keys()), all_symbols)\nexx = _eval_rk_matrix_gradient(rks.output_matrix[2:4,:], np.array([[]]),\n np.array([1013235, 300, np.log(101325), np.log(300), 0.3, 0.3, 0.4]), np.array([]))\nprint(exx)\n```\n\n [ 0.00000000e+00 -3.55256010e+00 -1.15287101e+04 0.00000000e+00\n 0.00000000e+00]\n\n\n\n```python\nrks.output_matrix[2:4,:]\n```\n\n\n\n\n array([[ 2.98150000e+02, 9.33600000e+02, 0.00000000e+00,\n 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 1.00000000e+00, -1.18418670e+01],\n [ 2.98150000e+02, 7.00000000e+02, 0.00000000e+00,\n 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 1.00000000e+00, 0.00000000e+00, 0.00000000e+00,\n 1.00000000e+00, -7.97615000e+03]])\n\n\n\n\n```python\n-1.18418670e01 * 300 + -7.97615000e03\n```\n\n\n\n\n -11528.7101\n\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "4df3cec882f53859115133f68cb6e395c9789aa9", "size": 8635, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "RKSum-gradient.ipynb", "max_stars_repo_name": "richardotis/pycalphad-sandbox", "max_stars_repo_head_hexsha": "43d8786eee8f279266497e9c5f4630d19c893092", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-03-08T18:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-08T18:21:30.000Z", "max_issues_repo_path": "RKSum-gradient.ipynb", "max_issues_repo_name": "richardotis/pycalphad-sandbox", "max_issues_repo_head_hexsha": "43d8786eee8f279266497e9c5f4630d19c893092", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RKSum-gradient.ipynb", "max_forks_repo_name": "richardotis/pycalphad-sandbox", "max_forks_repo_head_hexsha": "43d8786eee8f279266497e9c5f4630d19c893092", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-11-03T01:31:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-03T01:31:57.000Z", "avg_line_length": 41.5144230769, "max_line_length": 257, "alphanum_fraction": 0.4971627099, "converted": true, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.32387815017298455}} {"text": "# Quantum pipeline using t|ket> backend\nThis performs a shots-based simulation.\n\n\n```python\nimport numpy as np\n\ndef read_data(filename):\n labels, sentences = [], []\n with open(filename) as f:\n for line in f:\n labels.append([1, 0] if line[0] == '1' else [0, 1])\n sentences.append(line[1:].strip())\n return np.array(labels), sentences\n\n\ntrain_labels, train_data = read_data('datasets/mc_train_data.txt')\ndev_labels, dev_data = read_data('datasets/mc_dev_data.txt')\ntest_labels, test_data = read_data('datasets/mc_test_data.txt')\n```\n\n### Create diagrams\n\n\n```python\nfrom lambeq.ccg2discocat import DepCCGParser\n\nreader = DepCCGParser(possible_root_cats=['S[dcl]'])\n\nraw_train_diagrams = reader.sentences2diagrams(train_data)\nraw_dev_diagrams = reader.sentences2diagrams(dev_data)\nraw_test_diagrams = reader.sentences2diagrams(test_data)\n```\n\n\n```python\nfrom discopy.rigid import Id\n\n\ndef remove_cups(diagram):\n # Remove cups to reduce post-selection in the circuit, for faster execution\n\n diags = []\n for box, offset in zip(diagram.boxes, diagram.offsets):\n if not box.dom: # word box\n diags.insert(offset, box)\n else: # cup (the only other type of box in these diagrams)\n i = 0\n off = offset\n while off != len(diags[i].cod) - 1:\n assert off > 0\n off -= len(diags[i].cod)\n i += 1\n left, right = diags[i:i+2]\n \n if len(left.cod) == 1:\n new_diag = right >> (left.r.dagger() @ Id(right.cod[1:]))\n else:\n assert len(right.cod) == 1\n new_diag = left >> (Id(left.cod[:-1]) @ right.l.dagger())\n\n diags[i:i+2] = [new_diag]\n\n assert len(diags) == 1\n return diags[0]\n\n\ntrain_diagrams = [remove_cups(diagram) for diagram in raw_train_diagrams]\ndev_diagrams = [remove_cups(diagram) for diagram in raw_dev_diagrams]\ntest_diagrams = [remove_cups(diagram) for diagram in raw_test_diagrams]\n\ntrain_diagrams[0].draw()\n```\n\n### Create circuits\n\n\n```python\nfrom lambeq.circuit import IQPAnsatz\nfrom lambeq.core.types import AtomicType\n\nansatz = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1},\n n_layers=1, n_single_qubit_params=3)\n\ntrain_circuits = [ansatz(diagram) for diagram in train_diagrams]\ndev_circuits = [ansatz(diagram) for diagram in dev_diagrams]\ntest_circuits = [ansatz(diagram) for diagram in test_diagrams]\n\ntrain_circuits[0].draw(figsize=(9, 12))\n```\n\n### Parameterise\n\n\n```python\nfrom sympy import default_sort_key\n\nall_circuits = train_circuits + dev_circuits + test_circuits\n\n# sort the symbols since they are returned as a set\nparameters = sorted(\n {s for circ in all_circuits for s in circ.free_symbols},\n key=default_sort_key)\n```\n\n\n```python\n## CONFIGURE BACKEND\n# This uses Qiskit, which requires installing `pytket-qiskit`.\n# For more information on how to use pytket with different backends, see:\n# https://cqcl.github.io/pytket/build/html/extensions/\n\n# Aer is a shots-based backend that is always available.\n\nfrom pytket.extensions.qiskit import AerBackend\nbackend = AerBackend()\n\n## Having an IBMQ account gives access to the IBM emulator for noisy simulations:\n#\n# from pytket.extensions.qiskit import IBMQEmulatorBackend\n# backend = IBMQEmulatorBackend('PLACEHOLDER')\n#\n## To use a real device:\n#\n# from pytket.extensions.qiskit import IBMQBackend\n# backend = IBMQBackend('PLACEHOLDER')\n\nbackend_config = {\n 'backend': backend,\n 'compilation': backend.default_compilation_pass(2),\n 'n_shots': 8192 # maximum recommended shots, reduces sampling error\n}\n```\n\n\n```python\nfrom discopy.quantum import Circuit, Id, Measure\n\n\ndef randint(rng, low=-1 << 63, high=1 << 63-1):\n return rng.integers(low, high)\n\n\ndef normalise(predictions):\n # apply smoothing to predictions\n predictions = np.abs(predictions) + 1e-9\n return predictions / predictions.sum()\n\n\ndef make_pred_fn(circuits, rng):\n measured_circuits = [c >> Id().tensor(*[Measure()] * len(c.cod)) for c in circuits]\n circuit_fns = [c.lambdify(*parameters) for c in measured_circuits]\n\n def predict(params):\n outputs = Circuit.eval(*(c_fn(*params) for c_fn in circuit_fns),\n **backend_config, seed=randint(rng))\n return np.array([normalise(output.array) for output in outputs])\n return predict\n\n\nSEED = 0\nrng = np.random.default_rng(SEED)\n\ntrain_pred_fn = make_pred_fn(train_circuits, rng)\ndev_pred_fn = make_pred_fn(dev_circuits, rng)\ntest_pred_fn = make_pred_fn(test_circuits, rng)\n```\n\n### Train\n\n\n```python\nfrom noisyopt import minimizeSPSA\n\ndef make_cost_fn(pred_fn, labels):\n def cost_fn(params, **kwargs):\n predictions = pred_fn(params)\n\n cost = -np.sum(labels * np.log(predictions)) / len(labels) # binary cross-entropy loss\n costs.append(cost)\n\n acc = np.sum(np.round(predictions) == labels) / len(labels) / 2 # half due to double-counting\n accuracies.append(acc)\n\n return cost\n\n costs, accuracies = [], []\n return cost_fn, costs, accuracies\n\n\ntrain_cost_fn, train_costs, train_accs = make_cost_fn(train_pred_fn, train_labels)\ndev_cost_fn, dev_costs, dev_accs = make_cost_fn(dev_pred_fn, dev_labels)\n\nx0 = np.array(rng.random(len(parameters)))\nnp.random.seed(SEED)\nresult = minimizeSPSA(train_cost_fn, x0=x0, a=0.2, c=0.06, niter=80, callback=dev_cost_fn)\n```\n\n### Show results\n\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(10, 6))\nax_tl.set_title('Training set')\nax_tr.set_title('Development set')\nax_bl.set_xlabel('Iterations')\nax_br.set_xlabel('Iterations')\nax_bl.set_ylabel('Accuracy')\nax_tl.set_ylabel('Loss')\n\ncolours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])\nax_tl.plot(train_costs[1::2], color=next(colours)) # training evaluates twice per iteration\nax_bl.plot(train_accs[1::2], color=next(colours)) # so take every other entry\nax_tr.plot(dev_costs, color=next(colours))\nax_br.plot(dev_accs, color=next(colours))\n\n# print test accuracy\ntest_cost_fn, _, test_accs = make_cost_fn(test_pred_fn, test_labels)\ntest_cost_fn(result.x)\nprint('Test accuracy:', test_accs[0])\n```\n", "meta": {"hexsha": "d2bf7a5245923bc5437f4c88ab5bce749fcd91d7", "size": 113454, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/examples/quantum_pipeline_tket.ipynb", "max_stars_repo_name": "kinianlo/lambeq", "max_stars_repo_head_hexsha": "86aedb24bf826c226f2845af4327cf616cd01a1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-12T23:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T23:45:12.000Z", "max_issues_repo_path": "docs/examples/quantum_pipeline_tket.ipynb", "max_issues_repo_name": "yliu9418/lambeq", "max_issues_repo_head_hexsha": "357fb893e01e2b41d7628ceaed265356702ca5fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/examples/quantum_pipeline_tket.ipynb", "max_forks_repo_name": "yliu9418/lambeq", "max_forks_repo_head_hexsha": "357fb893e01e2b41d7628ceaed265356702ca5fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 326.0172413793, "max_line_length": 53132, "alphanum_fraction": 0.9284555855, "converted": true, "num_tokens": 1665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3234914548933221}} {"text": "# Including clouds\n\n## Powerlaw cloud models\n\nLet's initialize an atmosphere in the usual way, see [\"Getting Started\"](getting_started.html):\n\n\n```python\nimport numpy as np\nfrom petitRADTRANS import Radtrans\n\natmosphere = Radtrans(line_species = ['H2O', 'CO_all_iso', 'CH4', 'CO2', 'Na', 'K'], \\\n rayleigh_species = ['H2', 'He'], \\\n continuum_opacities = ['H2-H2', 'H2-He'], \\\n wlen_bords_micron = [0.3, 15])\n\npressures = np.logspace(-6, 2, 100)\natmosphere.setup_opa_structure(pressures)\n```\n\n \n Read CIA opacities for H2-H2...\n Read CIA opacities for H2-He...\n Done.\n \n\n\n
\n\n**Units in petitRADTRANS:** remember that all units in *petitRADTRANS* are in cgs, **except for pressure**, which is in bars, **and the mean molecular weight (MMW)**, which is in units of atomic mass units.\n
\n\nNext we set up the atmospheric parameters, with a parameter selection identical to the [\"Getting Started\"](getting_started.html) case.\n\n\n```python\nfrom petitRADTRANS import nat_cst as nc\nR_pl = 1.838*nc.r_jup_mean\ngravity = 1e1**2.45\nP0 = 0.01\n\nkappa_IR = 0.01\ngamma = 0.4\nT_int = 200.\nT_equ = 1500.\ntemperature = nc.guillot_global(pressures, kappa_IR, gamma, gravity, T_int, T_equ)\n\nmass_fractions = {}\nmass_fractions['H2'] = 0.74 * np.ones_like(temperature)\nmass_fractions['He'] = 0.24 * np.ones_like(temperature)\nmass_fractions['H2O'] = 0.001 * np.ones_like(temperature)\nmass_fractions['CO_all_iso'] = 0.01 * np.ones_like(temperature)\nmass_fractions['CO2'] = 0.00001 * np.ones_like(temperature)\nmass_fractions['CH4'] = 0.000001 * np.ones_like(temperature)\nmass_fractions['Na'] = 0.00001 * np.ones_like(temperature)\nmass_fractions['K'] = 0.000001 * np.ones_like(temperature)\n\nMMW = 2.33 * np.ones_like(temperature)\n```\n\n
\n\n**Abundances in petitRADTRANS:** remember that abundances in pRT are in units of **mass fractions**, not number fractions (aka volume mixing ratio, VMR). You can convert between mass fractions and VMRs by using\n\\begin{equation}\nX_i = \\frac{\\mu_i}{\\mu}n_i,\n\\end{equation}\nwhere $X_i$ is the mass fraction of species $i$, $\\mu_i$ the mass of a single molecule/atom/ion/... of species $i$, $\\mu$ is the atmospheric mean molecular weight, and $n_i$ is the VMR of species $i$.\n\n
\n\nNow, let's calculate cloudy spectra! The first available mode is the so-called power law cloud. In this case the following opacity is *added* to the scattering cross-section:\n\\begin{equation}\n\\kappa = \\kappa_0\\left(\\frac{\\lambda}{\\lambda_0}\\right)^\\gamma\n\\end{equation}\nWhere $\\kappa_0$ is the opacity in units of cm$^2$/g, at $\\lambda_0=0.35 \\ {\\rm \\mu m}$. The power law index $\\gamma$ fixes the wavelength dependence, Rayleigh-like scattering would be obtained for $\\gamma=-4$. Hence $\\kappa_0$ and $\\gamma$ are free parameters.\n\nWe now calculate a clear atmosphere, and then four power law cloudy models, with $\\kappa_0 = 0.01$ cm$^2$/g, and four different $\\gamma$ values.\n\nClear model:\n\n\n```python\nimport pylab as plt\nplt.rcParams['figure.figsize'] = (10, 6)\n\n# Clear\natmosphere.calc_transm(temperature, mass_fractions, \\\n gravity, MMW, R_pl=R_pl, P0_bar=P0)\nclear = atmosphere.transm_rad/nc.r_jup_mean\n```\n\nFirst, $\\gamma = -4$ (Rayleigh-like):\n\n\n```python\nkappa_zero = 0.01\ngamma_scat = -4.\n\natmosphere.calc_transm(temperature, mass_fractions, \\\n gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n kappa_zero = kappa_zero, gamma_scat = gamma_scat)\n\nm4 = atmosphere.transm_rad/nc.r_jup_mean\n```\n\nSecond, $\\gamma = -2$ (weaker scattering power law):\n\n\n```python\nkappa_zero = 0.01\ngamma_scat = -2.\n\natmosphere.calc_transm(temperature, mass_fractions, \\\n gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n kappa_zero = kappa_zero, gamma_scat = gamma_scat)\n\nm2 = atmosphere.transm_rad/nc.r_jup_mean\n```\n\nThird, $\\gamma = 0$ (flat opacity):\n\n\n```python\nkappa_zero = 0.01\ngamma_scat = 0.\n\natmosphere.calc_transm(temperature, mass_fractions, \\\n gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n kappa_zero = kappa_zero, gamma_scat = gamma_scat)\n\nm0 = atmosphere.transm_rad/nc.r_jup_mean\n```\n\nFourth, the exoctic case of, $\\gamma = 1$ (positive opacity slope):\n\n\n```python\nkappa_zero = 0.01\ngamma_scat = 1.\n\natmosphere.calc_transm(temperature, mass_fractions, \\\n gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n kappa_zero = kappa_zero, gamma_scat = gamma_scat)\n\np1 = atmosphere.transm_rad/nc.r_jup_mean\n\n# Make plot\n\nplt.plot(nc.c/atmosphere.freq/1e-4, clear, label = 'Clear')\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n m4, \\\n label = r'Powerlaw cloud, $\\gamma = -4$')\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n m2, \\\n label = r'Powerlaw cloud, $\\gamma = -2$')\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n m0, \\\n label = r'Powerlaw cloud, $\\gamma = 0$')\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n p1,\\\n label = r'Powerlaw cloud, $\\gamma = 1$')\nplt.xscale('log')\nplt.xlabel('Wavelength (microns)')\nplt.ylabel(r'Transit radius ($\\rm R_{Jup}$)')\nplt.legend(loc = 'best')\nplt.show()\nplt.clf()\n```\n\n## Gray cloud deck and/or scaled Rayhleigh scattering\n\nIn addition to power law clouds, petitRADTRANS can also simply add a gray cloud deck, or scale the Rayleigh scattering opacities of the gas by a factor specified by the user. For these examples we will reuse the Radtrans object from the demonstration of the power law cloud above, there's no need to intialize it again.\n\nLet's calculate three spectra:\n- A clear model\n- A cloudy model with a gray cloud deck at 0.01 bar\n- A haze-like model, mimicked by scaling the Rayleigh scattering of the gas by a factor 10\n- A combination of the two above cloud models: gray cloud deck plus haze\n\n\n```python\nimport pylab as plt\nplt.rcParams['figure.figsize'] = (10, 6)\n\n# Clear\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, R_pl=R_pl, P0_bar=P0)\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n atmosphere.transm_rad/nc.r_jup_mean, label = 'Clear')\n\n# Gray cloud deck at 0.01 bar\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n Pcloud = 0.01)\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n atmosphere.transm_rad/nc.r_jup_mean, label = 'Gray cloud deck at 0.01 bar')\n\n# Haze (10 x gas Rayleigh scattering)\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n haze_factor = 10)\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n atmosphere.transm_rad/nc.r_jup_mean, label = 'Rayleigh haze')\n\n# Haze + cloud deck\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, R_pl=R_pl, P0_bar=P0, \\\n haze_factor = 10, Pcloud = 0.01)\nplt.plot(nc.c/atmosphere.freq/1e-4, \\\n atmosphere.transm_rad/nc.r_jup_mean, label = 'Rayleigh haze + cloud deck')\n\nplt.xscale('log')\nplt.xlabel('Wavelength (microns)')\nplt.ylabel(r'Transit radius ($\\rm R_{Jup}$)')\nplt.legend(loc = 'best')\nplt.show()\nplt.clf()\n```\n\n## Condensate clouds from real optical constants\n\nLet's calculate some spectra using opacities derived from optical constants of various materials.\nIn this example we will start of with forsterite, that is $\\rm Mg_2SiO_4$. For the list of available cloud species see [\"Available opacity species\"](../available_opacities.html).\n\n
\n\n**Choose your favorite particle setup:** petitRADTRANS offers multiple opacity versions for every given condensate, assuming either spherical (Mie scattering) or irreagularly shaped (DHS method = distribution of hollow spheres) particles. Moreover, opacities assuming a crystalline and/or amorphous internal structure can be used, where available.\n\n
\n\nWe set up the atmosphere like before, this time loading the opacity of crystalline (``c``), irregularly shaped particles (DHS method, abbreviated ``d``). The mode identifier for the $\\rm Mg_2SiO_4$ opacity therefore is ``Mg2SiO4(c)_cd``. ``(c)`` stands for condensed. These are all possible modes, note that for some species only crystalline or amorphous cross-sections are available.\n\n| Opacity code | Description |\n|------|------|\n| Species(c)_cm | crystalline Mie opacity of Species|\n| Species(c)_cd | crystalline DHS opacity of Species|\n| Species(c)_am | amorphous Mie opacity of Species|\n| Species(c)_ad | amorphous DHS opacity of Species|\n\nBut now, let's start! We simply give one additional ``cloud_species`` list to the Radtrans object, containing the name of the opacity species we want to use.\n\n\n```python\nimport numpy as np\nfrom petitRADTRANS import Radtrans\n\natmosphere = Radtrans(line_species = ['H2O', 'CO_all_iso', 'CH4', 'CO2', 'Na', 'K'], \\\n cloud_species = ['Mg2SiO4(c)_cd'], \\\n rayleigh_species = ['H2', 'He'], \\\n continuum_opacities = ['H2-H2', 'H2-He'], \\\n wlen_bords_micron = [0.3, 15])\n\npressures = np.logspace(-6, 2, 100)\natmosphere.setup_opa_structure(pressures)\n```\n\n \n Read CIA opacities for H2-H2...\n Read CIA opacities for H2-He...\n Done.\n \n\n\n
\n\n**Units in petitRADTRANS:** remember that all units in *petitRADTRANS* are in cgs, **except for pressure**, which is in bars, **and the mean molecular weight (MMW)**, which is in units of atomic mass units.\n
\n\nNext we set up the atmospheric parameters, with a parameter selection *almost* identical to the [\"Getting Started\"](getting_started.html) case. We now also add the mass fraction of the cloud species we are interested in. Note that the mass fractions only contains the name ``Mg2SiO4(c)`` now, the ``_cd`` suffix has to be omitted.\n\n\n```python\nfrom petitRADTRANS import nat_cst as nc\nR_pl = 1.838*nc.r_jup_mean\ngravity = 1e1**2.45\nP0 = 0.01\n\nkappa_IR = 0.01\ngamma = 0.4\nT_int = 200.\nT_equ = 1500.\ntemperature = nc.guillot_global(pressures, kappa_IR, gamma, gravity, T_int, T_equ)\n\nmass_fractions = {}\nmass_fractions['H2'] = 0.74 * np.ones_like(temperature)\nmass_fractions['He'] = 0.24 * np.ones_like(temperature)\nmass_fractions['H2O'] = 0.001 * np.ones_like(temperature)\nmass_fractions['CO_all_iso'] = 0.01 * np.ones_like(temperature)\nmass_fractions['CO2'] = 0.00001 * np.ones_like(temperature)\nmass_fractions['CH4'] = 0.000001 * np.ones_like(temperature)\nmass_fractions['Na'] = 0.00001 * np.ones_like(temperature)\nmass_fractions['K'] = 0.000001 * np.ones_like(temperature)\nmass_fractions['Mg2SiO4(c)'] = 0.0000005 * np.ones_like(temperature)\n\nMMW = 2.33 * np.ones_like(temperature)\n```\n\n
\n\n**Abundances in petitRADTRANS:** remember that abundances in petitCODE are in units of **mass fractions**, not number fractions (aka volume mixing ratio, VMR). You can convert between mass fractions and VMRs by using\n\\begin{equation}\nX_i = \\frac{\\mu_i}{\\mu}n_i,\n\\end{equation}\nwhere $X_i$ is the mass fraction of species $i$, $\\mu_i$ the mass of a single molecule/atom/ion/... of species $i$, $\\mu$ is the atmospheric mean molecular weight, and $n_i$ is the VMR of species $i$.\n\n
\n\n### Setting the cloud particle size\n\nWe have to define a few additional parameters for the clouds, to start the calculation.\nWe can give the mean particle size and width of the log-normal particle distribution:\n\n\n```python\nradius = {}\nradius['Mg2SiO4(c)'] = 0.00005*np.ones_like(temperature) # I.e. a 0.5-micron particle size (0.00005 cm)\n\nsigma_lnorm = 1.05\n```\n\nNow, let's calculate a clear and cloudy spectrum to compare:\n\n\n```python\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, \\\n R_pl=R_pl, P0_bar=P0, \\\n radius = radius, sigma_lnorm = sigma_lnorm)\n\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.transm_rad/nc.r_jup_mean, label = 'cloudy', zorder = 2)\n\nmass_fractions['Mg2SiO4(c)'] = np.zeros_like(temperature)\n\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, \\\n R_pl=R_pl, P0_bar=P0, \\\n radius = radius, sigma_lnorm = sigma_lnorm)\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.transm_rad/nc.r_jup_mean, label = 'clear', zorder = 1)\n\nplt.xscale('log')\nplt.xlabel('Wavelength (microns)')\nplt.ylabel(r'Transit radius ($\\rm R_{Jup}$)')\nplt.legend(loc='best')\nplt.show()\nplt.clf()\n```\n\nHere one sees that there is a lot of additional absorption in the optical and near-IR. Also note the silicate (Si-O stretching mode) becoming visible at 10 micron.\n\n### Calculating the particle size\n\nAlternatively, one can specify an eddy diffusion parameter ($K_{zz}$, with units of cm$^2$/s), which expresses how strongly atmospheric mixing is. The cloud particle size is then controlled by specifying $K_{zz}$, and the unitless settling parameter $f_{\\rm sed}$, which expresses the particles' mass averaged settling velocity, when compared to the local atmospheric mixing speed. Also, a width for the log-normal particle size distribution must be specified:\n\n\n```python\nKzz = np.ones_like(temperature)*1e1**7.5\nfsed = 2.\nsigma_lnorm = 1.05\n```\n\nAgain, let's calculate a clear and cloudy spectrum to compare:\n\n\n```python\nmass_fractions['Mg2SiO4(c)'] = 0.0000005 * np.ones_like(temperature)\n\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, \\\n R_pl=R_pl, P0_bar=P0, \\\n Kzz = Kzz, fsed=fsed, sigma_lnorm = sigma_lnorm)\n\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.transm_rad/nc.r_jup_mean, label = 'cloudy', zorder = 2)\n\nmass_fractions['Mg2SiO4(c)'] = np.zeros_like(temperature)\n\natmosphere.calc_transm(temperature, mass_fractions, gravity, MMW, \\\n R_pl=R_pl, P0_bar=P0, \\\n Kzz = Kzz, fsed=fsed, sigma_lnorm = sigma_lnorm)\n\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.transm_rad/nc.r_jup_mean, label = 'clear', zorder = 1)\n\nplt.xscale('log')\nplt.xlabel('Wavelength (microns)')\nplt.ylabel(r'Transit radius ($\\rm R_{Jup}$)')\nplt.legend(loc='best')\nplt.show()\nplt.clf()\n```\n\nThe resulting mean particle sizes can be accessed like this:\n\n\n```python\nplt.yscale('log')\nplt.xscale('log')\n\nplt.ylim([1e2,1e-6])\n\nplt.ylabel('P (bar)')\nplt.xlabel('Average particle size (microns)')\n\nplt.plot(atmosphere.r_g[:,atmosphere.cloud_species.index('Mg2SiO4(c)')]/1e-4, pressures)\nplt.show()\nplt.clf()\n```\n\n
\n\n**Minimum particle size:** the opacity of particles smaller than 1 nm is set to zero.\n\n
\n\n## Emission spectra\n\nWe can use the Radtrans object created above to calculate emission spectra as well. Here we will also generate an instance of pRT with scattering turned on, (see [\"Scattering for Emission Spectra\"](emis_scat.html) for an example on how to do this in detail).\n\n\n```python\nmass_fractions['Mg2SiO4(c)'] = 0.0000005 * np.ones_like(temperature)\n\natmosphere.calc_flux(temperature, mass_fractions, gravity, MMW, \\\n Kzz = Kzz, fsed=fsed, sigma_lnorm = sigma_lnorm)\n\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.flux/1e-6, \\\n color = 'black', label = 'cloudy, no scattering', zorder = 1)\n\n# Load scattering version of pRT\natmosphere = Radtrans(line_species = ['H2O', 'CO_all_iso', 'CH4', 'CO2', 'Na', 'K'], \\\n cloud_species = ['Mg2SiO4(c)_cd'], \\\n rayleigh_species = ['H2', 'He'], \\\n continuum_opacities = ['H2-H2', 'H2-He'], \\\n wlen_bords_micron = [0.3, 15], \\\n do_scat_emis = True)\npressures = np.logspace(-6, 2, 100)\natmosphere.setup_opa_structure(pressures)\n\natmosphere.calc_flux(temperature, mass_fractions, gravity, MMW, \\\n Kzz = Kzz, fsed=fsed, sigma_lnorm = sigma_lnorm, \\\n add_cloud_scat_as_abs = True)\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.flux/1e-6, \\\n label = 'cloudy, including scattering', zorder = 2)\n\nmass_fractions['Mg2SiO4(c)'] = np.zeros_like(temperature)\n\natmosphere.calc_flux(temperature, mass_fractions, gravity, MMW, \\\n Kzz = Kzz, fsed=fsed, sigma_lnorm = sigma_lnorm)\n\nplt.plot(nc.c/atmosphere.freq/1e-4, atmosphere.flux/1e-6, '-', \\\n color = 'red', label = 'clear', zorder = 0)\n\nplt.legend(loc='best')\nplt.xscale('log')\nplt.xlabel('Wavelength (microns)')\nplt.ylabel(r'Planet flux $F_\\nu$ (10$^{-6}$ erg cm$^{-2}$ s$^{-1}$ Hz$^{-1}$)')\nplt.show()\nplt.clf()\n```\n\nHere we plotted the clear spectrum, neglecting the cloud opacity, the cloudy spectrum only considering the absorption of the cloud particles, and the cloudy spectrum with scattering, using the scattering version of pRT.\n\n
\n\n**Scattering and petitRADTRANS:** remember that scattering is included for emission spectra in petitRADTRANS only if requested specifically when generating the Radtrans object, as it increases the runtime (see [\"Scattering for Emission Spectra\"](emis_scat.html) for an example how to do this).\n
\n", "meta": {"hexsha": "6addf557edf419bd115f3b1b3f1769dc92dde423", "size": 333714, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/content/notebooks/clouds.ipynb", "max_stars_repo_name": "nborsato/petitRADTRANS", "max_stars_repo_head_hexsha": "2df983bc46b892486b1b035d7c6933ab46f0d36c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/content/notebooks/clouds.ipynb", "max_issues_repo_name": "nborsato/petitRADTRANS", "max_issues_repo_head_hexsha": "2df983bc46b892486b1b035d7c6933ab46f0d36c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/content/notebooks/clouds.ipynb", "max_forks_repo_name": "nborsato/petitRADTRANS", "max_forks_repo_head_hexsha": "2df983bc46b892486b1b035d7c6933ab46f0d36c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 373.6998880179, "max_line_length": 77916, "alphanum_fraction": 0.9316810203, "converted": true, "num_tokens": 4890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3231331291566954}} {"text": "```python\n%matplotlib inline \n# plots graphs within the notebook\n%config InlineBackend.figure_format='svg' # not sure what this does, may be default images to svg format\nfrom __future__ import division\nfrom IPython.display import Image\n\nfrom IPython.core.display import HTML\ndef header(text):\n raw_html = '

' + str(text) + '

'\n return raw_html\n\ndef box(text):\n raw_html = '
'+str(text)+'
'\n return HTML(raw_html)\n\ndef nobox(text):\n raw_html = '

'+str(text)+'

'\n return HTML(raw_html)\n\ndef addContent(raw_html):\n global htmlContent\n htmlContent += raw_html\n```\n\n### Library for thermodynamic properties\n\nDefines thermodynamic properties of air and water at 1 atm. Air properties are tabled between $-150\\text{$^\\circ$C}$ and $400\\text{$^\\circ$C}$, water between $274\\text{K}$ and $373\\text{K}$, Argon between $100\\text{K}$ and $700\\text{K}$ and Krypton between $150\\text{K}$ and $750\\text{K}$\n

\nInput must be in Kelvin\n

\nUse the scipy functions C2K and F2K to convert temperatures to Kelvin. Thermodynamic properties are linearly interpolated from the two nearest temperature states.\n\n\n```python\n%%file thermodynamics.py\n\"\"\" Object name: Fluid\"\"\"\nimport numpy as np\nimport scipy\nimport scipy.optimize\nfrom scipy.constants import convert_temperature\ndef C2K(T):\n return convert_temperature(T,'Celsius','Kelvin')\ndef C2F(T):\n return convert_temperature(T,'Celsius','Fahrenheit')\ndef F2K(T):\n return convert_temperature(T,'Fahrenheit','Kelvin')\ndef F2C(T):\n return convert_temperature(T,'Fahrenheit','Celsius')\ndef K2F(T):\n return convert_temperature(T,'Kelvin','Fahrenheit')\ndef K2C(T):\n return convert_temperature(T,'Kelvin','Celsius')\nimport scipy.constants as sc\n\ndef interpolate_table(target,index,xquantity,yquantity):\n return yquantity[index] + \\\n (yquantity[index+1]-yquantity[index])* \\\n (target-xquantity[index])/(xquantity[index+1]-xquantity[index])\n \nclass Fluid(object):\n \"\"\" How to:\n from NewLibraries import thermodynamics as thermo\n \n fluid_of_interest = thermo.Fluid(material,T) material can be air, water, argon and krypton (see below for ranges)\n and the temperature of the fluid T is in Kelvin.\n Outputs:\n The new object computes thermodynamic properties of air between -150 C and 400 C, \n water between 274K and 373K, argon between 100 and 700K and\n krypton between 150 and 700 K under 1 atm. Argon, krypton and water were obtained \n through http://webbook.nist.gov/chemistry/fluid/\n More fluids to be added in the future\n fluid_of_interest.beta thermal expansion coefficient\n fluid_of_interest.rho density\n fluid_of_interest.Cp specific heat\n fluid_of_interest.mu dynamic viscosity\n fluid_of_interest.k thermal conductivity\n fluid_of_interest.nu kinematic viscosity\n fluid_of_interest.alpha thermal diffusivity\n fluid_of_interest.Pr\n \n \n \"\"\"\n def __init__(self,name,T,unit = \"K\",P = 101325.01):\n self.name = name\n if unit == \"C\":\n T = C2K(T)\n elif unit == \"F\":\n T = F2K(T)\n self.T = T\n self.P = P\n if P != 101325.01:\n print(\"All available tables are for P=1ATM, reverting to P=101325.01Pa\")\n self.P = 101325.01\n if self.name == 'water':\n if T < 274 or T > 373:\n print(\"Temperature is out of bounds for liquid water\")\n return \n Ttab,ptab,rhotab,Cptab,mutab,ktab = \\\n np.genfromtxt('Tables/water1atm.csv', delimiter=',', skip_header = 1, unpack=True, dtype=float)\n Ntab = len(Ttab)\n Cptab *= 1e3\n nutab = mutab/rhotab \n alphatab = ktab/(rhotab*Cptab)\n Prtab = nutab/alphatab\n dTtab = Ttab[1] - Ttab[0]\n # compute beta from -rho(d rho/dT)\n betatab = -(1./rhotab)*np.gradient(rhotab)/dTtab\n i = int((T-Ttab[0])/dTtab)\n if (i == Ntab - 1):\n i == Ntab - 2\n elif self.name == 'argon':\n if T < 100 or T > 700:\n print(\"Temperature is out of bounds for argon\")\n return \n Ttab,ptab,rhotab,Cptab,mutab,ktab = \\\n np.loadtxt('Tables/Argon1atm.csv', delimiter=',', skiprows = 1, unpack=True, dtype=float)\n Ntab = len(Ttab)\n Cptab *= 1e3\n nutab = mutab/rhotab \n alphatab = ktab/(rhotab*Cptab)\n Prtab = nutab/alphatab\n dTtab = Ttab[1] - Ttab[0]\n # compute beta from -rho(d rho/dT)\n betatab = -(1./rhotab)*np.gradient(rhotab)/dTtab\n i = int((T-Ttab[0])/dTtab)\n if (i == Ntab - 1):\n i == Ntab - 2\n elif self.name == 'krypton':\n if T < 150 or T > 740:\n print(\"Temperature is out of bounds for krypton\")\n return \n Ttab,ptab,rhotab,Cptab,mutab,ktab = \\\n np.loadtxt('Tables/Krypton1atm.csv', delimiter=',', skiprows = 1, unpack=True, dtype=float)\n Ntab = len(Ttab)\n Cptab *= 1e3\n nutab = mutab/rhotab \n alphatab = ktab/(rhotab*Cptab)\n Prtab = nutab/alphatab\n dTtab = Ttab[1] - Ttab[0]\n # compute beta from -rho(d rho/dT)\n betatab = -(1./rhotab)*np.gradient(rhotab)/dTtab\n i = int((T-Ttab[0])/dTtab)\n if (i == Ntab - 1):\n i == Ntab - 2\n elif self.name == 'air':\n if T < C2K(-150.) or T > C2K(400.):\n print(\"Temperature is out of bounds of the table for air\")\n return\n Ttab,rhotab,Cptab,ktab,nutab,betatab,Prtab = \\\n np.genfromtxt('Tables/air1atm.csv', delimiter=',', skip_header = 1, unpack=True, dtype=float)\n Ntab = len(Ttab)\n Ttab = C2K(Ttab)\n Cptab *= 1e3\n nutab *= 1e-6\n mutab = rhotab*nutab\n alphatab = ktab/(rhotab*Cptab)\n Prtab = nutab/alphatab\n i = 0\n while (Ttab[i] < T) and (i Library for extended surfaces\n\n\n```python\n%%file HT_conduction_extended_surfaces.py\n\"\"\"Object: ExtSurfaces\"\"\"\nfrom sympy.interactive import printing\nprinting.init_printing(use_latex='mathjax')\n\n\nfrom IPython.display import display,Image, Latex\nimport numpy as np\nimport math\nimport scipy.constants as sc\n\nimport sympy as sym\n#from sympy import *\n\nclass ExtSurfaces(object):\n \"\"\" Defines temperature distribution, heat rate for constant cross sectional area fins.\n from Libraries import HT_conduction_extended_surfaces as condext\n \n fin = condext.ExtSurfaces(T_b,T_infty,T_L,k,h,P,Ac,L)\n calculates fin.m, fin.M which are constants used in flux calculation. Also provides\n fin.theta_b,.theta_L,.T_b,.T_infty,.T_L,.h,.k,.h,.P,.Ac,.L,.Af(fin exposed surface area)\n fin.heat_rate(bc) calculate the heat rate for bc=\"convection\", \"adiabatic\", \"isothermal\", \"infinite\"\n The ouptuts are fin.q_f, fin.effectiveness, fin.resistance, fin.efficiency\n fin.temperature(bc,x) calculates the temperature as a function of bc and the location x\n The output is fin.theta_over_theta_b\n fin.equations(T_b_name,T_infty_name,T_L_name,k_name,h_name,P_name,Ac_name,L_name) writes all the equations for you\n you need to run fin.heat_rate first.\n \"\"\"\n def __init__(self,T_b,T_infty,T_L,k,h,P,Ac,L):\n self.T_b = T_b\n self.T_infty = T_infty\n self.T_L = T_L\n theta_b = T_b-T_infty\n theta_L = T_L-T_infty\n self.theta_b = T_b-T_infty\n self.theta_L = T_L-T_infty\n self.k = k\n self.h = h\n self.P = P\n self.Ac = Ac\n self.L = L\n self.Af = self.P*self.L\n m = np.sqrt(self.h*self.P/(self.k*self.Ac))\n self.m = m\n M = np.sqrt(self.h*self.P*self.k*self.Ac)*self.theta_b\n self.M = M\n def heat_rate(self,bc):\n self.bc = bc\n it_works = True\n if self.bc == \"convection\":\n self.q_f = self.M*(np.sinh(self.m*self.L) + (self.h/(self.m*self.k))*np.cosh(self.m*self.L))/\\\n (np.cosh(self.m*self.L) + (self.h/(self.m*self.k))*np.sinh(self.m*self.L))\n elif self.bc == \"adiabatic\":\n self.q_f = self.M*np.tanh(self.m*self.L)\n elif self.bc == \"isothermal\":\n self.q_f = self.M*np.cosh(self.m*self.L - self.theta_L/self.theta_b)/np.sinh(self.m*self.L)\n elif self.bc == 'infinite':\n self.q_f = self.M\n else:\n print(\"boundary condition is not properly defined\")\n it_works = False\n if it_works:\n self.effectiveness = self.q_f/(self.h*self.Ac*self.theta_b)\n self.Resistance = self.theta_b/self.q_f\n self.efficiency = self.q_f/(self.h*self.Af*self.theta_b)\n \n \n def temperature(self,bc,x):\n self.bc = bc\n if self.bc == \"convection\":\n self.theta_over_theta_b = (np.cosh(self.m*(self.L-x)) + (self.h/(self.m*self.k))*np.sinh(self.m*(self.L-x)))/\\\n (np.cosh(self.m*self.L) + (self.h/(self.m*self.k))*np.sinh(self.m*self.L))\n elif self.bc == \"adiabatic\":\n self.theta_over_theta_b = np.cosh(self.m*(self.L-x))/np.cosh(self.m*self.L)\n elif self.bc == \"isothermal\":\n self.theta_over_theta_b = ((self.theta_L/self.theta_b)*np.sinh(self.m*self.L)+np.sinh(self.m*self.L - x))\\\n /np.sinh(self.m*self.L)\n elif self.bc == 'infinite':\n self.theta_over_theta_b = np.exp(-self.m*x)\n else:\n print(\"boundary condition is not properly defined\")\n self.T_x = self.T_infty + self.theta_over_theta_b*self.theta_b\n \n \n \n \n \n```\n\n Overwriting HT_conduction_extended_surfaces.py\n\n\n\n```python\nimport HT_conduction_extended_surfaces as extsurf\nh = 100.\nD = 0.005\nP = np.pi*D\nk = 398.\nAc = np.pi*(D**2)/4\nT_b = 100.\nT_infty = 25.\nT_L = 0.\nL = 0.04\nfin = extsurf.ExtSurfaces(T_b,T_infty,T_L,k,h,P,Ac,L)\nfin.heat_rate('isothermal')\nprint(fin.q_f)\nfin.temperature('infinite',L/2.)\nprint(fin.theta_over_theta_b,fin.T_x)\n```\n\n 19.919974789199607\n 0.7531035967174129 81.48276975380597\n\n\n### Library of Nu correlations for external flows\n\n\n```python\n%%file HT_external_convection.py\n\"\"\" Object name 1: FlatPlate\n Object name 2: CircularCylinder\n Object name 3: NoncircularCylinder\n Object name 4: BankofTubes\n\"\"\"\n\nfrom sympy.interactive import printing\nprinting.init_printing(use_latex='mathjax')\n\n\nfrom IPython.display import display,Image, Latex\nimport numpy as np\nimport math\nimport scipy.constants as sc\nimport sys\ntry:\n import thermodynamics as thermo\nexcept ModuleNotFoundError:\n from Libraries import thermodynamics as thermo\nimport sympy as sym\n#from sympy import *\n\nclass FlatPlate(object):\n \"\"\" Definition of boundary layer thickness, friction coefficient, Nusselt number (both local and average)\n as a function of the regime.\n import HT_external_convection.py as extconv\n \n bl =extconv.FlatPlate(regime,thermal_bc,U_infty,nu,alpha,L,xi=0.0,Re_xc=5e5)\n where regime = 'laminar' or 'turbulent' or 'mixed', \n thermal_bc = 'isothermal', 'heat flux', 'unheated starting length',\n U_infty is the free stream velocity,\n nu the fluid viscosity,\n alpha the fluid thermal diffusivity,\n L length of the plate\n xi unheated started length (only applies of using unheated starting length)\n Re_xc critical Reynolds number for transition laminar to turbulence\n \n output: bl.Re_L Reynolds at the trailing edge of the plate (x=L)\n \n bl.local(x) calculates the local Re (bl.Re_x), Cf (bl.Cf_x), Nu (bl.Nu_x) and velocity\n thermal boundary layer thicknesses (bl.delta_x and bl.delta_Tx) at x based on thermal_bc\n \n bl.average(x) calculates the average Cf (bl.C_fave), Nu (bl.Nu_ave) over a length x from the leading edge\n \n \"\"\"\n def __init__(self,regime,thermal_bc,U_infty,nu,alpha,L,xi=0.0,Re_xc=5e5):\n self.regime = regime\n self.thermal_bc = thermal_bc\n self.U_infty = U_infty\n self.nu = nu\n self.alpha = alpha\n self.Pr = self.nu/self.alpha\n self.L = L\n self.xi = xi\n self.Re_xc = Re_xc\n self.Re_L = self.L*self.U_infty/self.nu\n self.x_c = self.Re_xc*self.nu/self.U_infty\n if self.regime != \"laminar\" and self.regime and \"turbulent\" and self.regime != \"mixed\":\n print(\"Warning: regime is not properly defined\")\n if self.thermal_bc != \"isothermal\" and self.thermal_bc != \"heat flux\" and self.thermal_bc != \"unheated starting length\":\n print(\"Warning: thermal boundary condition is not properly defined\")\n if self.Re_L > self.Re_xc and self.regime == \"laminar\":\n print(\"Warning: The end plate Reynolds number is larger than the critical Reynolds number, consider 'mixed' regime instead\")\n def local(self,x):\n self.x = x\n self.Re_x = self.U_infty*self.x/self.nu\n if x == 0.:\n self.delta_x = 0.\n self.delta_Tx = 0.\n self.Cf_x = 0.\n self.Nu_x = 0.\n else:\n if self.regime == \"laminar\":\n self.delta_x = 5.0*self.x/np.sqrt(self.Re_x)\n self.Cf_x = 0.664*np.power(self.Re_x,-1./2.)\n if self.thermal_bc == \"isothermal\":\n self.Nu_x = 0.332*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"heat flux\":\n self.Nu_x = 0.453*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"unheated starting length\":\n self.Re_xi = self.xi*self.U_infty/self.nu \n self.Nu_x = 0.332*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)/\\\n np.power(1.-np.power(self.xi/self.x,3./4.),1./3.)\n elif self.regime == \"turbulent\":\n self.delta_x = 0.37*self.x*np.power(self.Re_x,-1./5.)\n self.Cf_x = 0.0592*np.power(self.Re_x,-1./5.)\n if self.thermal_bc == \"isothermal\":\n self.Nu_x = 0.0296*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"heat flux\":\n self.Nu_x = 0.0296*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"unheated starting length\":\n self.Re_xi = self.xi*self.U_infty/self.nu\n self.Nu_x = 0.0296*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)/\\\n np.power(1.-np.power(self.xi/self.x,9./10.),1./9.)\n elif self.regime == \"mixed\":\n if self.x < self.x_c:\n self.delta_x = 5.0*self.x/np.sqrt(self.Re_x)\n self.Cf_x = 0.664*np.power(self.Re_x,-1./2.)\n if self.thermal_bc == \"isothermal\":\n self.Nu_x = 0.332*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"heat flux\":\n self.Nu_x = 0.453*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"unheated starting length\":\n self.Re_xi = self.xi*self.U_infty/self.nu \n self.Nu_x = 0.332*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)/\\\n np.power(1.-np.power(self.xi/self.x,3./4.),1./3.)\n else:\n self.delta_x = 0.37*self.x*np.power(self.Re_x,-1./5.)\n self.Cf_x = 0.0592*np.power(self.Re_x,-1./5.)\n if self.thermal_bc == \"isothermal\":\n self.Nu_x = 0.0296*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"heat flux\":\n self.Nu_x = 0.0296*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"unheated starting length\":\n self.Re_xi = self.xi*self.U_infty/self.nu\n self.Nu_x = 0.0296*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)/\\\n np.power(1.-np.power(self.xi/self.x,9./10.),1./9.)\n \n self.delta_Tx = self.delta_x*np.power(self.Pr,-1./3.)\n def average(self,x):\n self.x = x\n self.Re_x = self.U_infty*self.x/self.nu\n if x == 0.:\n print(\"The length cannot be zero\")\n if self.regime == \"laminar\":\n self.Cf_ave = 1.328*np.power(self.Re_x,-1./2.)\n if self.thermal_bc == \"isothermal\" or self.thermal_bc == \"heat flux\":\n self.Nu_ave = 0.664*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"unheated starting length\":\n p = 2.\n self.Re_xi = self.xi*self.U_infty/self.nu\n self.Nu_ave = 0.664*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)*\\\n x/(x-self.xi)*np.power(1.-np.power(self.xi/x,(p+1.)/(p+2.)),p/(p+1.))\n elif self.regime == \"turbulent\":\n self.Cf_ave = 0.074*np.power(self.Re_x,-1./5.)\n if self.thermal_bc == \"isothermal\" or self.thermal_bc == \"heat flux\":\n self.Nu_ave = 0.037*np.power(self.Re_x,4./5.)*np.power(self.Pr,1./3.)\n elif self.thermal_bc == \"unheated starting length\":\n p = 8.\n self.Re_xi = self.xi*self.U_infty/self.nu\n self.Nu_ave = 0.664*np.power(self.Re_x,1./2.)*np.power(self.Pr,1./3.)*\\\n x/(x-self.xi)*np.power(1.-np.power(self.xi/x,(p+1.)/(p+2.)),p/(p+1.))\n elif self.regime == \"mixed\":\n A = 0.037*np.power(self.Re_xc,4./5.)-0.664*np.power(self.Re_xc,1./2.)\n \n self.C_fave = 0.074*np.power(self.Re_x,-1./5.) - 2.*A/self.Re_x\n self.Nu_ave = (0.037*np.power(self.Re_x,4./5.) - A)*np.power(self.Pr,1./3.)\n \nclass CircularCylinder(object):\n \"\"\" Nusselt correlations for cylinders\n import HT_external_convection.py as extconv\n \n bluff_body =extconv.CircularCylinder(correlation,Re,Pr,Pr_s = 0.0) \n where Re, Pr, and Pr_s are the Reynolds number, Prandtl number of the flow and surface Prandtl numbers, respectively. If using Hilpert of Churchill Bernstein correlations,\n Re and Pr must be defined at film temperature, Pr_s can be set to anything since it is not used. \n If using Zukauskas, Re and Pr are defined at temperature at infinity.\n correlation may be 'Hilpert', 'Churchill-Bernstein', 'Zukauskas'\n Example:\n bluff_body = extconv.CircularCylinder('Hilpert',Re,Pr)\n bluff_body = extconv.CircularCylinder('Churchill-Bernstein',Re,Pr)\n bluff_body = extconv.CircularCylinder('Zukauskas',Re,Pr,Pr_s = xx)\n \n Output: bluff_body.Nu average Nusselt number also bluff_body.correlation, bluff_body.Re, bluff_body.Pr, bluff_body.Pr_s\n \n bluff_body.correlation('Name of the correlation')\n Name of the correlation may be 'Hilpert', 'Churchill-Bernstein', 'Zukauskas'\n \n \n \"\"\"\n def __init__(self,correlation,Re,Pr,Pr_s = 0.0):\n self.correlation = correlation\n self.Re = Re\n self.Pr = Pr\n self.Pr_s = Pr_s\n if correlation == \"Zukauskas\" and Pr_s == 0.0:\n print(\"Warning: Zukauskas correlation requires Pr_s\")\n if self.correlation == \"Hilpert\":\n if self.Re < 0.4:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu = 0.\n elif self.Re < 4.:\n C = 0.989\n m = 0.33\n elif self.Re < 40:\n C = 0.911\n m = 0.385\n elif self.Re < 4000:\n C = 0.683\n m = 0.466\n elif self.Re < 40000.:\n C = 0.193\n m = 0.618\n elif self.Re <= 400000.:\n C = 0.027\n m = 0.805\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation\")\n self.Nu = 0.\n if self.Re >= 0.4 and self.Re <= 400000.:\n self.Nu = C * self.Re**m * self.Pr**(1./3.)\n elif self.correlation == \"Churchill-Bernstein\":\n if (self.Re*self.Pr < 0.2):\n print(\"Warning: Product RePr lower than acceptable limit for Churchill Bernstein Correlation\")\n self.Nu = 0.\n \n else:\n self.Nu = 0.3+(0.62*self.Re**(0.5)*self.Pr**(1./3.)) \\\n /(1.+(0.4/self.Pr)**(2./3.))**(1./4.) \\\n *(1.+(self.Re/282000.)**(5./8.))**(4./5.)\n elif self.correlation == \"Zukauskas\":\n if (self.Pr <= 10):\n n = 0.37\n else:\n n = 0.36\n if (self.Re < 1.) and (self.Re > 1.e6):\n print(\"Warning Reynolds number out of bounds for the Zukauskas Correlation\")\n self.Nu = 0.\n else:\n if (self.Re < 40.):\n C = 0.75\n m = 0.4\n elif (self.Re < 1000.):\n C = 0.51\n m = 0.5\n elif (self.Re < 2.e5):\n C = 0.26\n m = 0.6\n else:\n C = 0.076\n m = 0.7\n self.Nu = C*self.Re**m*self.Pr**n*(self.Pr/self.Pr_s)**(1./4.)\n\nclass NonCircularCylinder(object):\n \"\"\" Nusselt correlations for cylinders with non circular cross-sections.\n import HT_external_convection.py as extconv\n \n bluff_body =extconv.NonCircularCylinder(geometry,Re,Pr) where \n geometry = \"angled square\" square with stagnation point on one of its edges\n \"square\" square with stagnation point at the center of one of its faces\n \"angled hexagon\" hexagon with stagnation point on one of its edges\n \"hexagon\" hexagon with stagnation point at the center of one of its faces\n \"thin plate\" thin plate perpendicular to the flow\n Re: Reynolds number at film temperature\n Pr: Prandtl number at film temperature\n \n Output: bluff_body.Nu, bluff_body.Nu_front, bluff_body.Nu_back, the last two are for thin plate only\n also bluff_body.geometry, bluff_body.Re, bluff_body.Pr\n \n \"\"\"\n def __init__(self,geometry,Re,Pr):\n self.geometry = geometry\n self.Re = Re\n self.Pr = Pr\n if self.geometry == \"angled square\":\n self.Nu_front = np.inf\n self.Nu_back = np.inf\n if self.Re < 6000:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu = np.inf\n elif self.Re <= 60000.:\n C = 0.304\n m = 0.59\n self.Nu = C * self.Re**m * self.Pr**(1./3.)\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation\")\n self.Nu = np.inf\n elif self.geometry == \"square\":\n self.Nu_front = np.inf\n self.Nu_back = np.inf\n if self.Re < 5000:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu = np.inf\n elif self.Re <= 60000.:\n C = 0.158\n m = 0.66\n self.Nu = C * self.Re**m * self.Pr**(1./3.)\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation\")\n self.Nu = np.inf\n elif self.geometry == \"angled hexagon\":\n self.Nu_front = np.inf\n self.Nu_back = np.inf\n if self.Re < 4500:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu = np.inf\n elif self.Re <= 90700.:\n C = 0.150\n m = 0.638\n self.Nu = C * self.Re**m * self.Pr**(1./3.)\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation\")\n self.Nu = np.inf\n elif self.geometry == \"hexagon\":\n self.Nu_front = np.inf\n self.Nu_back = np.inf\n if self.Re < 5200:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu = np.inf\n elif self.Re <= 20400.:\n C = 0.164\n m = 0.638\n self.Nu = C * self.Re**m * self.Pr**(1./3.)\n elif self.Re <= 105000.:\n C = 0.039\n m = 0.78\n self.Nu = C * self.Re**m * self.Pr**(1./3.)\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation\")\n self.Nu = np.inf\n elif self.geometry == \"thin plate\":\n self.Nu = np.inf\n if self.Re < 10000:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu_front = np.inf\n elif self.Re <= 50000.:\n C = 0.667\n m = 0.5\n self.Nu_front = C * self.Re**m * self.Pr**(1./3.)\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation for Nu_front\")\n self.Nu_back = np.inf\n if self.Re < 7000:\n print(\"Warning, Reynolds number too low for Hilpert Correlation\")\n self.Nu_back = np.inf\n elif self.Re <= 80000.:\n C = 0.191\n m = 0.667\n self.Nu_back = C * self.Re**m * self.Pr**(1./3.)\n else :\n print(\"Warning Reynolds number is too high for the Hilpert Correlation for Nu_front\")\n self.Nu_back = np.inf\n \nclass BankofTubes(object):\n \"\"\" Nusselt correlations for flow across banks of tubes\n import HT_external_convection.py as extconv\n bank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,\"C\",V_i,D,S_L,S_T,N_L=1)\n **Input:** \n arrangement = \"aligned\" tubes are aligned in row and column\n \"staggered\" tubes are staggered from one row to the next\n fluidspecie = 'air', 'water' or any other specie available in library thermodynamics\n T_i = inlet temperature\n T_s = tube surface temperature\n T_o = outlet temperature, provide a guess < T_s if unknown\n V_i: Inlet velocity\n S_L: tube center to tube center separation between two consecutive rows (perpendicular to the flow)\n S_T: tube center to tube center separation between two consecutive rows (aligned with the flow)\n N_L: number of rows aligned with flow if unknown give your best guess (default =1)\n \n Output:\n bank.T_m: arithmetic mean of T_i and T_o\n bank.Nu: average Nusselt number\n bank.Delta_T_lm: Log mean temperature difference\n bank.rho_i: inlet fluid density\n bank.mu_m: fluid viscosity at T_m\n bank.k_m: fluid thermal conductivity at T_m\n bank.Cp_m: Specific heat at T_m\n bank.Pr_m: Prandtl number at T_m\n bank.Pr_s: Prandtl number at T_s\n bank.Vmax: Max fluid velocity based on arrangement\n bank.Re: Reynolds number of the system\n \n bank.Nu: average Nusselt number\n bank.hbar: average heat transfer coefficient\n \n Functions: \n bank.heat_rate(N_T,N_L,L=1) creates bank.q, the heat rate per tube length is L is omitted \n or total heat rate if L is provided, based on the average convection coefficient\n bank.temperature_outlet_tube_banks(N_T,N_L) overwite bank.T_o (useful if T_o is unkown and you provided a \n guess. Rerun the object with new T_o to adjust Nu)\n bank.pressure_drop(N_L,f,chi) creates bank.Delta_p the pressure drop across the bank. f and chi must\n be extrapolated from graphs (see book or notebook)\n \n\n \"\"\"\n def __init__(self,arrangement,fluidspecie,T_i,T_s,T_o,unit,V_i,D,S_L,S_T,N_L=1):\n self.arrangement = arrangement\n self.T_i = T_i\n self.T_s = T_s\n self.V_i = V_i\n if (T_o == T_s):\n print(\"T_o and T_s cannot be equal, setting T_o to (T_i+T_s)/2 (think of it as your first guess)\")\n T_o = (T_i+T_s)/2.\n self.T_o = T_o\n T_m = (T_i + T_o)/2.\n self.T_m = T_m\n self.Delta_T_lm = ((T_s-T_i)-(T_s-T_o))/np.log((T_s-T_i)/(T_s-T_o))\n self.fluid = fluidspecie\n fluid_i = thermo.Fluid(fluidspecie,T_i,unit)\n fluid_m = thermo.Fluid(fluidspecie,T_m,unit)\n fluid_s = thermo.Fluid(fluidspecie,T_s,unit)\n self.rho_i = fluid_i.rho\n self.mu_m = fluid_m.mu\n self.k_m = fluid_m.k\n self.Cp_m = fluid_m.Cp\n self.Pr_m = fluid_m.nu/fluid_m.alpha\n self.Pr_s = fluid_s.nu/fluid_s.alpha\n self.S_L = S_L\n self.S_T = S_T\n self.N_L = N_L\n self.D = D\n if self.arrangement == 'aligned':\n self.Vmax = self.S_T*self.V_i/(self.S_T-D)\n elif self.arrangement == 'staggered':\n self.S_D = np.sqrt(self.S_L**2+(self.S_T/2.)**2)\n self.Vmax = self.S_T*V_i/(2.*(self.S_D-D))\n Re = self.rho_i*self.Vmax*self.D/self.mu_m\n self.Re = Re\n self.Nu = np.inf\n Corr_aligned = np.array([0.70,0.80,0.86,0.90,0.92,0.94,0.95,0.96,0.96,0.97,0.97,0.97,0.98,0.99,0.99,0.99,0.99,0.99,0.99])\n Corr_staggered = np.array([0.64,0.76,0.84,0.89,0.92,0.94,0.95,0.96,0.96,0.97,0.97,0.97,0.98,0.99,0.99,0.99,0.99,0.99,0.99])\n if (N_L < 20):\n if arrangement == 'aligned':\n Corr = Corr_aligned[N_L-1]\n elif arrangement == 'staggered':\n Corr = Corr_staggered[N_L-1]\n else:\n Corr = 1.\n if (Re < 10.):\n print('Warning: Re is out of bounds')\n if (Re >= 10.) and (Re <= 100.):\n if arrangement == 'aligned':\n C = 0.8\n m = 0.4\n elif arrangement == 'staggered':\n C = 0.9\n m = 0.4\n self.Nu = Corr*C*self.Re**m*self.Pr_m**(0.36)*(self.Pr_m/self.Pr_s)**(1./4.)\n elif (Re > 100.) and (Re <= 1000.):\n C = 0.51\n m = 0.\n self.Nu = Corr*C*self.Re**m*self.Pr_m**(0.36)*(self.Pr_m/self.Pr_s)**(1./4.)\n elif (Re > 1000.) and (Re <= 2.e5):\n if arrangement == 'aligned':\n if (S_T/S_L > 0.7):\n C = 0.27\n m = 0.63\n else:\n print('Warning: inefficient, S_T/S_L<0.7')\n \n elif arrangement == 'staggered':\n if (S_T/S_L < 2):\n C = 0.35*(S_T/S_L)**(1./5.)\n m = 0.6\n else:\n C = 0.40\n m = 0.6\n self.Nu = Corr*C*self.Re**m*self.Pr_m**(0.36)*(self.Pr_m/self.Pr_s)**(1./4.)\n elif (Re > 2e5) and (Re <= 2.e6):\n if arrangement == 'aligned':\n C = 0.021\n m = 0.84\n elif arrangement == 'staggered':\n C = 0.022\n m = 0.84\n self.Nu = Corr*C*self.Re**m*self.Pr_m**(0.36)*(self.Pr_m/self.Pr_s)**(1./4.)\n else:\n print('Warning: Re is out of bounds')\n\n self.hbar = self.Nu*self.k_m/self.D\n self.N_L_for_given_To = -np.log((self.T_s-self.T_o)/(self.T_s-self.T_i))/ \\\n (np.pi*self.D*self.hbar)*(self.rho_i*self.V_i*self.S_T*self.Cp_m)\n if (self.N_L < 20) and (self.N_L_for_given_To >= 20):\n print(\"WARNING input N_L < 20 but N_L computed for input T_o >=20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\")\n if (self.N_L < 20) and (self.N_L_for_given_To >= 20):\n print(\"WARNING input N_L >= 20 but N_L computed for input T_o <20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\")\n\n def heat_rate(self,N_T,N_L,L=1):\n N = N_T*N_L\n if N_L > 20 and self.N_L < 20:\n print(\"WARNING: you chose N_L > 20 but your initial guess was < 20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\")\n elif N_L < 20 and self.N_L >= 20:\n print(\"WARNING: you chose N_L < 20 but your initial guess was > 20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\")\n self.q=N*self.hbar*np.pi*self.D*self.Delta_T_lm*L\n\n \n def temperature_outlet_tube_banks(self,N_T,N_L):\n if N_L >= 20 and self.N_L < 20:\n print(\"WARNING: you chose N_L > 20 but your initial guess was < 20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\")\n elif N_L < 20 and self.N_L >= 20:\n print(\"WARNING: you chose N_L < 20 but your initial guess was > 20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\")\n N = N_T*N_L\n self.T_o = self.T_s-(self.T_s-self.T_i)* \\\n np.exp(-np.pi*self.D*N*self.hbar/(self.rho_i*self.V_i*N_T*self.S_T*self.Cp_m))\n def pressure_drop(self,N_L,f,chi):\n self.Delta_p = N_L*chi*(self.rho_i*self.Vmax**2/2)*f\n\n\n\n\n\n\n```\n\n Overwriting HT_external_convection.py\n\n\n\n```python\n\n\nimport HT_external_convection as extconv\n\nsquare = extconv.NonCircularCylinder(\"thin plate\",30000.,0.7)\nprint(square.Nu_back)\n```\n\n 164.30064088485295\n\n\n\n```python\n\n\n\nD = 10.e-3\nS_T = 15.e-3\nS_L = S_T\nN_L = 14\nN_T = 14\nN = 196\nT_i = 25.\nV_i = 5.\nT_s = 100.\nT_o = T_s - 10.\nL = 1.\nimport thermodynamics as thermo\nbank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,\"C\",V_i,D,S_L,S_T,N_L)\n\nprint(bank.Re)\nprint(bank.Nu)\nprint(bank.hbar)\nbank.heat_rate(N_T,N_L,L)\nprint(bank.q)\nbank.temperature_outlet_tube_banks(N_T,N_L)\nprint(bank.T_o)\nT_o = bank.T_o\nprint(\"New iteration\")\nbank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,\"C\",V_i,D,S_L,S_T,N_L)\n\nprint(bank.Re)\nprint(bank.Nu)\nprint(bank.hbar)\nbank.heat_rate(N_T,N_L,L)\nprint(bank.q)\nbank.temperature_outlet_tube_banks(N_T,N_L)\nprint(bank.T_o)\nbank.pressure_drop(N_L,0.32,1.)\nprint(bank.Delta_p)\n# h = bank.Nu*air.k/D\n# T_o = extconv.temperature_outlet_tube_banks(T_s,T_i,D,N,N_T,h,air.rho,V_i,S_T,air.Cp)\n# DT_lm = extconv.Delta_T_lm(T_s,T_i,T_o)\n# bank.heat_rate(h,D,T_s,T_i,T_o)\n# print(bank.q)\n# print(T_o)\n```\n\n WARNING input N_L < 20 but N_L computed for input T_o >=20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\n WARNING input N_L >= 20 but N_L computed for input T_o <20. \\ Rerun your BankofTubes object with the appropriate N_L to calculate the correct Nu\n 8875.203078134544\n 73.02371543088573\n 206.83967395798382\n 41086.48584005276\n 72.80755683113756\n New iteration\n 9077.946763871732\n 73.94647560894492\n 205.00377013428093\n 59482.787646596495\n 72.60865494226965\n 597.4920000000001\n\n\n\n```python\n\n\n\nD = 10.e-3\nS_T = 15.e-3\nS_L = S_T\nN_L = 14\nN_T = 14\nN = 196\nT_i = 25.\nV_i = 5.\nT_s = 100.\nT_o = 75.\nL = 1.\nimport thermodynamics as thermo\nbank = extconv.BankofTubes('aligned','air',T_i,T_s,T_o,\"C\",V_i,D,S_L,S_T,N_L)\n\nprint(bank.Re)\nprint(bank.Nu)\nprint(bank.hbar)\nprint(bank.N_L_for_given_To)\nN_L = int(bank.N_L_for_given_To) + 1\nbank.heat_rate(N_T,N_L,L)\nprint(bank.q)\nbank.temperature_outlet_tube_banks(N_T,N_L)\nprint(bank.T_o)\n# T_o = bank.T_o\n# print(\"New iteration\")\n# bank = extconv.BankofTubes('aligned','air',T_i,T_m,T_s,T_o,\"C\",V_i,D,S_L,S_T,N_L)\n\n# print(bank.Re)\n# print(bank.Nu)\n# print(bank.hbar)\n# bank.heat_rate(N_T,N_L,L)\n# print(bank.q)\n# bank.temperature_outlet_tube_banks(N_T,N_L)\n# print(bank.T_o)\n# bank.pressure_drop(N_L,0.32,1.)\n# print(bank.Delta_p)\n# # h = bank.Nu*air.k/D\n# # T_o = extconv.temperature_outlet_tube_banks(T_s,T_i,D,N,N_T,h,air.rho,V_i,S_T,air.Cp)\n# # DT_lm = extconv.Delta_T_lm(T_s,T_i,T_o)\n# # bank.heat_rate(h,D,T_s,T_i,T_o)\n# # print(bank.q)\n# # print(T_o)\n```\n\n 9051.578344318328\n 73.82744472007458\n 205.2402963218073\n 15.25542247062167\n 65733.39689091778\n 76.30520476189815\n\n\n\n```python\n\n\n\nD = 10.e-3\nS_T = 15.e-3\nS_L = S_T\nN_L = int(np.int(np.sqrt(196)))\nN_T = int(np.int(np.sqrt(196)))\nN = 196\nT_i = 25.\nV_i = 5.\nT_s = 100.\nT_o = 75\nT_m = (T_i+T_o)/2.\nimport thermodynamics as thermo\nair = thermo.Fluid(\"air\",thermo.C2K(T_m))\nair_s = thermo.Fluid(\"air\",thermo.C2K(T_s))\n\nimport HT_external_convection as extconv\n\n?extconv.BankofTubes\n\nnu = air.nu\nPr = air.Pr\nPr_s = air_s.Pr\n\nbank = extconv.BankofTubes(\"aligned\",V_i,D,nu,Pr,Pr_s,S_L,S_T,N_L,N_T)\nprint(bank.Re)\nprint(bank.Nu)\nh = bank.Nu*air.k/D\nT_o = extconv.temperature_outlet_tube_banks(T_s,T_i,D,N,N_T,h,air.rho,V_i,S_T,air.Cp)\nDT_lm = extconv.Delta_T_lm(T_s,T_i,T_o)\nbank.heat_rate(h,D,T_s,T_i,T_o)\nprint(bank.q)\nprint(T_o)\n```\n\n 7830.853563038373\n 67.4638616535179\n 55034.79484540479\n 74.06985116378564\n\n\n### Library of Nu correlations and functions for internal flow in pipes\n\n\n```python\n%%file HT_internal_convection.py\n\"\"\" \nObject name: PipeFlow\n\"\"\"\nimport numpy as np\nimport scipy\nimport scipy.optimize\n\nclass PipeFlow(object):\n \"\"\" Determination of Nu, pressure drop, mean temperature for internal convection\n import HT_internal_convection.py as intconv\n \n pipe =intconv.PipeFlow(D, Re=0.0, Um = 0.0, mdot = 0.0, nu = 0.0, rho = 0.0)\n where \n D is the only required input and one of the following combination (Re, nu) or (Um, nu) or (mdot, rho, nu)\n Hence the minimum calls for PipeFlow are\n pipe =intconv.PipeFlow(D, Re= Re_m, nu = nu_m) outputs pipe.Um\n pipe =intconv.PipeFlow(D, Re= Re_m, nu = nu_m, rho = rho_m) outputs pipe.Um (bulk velocity) \n and pipe.mdot (mass flow)\n pipe =intconv.PipeFlow(D, Um = 0.0, nu = 0.0) outputs pipe.Re\n pipe =intconv.PipeFlow(D, Um = Um, nu = nu_m, rho = rho_m) outputs pipe.Re, pipe.mdot\n pipe =intconv.PipeFlow(D, mdot = 0.0, nu = 0.0, rho = 0.0) outputs pipe.Re, pipe.Um\n \n pipe.f_laminar(Re) outputs the friction factor for laminar flow pipe.f\n pipe.f_turbulent(Re,eps = 0.0, nu = 0.0) outputs the friction factor for turbulent flow pipe.f\n \n The following correlations output pipe.Nu\n pipe.laminar_isothermal for isothermal wall boundary condition\n pipe.laminar_isoflux for isoflux wall boundary condition\n pipe.Dittus_Boelter(mode, Pr, Re = 0.) for turbulent flow where mode is either \"heating\" or \"cooling\"\n The Re is optional if omitted, the Reynolds number calculated in the object PipeFlow will be used\n pipe.Sieder_Tate(Pr,mu,mu_s, Re = 0.0) mu and mu_s are the mean and wall dynamics viscosities\n The Re is optional if omitted, the Reynolds number calculated in the object PipeFlow will be used\n pipe.Gnielinski( Pr, f,Re = 0.0): where f is the friction factor\n The Re is optional if omitted, the Reynolds number calculated in the object PipeFlow will be used\n \n \"\"\"\n def __init__(self,D, Re=0.0, Um = 0.0 , mdot = 0.0, nu = 0.0, rho = 0.0, L = 1.0 ):\n self.D = D\n self.L = L\n \n if Re == 0.0:\n if Um != 0.0 and nu != 0.0:\n Re = Um*D/nu\n elif mdot != 0 and rho != 0.0 and nu != 0.0:\n Um = mdot/(rho*np.pi*D**2/4.)\n Re = Um*D/nu\n else:\n print(\"Warning if Re == 0, Um, D and nu or mdot, rho and nu must be specified\")\n \n self.Re = Re\n if Um == 0.:\n if Re != 0. and nu != 0.:\n Um = Re*nu/D\n if mdot == 0.0 and rho != 0.0:\n mdot = rho*Um*np.pi*D**2/4.\n elif mdot !=0.0 and rho != 0.0:\n Um = mdot/(rho*np.pi*D**2/4.)\n \n \n self.Um = Um\n if mdot == 0.0:\n if rho != 0.0:\n mdot = rho*Um*np.pi*D**2/4.\n else:\n self.rho = 1.0\n self.mdot = rho*Um*np.pi*D**2/4.\n self.mdot = mdot\n self.nu = nu\n if Re == 0. and nu != 0.:\n Re = Um*D/nu\n self.Re = Re\n \n if rho == 0.0:\n self.rho = 1.0\n \n else:\n self.rho = rho\n \n \n\n\n def f_laminar(self, Re = 0.0):\n if Re == 0. and self.Re !=0:\n Re = self.Re\n elif Re == 0 and self.Re == 0.0:\n print(\"Warning Reynolds number is not defined\")\n self.f = 64./Re\n self.dPdx = self.f*(self.L/self.D)*(self.rho*self.Um**2)/2.\n\n def f_turbulent(self,Re = 0.0, eps = 0.0):\n if Re == 0. and self.Re !=0.0:\n Re = self.Re\n elif Re == 0 and self.Re == 0.0:\n print(\"Warning Reynolds number is not defined\")\n if eps == 0.0:\n print(\"Pipe wall is assumed to be hydrodynamically smooth\") \n e = eps\n \n f_0 = (0.790*np.log(Re)- 1.64)**(-2.)\n if (e > 0.):\n f_1 = 1./(-2.0*np.log10(e/3.71))**2\n else:\n f_1 = f_0\n f_guess = np.max([f_0,f_1])\n #f_guess = 0.04\n def f_tmp(x):\n y = (-2*np.log10((2.51/(Re*np.sqrt(x))) + (e/(3.71))) - 1.0/np.sqrt(x))\n return y\n y = scipy.optimize.fsolve(f_tmp, f_guess)\n self.f = y[0]\n self.dPdx = self.f*(self.L/self.D)*(self.rho*self.Um**2)/2.\n \n def laminar_isothermal(self):\n self.Nu = 3.66\n\n def laminar_isoflux(self):\n self.Nu = 4.36\n\n def Dittus_Boelter(self,mode,Pr,Re = 0.0):\n if Re == 0. and self.Re !=0:\n Re = self.Re\n else:\n print(\"Warning Reynolds number is not defined\")\n if (mode == 'heating'):\n n = 0.4\n elif (mode == 'cooling'):\n n = 0.3\n else:\n print(\"Warning you have to specify mode='heating' or 'cooling'\")\n self.Nu = 0.023*Re**(4./5.)*Pr**n\n\n def Sieder_Tate(self,Pr,mu,mu_s, Re = 0.0):\n if Re == 0. and self.Re !=0:\n Re = self.Re\n else:\n print(\"Warning Reynolds number is not defined\")\n self.Nu = 0.027*Re**(4/5)*Pr**(1/3)*(mu/mu_s)**0.14\n\n def Gnielinski(self, Pr, f,Re = 0.0):\n if Re == 0. and self.Re !=0:\n Re = self.Re\n else:\n print(\"Warning Reynolds number is not defined\")\n self.Nu = (f/8.)*(Re-1000.)*Pr/(1+12.7*(f/8.)**0.5*(Pr**(2./3.)-1.))\n\n def Skupinski(self,Pr, Re = 0.0):\n if Re == 0. and self.Re !=0:\n Re = self.Re\n else:\n print(\"Warning Reynolds number is not defined\")\n self.Nu = 4.82+0.0185*(Re*Pr)**0.827\n\n def Seban(self,Pr, Re = 0.0):\n if Re == 0. and self.Re !=0:\n Re = self.Re\n else:\n print(\"Warning Reynolds number is not defined\")\n self.Nu = 5.0+0.025*(Re*Pr)**0.8\n\ndef log_mean_temperature(T_s,T_o,T_i):\n if (T_s < min(T_o,T_i)):\n DT_o = T_o-T_s\n DT_i = T_i-T_s\n elif (T_s > max(T_o,T_i)):\n DT_o = T_s-T_o\n DT_i = T_s-T_i\n return (DT_o-DT_i)/np.log(DT_o/DT_i)\n\n\ndef T_mx_Ts_constant(T_s,T_mi,P,mdot,Cp,hbar,x):\n return T_s-(T_s-T_mi)*np.exp(-P*x*hbar/(mdot*Cp))\n\ndef T_mo_T_infty(T_infty,T_mi,P,L,mdot,Cp,R_tot):\n return T_infty-(Tinfty-T_mi)*np.exp(-1/(mdot*Cp*Rtot))\n\n\n\n```\n\n Overwriting HT_internal_convection.py\n\n\n\n```python\nimport HT_internal_convection as intconv\n\npipe = intconv.PipeFlow(D=0.01, L= 1., rho=1000., nu=1e-6, Um=2)\n\npipe.f_turbulent()\nprint(pipe.f,pipe.dPdx, pipe.Re)\n```\n\n Pipe wall is assumed to be hydrodynamically smooth\n 0.025883078538096054 5176.615707619211 20000.0\n\n\n### Library for natural convection around cylinders\n\n\n```python\n%%file HT_natural_convection.py\n\"\"\" \nObject name: HorizontalCylinder\nFunctions: Gr(g,beta,DT,D,nu) gives the Grashoff number based on:\n gravity g, thermal expansion coefficient beta, Temperature difference DT, \n length scale D, viscosity nu\n Ra(g,beta,DT,D,nu,alpha) gives the Rayleigh number where alpha is the thermal conductivity.\n\"\"\"\nimport numpy as np\nimport scipy\nimport scipy.optimize\n\nclass HorizontalCylinder(object):\n \"\"\" Natural convection about a horizontal cylinder\n from NewLibraries import HT_natural_convection as natconv\n cyl = natconv.HorizontalCylinder(correlation, Ra, Pr = 0.0)\n where correlation is \"Morgan\" or \"Churchill-Chu\"\n cyl = natconv.HorizontalCylinder(\"Morgan\", Ra)\n cyl = natconv.HorizontalCylinder(\"Churchill-Chu\", Ra, Pr = xx)\n \"\"\"\n\n def __init__(self,correlation=\"Morgan\", Ra=0.0, Pr = 0.0):\n self.correlation = correlation\n self.Ra = Ra\n if correlation == \"Morgan\":\n if (Ra <= 1e-2):\n C=0.675\n n=0.058\n elif (Ra <= 1e2):\n C=1.02\n n=0.148\n elif (Ra <= 1e4):\n C=0.85\n n=0.188\n elif (Ra <= 1e7):\n C=0.480\n n=0.250\n elif (Ra <= 1e12):\n C=0.125\n n=0.333\n self.Nu = C*Ra**n\n elif correlation == \"Churchill-Chu\":\n if Pr == 0.:\n print(\"Warning you must specify Pr for Churchill and Chu correlation\")\n else:\n self.Nu = (0.60+(0.387*Ra**(1./6.))/(1.+(0.559/Pr)**(9./16.))**(8./27.))**2\n else:\n print(\"Warning wrong correlation name\")\n\nclass VerticalEnclosure(object):\n \"\"\" Natural convection about a horizontal cylinder\n from NewLibraries import HT_natural_convection as natconv\n cyl = natconv.HorizontalCylinder(correlation, Ra, Pr = 0.0)\n where correlation is \"Morgan\" or \"Churchill-Chu\"\n cyl = natconv.HorizontalCylinder(\"Morgan\", Ra)\n cyl = natconv.HorizontalCylinder(\"Churchill-Chu\", Ra, Pr = xx)\n \"\"\"\n\n def __init__(self,Ra,Pr,H,L):\n self.Ra = Ra\n self.Pr = Pr\n self.H = H\n self.L = L\n if correlation == \"Morgan\":\n if (H/L) < 2.:\n if Ra*Pr/(0.2+Pr)> 1.e3:\n self.Nu = 0.18*(Pr/(0.2+Pr)*Ra)**0.29\n else:\n print('Ra is too low for this correlation')\n self.Nu = np.inf\n elif H/L < 10:\n if Ra < 1e10:\n self.Nu = 0.22*(Pr/(0.2+Pr)*Ra)**0.28*(H/L)**(-0.25)\n else:\n print('Ra is too high for this correlation')\n self.Nu = np.inf\n elif Ra < 1e4:\n print('Ra is too low for this correlation')\n self.Nu = np.inf\n elif Ra < 1e7:\n if Pr > 0.6 and Pr < 2e4:\n print('ok')\n self.Nu =0.42*Ra**0.25*Pr**0.012*(H/L)**(-0.3)\n else :\n print('Pr is out of bounds for this correlation')\n self.Nu = np.inf\n elif Ra < 1e9:\n if Pr > 0.6 and Pr < 20.:\n self.Nu =0.46*Ra**(1./3.)\n else :\n print('Pr is out of bounds for this correlation')\n self.Nu = np.inf\n else:\n print('Ra is too high, got nothing for you')\n self.Nu = np.inf\n\ndef Gr(g=9.81,beta=0.0,DT=0.0,D=0.0,nu=1.0):\n return (g*beta*DT*D**3)/(nu**2)\n\ndef Ra(g=9.81,beta=0.0,DT=0.0,D=0.0,nu=1.0,alpha=1.0):\n return (g*beta*DT*D**3)/(nu*alpha)\n\n\n\n\n```\n\n Overwriting HT_natural_convection.py\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "82b20df627b9e868dee6ba5b10bea2f408a7d1cf", "size": 72143, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Libraries/ME144-libraries.ipynb", "max_stars_repo_name": "ekuhn1/UVM-ME144-Heat-Transfer", "max_stars_repo_head_hexsha": "90bbaf0e1a25f66fe1197799ccdd155dbcfa181f", "max_stars_repo_licenses": ["CC-BY-3.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Libraries/ME144-libraries.ipynb", "max_issues_repo_name": "ekuhn1/UVM-ME144-Heat-Transfer", "max_issues_repo_head_hexsha": "90bbaf0e1a25f66fe1197799ccdd155dbcfa181f", "max_issues_repo_licenses": ["CC-BY-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Libraries/ME144-libraries.ipynb", "max_forks_repo_name": "ekuhn1/UVM-ME144-Heat-Transfer", "max_forks_repo_head_hexsha": "90bbaf0e1a25f66fe1197799ccdd155dbcfa181f", "max_forks_repo_licenses": ["CC-BY-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6629213483, "max_line_length": 307, "alphanum_fraction": 0.4792564767, "converted": true, "num_tokens": 15987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3225085113191054}} {"text": "# 变分量子本征求解器\n\n Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. \n\n## 概览\n\n目前普遍认为,量子计算在近期很有前景的一个应用是处理量子化学问题 [1-2]。**变分量子本征求解器** (VQE)作为这个研究方向的核心应用之一,为研究者们提供了可以在目前含噪的中等规模量子设备(NISQ device)上研究量子化学的可能 [1-4]。其核心任务是求解一个量子尺度上封闭物理系统的哈密顿量 $\\hat{H}$ 的基态能量及其对应的量子态。主要的实现方法是通过在量子设备上准备一个参数化的试探波函数 $|\\Psi(\\boldsymbol\\theta)\\rangle$ 然后结合经典机器学习中的优化算法(例如梯度下降法)去不断地调整、优化参数 $\\boldsymbol\\theta$ 使得期望值 $\\langle \\Psi(\\boldsymbol\\theta)|\\hat{H}|\\Psi(\\boldsymbol\\theta)\\rangle$ 最小化。这套方案的基本原理是基于 **Rayleigh-Ritz 变分原理**。 \n\n$$\nE_0 = \\min_{\\boldsymbol\\theta} \\langle \\Psi(\\boldsymbol\\theta)|\\hat{H}|\\Psi(\\boldsymbol\\theta)\\rangle.\n\\tag{1}\n$$\n\n其中 $E_0$ 表示该系统的基态能量。从数值分析的角度来看,该问题可以被理解为求解一个**离散化**哈密顿量 $H$(埃尔米特矩阵)的最小本征值 $\\lambda_{\\min}$ 和其对应的本征向量 $|\\Psi_0\\rangle$。具体的离散化过程是如何通过建立模型实现的,这属于量子化学的专业领域范畴。精确地解释该过程需要很长的篇幅,这超过了本教程所能处理的范围。我们会在下一节背景知识模块粗略的介绍一下相关知识,感兴趣的读者可以参考 `量子化学: 基本原理和从头计算法`系列丛书 [5]。通常来说,为了能在量子设备上处理量子化学问题,哈密顿量 $H$ 会被表示成为泡利算符 $\\{X,Y,Z\\}$ 的加权求和形式。\n\n$$\nH = \\sum_k c_k ~ \\bigg( \\bigotimes_{j=0}^{M-1} \\sigma_j^{(k)} \\bigg),\n\\tag{2}\n$$\n\n其中 $c_k$ 表示权重系数, $\\sigma_j^{(k)} \\in \\{I,X,Y,Z\\}$ 并且 $M$ 表示所需的量子比特个数。这样一种哈密顿量的表示形式被称为 **泡利字符串**。以下为一个2量子比特的具体例子,\n\n$$\nH= 0.12~Y_0 \\otimes I_1-0.04~X_0\\otimes Z_1.\n\\tag{3}\n$$\n\n在下一节,我们会补充一些关于电子结构问题的背景知识。本质上讨论的就是上述哈密顿量 $H$ 是如何计算的。对于熟悉相关背景的读者,或者主要关心如何在量桨上实现 VQE 的读者,请直接跳转至第三节分析氢分子($H_2$)基态的具体例子。 \n\n## 背景: 电子结构问题\n\n这里,我们集中讨论下量子化学中的一个基本问题 -- **电子结构问题**。更准确的说,我们关心的是给定分子(molecule)的低位能量本征态。这些信息可以帮助我们预测化学反应的速率和分子的稳定结构等等 [6]。假设一个分子由 $N_n$ 个原子核和 $N_e$ 个电子组成,描述该分子系统总能量的哈密顿量算符 $\\hat{H}_{mol}$ 在一次量子化表示下可以写为,\n\n$$\n\\begin{align}\n\\hat{H}_{\\text{mol}} & = -\\sum_{i}\\frac{\\nabla_{R_i}^2}{2M_i} - \\sum_{i} \\frac{\\nabla_{r_i}^2}{2} -\\sum_{i,j}\\frac{Z_i}{\\lvert R_i - r_j\\lvert} + \\sum_{i,j>i}\\frac{Z_iZ_j}{\\lvert R_i - R_j\\lvert} + \\sum_{i, j>i}\\frac{1}{\\lvert r_i - r_j\\lvert}, \n\\tag{4}\n\\end{align}\n$$\n\n其中 $R_i、M_i$ 和 $Z_i$ 分别表示第 $i$ 个原子核的位置、质量和原子序数(原子核内质子数),第 $i$ 个电子的位置则表示为 $r_i$。以上公式右边前两项分别代表原子核和电子的总动能。第三项表示带正电的质子和带负电的电子之间的库伦相互吸引作用。最后两项则表示原子核-原子核之间,电子-电子之间的相互排斥作用。这里,分子哈密顿量 $\\hat{H}_\\text{mol}$ 使用的是原子单位制能量 **哈特里能量**(Hartree),记为 Ha。$1$ 哈特里能量的大小为 $[\\hbar^2/(m_ee^2a_0^2)] = 27.2$ 电子伏或 $630$ 千卡/摩尔,其中 $m_e、e$ 和 $a_0$ 分别表示电子质量、基本电荷和玻尔半径。\n\n**注释1:** 在处理电子结构问题时,我们不考虑自旋-轨道耦合以及超精细结构。如果出于计算需要,可以作为微扰加入。\n\n### 玻恩-奥本海默近似\n\n由于原子核的质量要远大于电子,因而在同样的相互作用下电子的运动速度会比原子核快很多。所以,将原子核所处的位置看成固定 $R_i =$常数 是一种合理的近似。这种通过在时间尺度上将电子行为和原子核行为去耦合的近似处理思想被称为玻恩-奥本海默近似。作为近似的直接结果,公式(4)中原子核的动能项会被消去并且表示原子核-原子核相互排斥作用的项可以被认为是一个能量移位(这个项是与电子位置 $r_i$ 无关的)从而也可以作为常数项被忽略。经过这些步骤后,我们可以把哈密顿量近似为:\n\n$$\n\\begin{align}\n\\hat{H}_{\\text{electron}} & = - \\sum_{i} \\frac{\\nabla_{r_i}^2}{2} -\\sum_{i,j}\\frac{Z_i}{\\lvert R_i - r_j\\lvert} + \\sum_{i, j>i}\\frac{1}{\\lvert r_i - r_j\\lvert} \n\\tag{5},\n\\end{align}\n$$\n\n在经过以上近似后,分子中多电子结构的能级在理论上可以通过求解以下不含时薛定谔方程获得:\n\n$$\n\\hat{H}_{\\text{electron}} |\\Psi_n \\rangle = E_n |\\Psi_n \\rangle,\n\\tag{6}\n$$\n\n其中 $n$ 指代能级。值得注意的是,电子哈密顿量中电子-电子相互排斥作用的求和项数会随着电子数 $N_e$ 的增多至 $N_e(N_e-1)/2$ 项。这意味着对于一个含有16个电子的氧分子($O_2$)我们需要计算多达120项的相互排斥作用项。 一般来说,这样的问题是无法从理论上精确求解的。正如狄拉克在 [Quantum mechanics of many-electron systems](https://royalsocietypublishing.org/doi/10.1098/rspa.1929.0094) [7] 所指出的那样,\n\n> *The underlying physical laws necessary for the mathematical theory of a large part of physics and the whole of chemistry are thus completely known, and the difficulty is only that the exact application of these laws leads to equations much too complicated to be soluble.* \n> \n> -- Paul Dirac (1929)\n\n由于解析的方法太复杂,那么我们可以采用数值方法来处理。一个最简单的数值方法(离散化方法)就是把上述作用中无限维度希尔伯特空间离散化为等间距排开的立方体晶格点。在这样一个离散化的空间里,主要运算规则为复数域的线性代数。假设空间的每个轴都离散为等间距排开的 $k$ 个点,则 $N$-电子(为了方便去掉下标 $e$)的多体波函数可以写为 [2]:\n\n$$\n|\\Psi \\rangle = \\sum_{\\mathbf{x_1}, \\ldots, \\mathbf{x_N}} \\psi(\\mathbf{x_1}, \\ldots, \\mathbf{x_N}) \\mathcal{A}(|\\mathbf{x_1}, \\ldots, \\mathbf{x_N}\\rangle).\n\\tag{7}\n$$\n\n其中坐标 $|\\mathbf{x_j}\\rangle = |r_j\\rangle |\\sigma_j\\rangle$ 记录第 $j$ 个电子的空间位置信息和自旋,$|r_j\\rangle = |x_j,y_j,z_j\\rangle$ 且 $j\\in \\{1,2,\\cdots,N\\}$, $x_j,y_j,z_j \\in \\{0,1,\\cdots,k-1\\}$ 同时 $\\sigma_j \\in \\{\\downarrow,\\uparrow\\}$ 表示自旋向下和向上。这样一种离散化方式共计需要 $k^{3N}\\times 2^{N}$ 个数据来表示波函数。在这里,$\\mathcal{A}$ 表示反对称化操作(根据泡利不相容原理)并且 $\\psi(\\mathbf{x_1}, \\mathbf{x_2}, \\ldots, \\mathbf{x_N})=\\langle\\mathbf{x_1}, \\mathbf{x_2}, \\ldots, \\mathbf{x_N}|\\Psi\\rangle$。 可以看出,经典计算机存储这样一个波函数需要的内存是随着电子个数呈指数增长的。这使得基于这种离散化的经典数值方法,无法模拟超过几十个电子的系统。那么,我们是不是能够通过量子设备来存储和准备这样一个波函数然后求解基态能量 $E_0$ 呢?在下一节中,我们将以最简单的分子系统 -- 氢分子($H_2$)为例,讲解 VQE 算法。\n\n**注释2:** 关于量子化学和现有数值计算方法的综述也超过了本教程的处理范围,我们推荐感兴趣的读者去查阅以下经典教材 Helgaker 等人撰写的 *'Molecular Electronic-Structure Theory'* [6] 以及 Szabo & Ostlund 撰写的 *'Modern Quantum Chemistry: Introduction to Advanced Electronic Structure Theory'* [8]。 如果需要弥补量子计算和量子化学之间知识空缺,请参考以下综述文章 [Quantum chemistry in the age of quantum computing](https://pubs.acs.org/doi/10.1021/acs.chemrev.8b00803) [1] 和 [Quantum computational chemistry](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.92.015003) [2] 。\n\n**注释3:** 对于量子化学中的能量计算,我们期望能够达到 **化学精度**(chemical accuracy)$1.6\\times10^{-3}$ Ha 或者 1 千卡/摩尔。\n\n\n\n## 氢分子 $H_2$ 基态能量\n\n### 构造电子哈密顿量\n\n首先,让我们通过下面几行代码引入必要的 library 和 package。量桨的量子化学工具包是基于 `psi4` 和 `openfermion` 进行开发的,所以需要读者先行安装这两个语言包。在进入下面的教程之前,我们强烈建议您先阅读[哈密顿量的构造](./BuildingMolecule_CN.ipynb)教程,该教程介绍了如何使用量桨的量子化学工具包。\n\n**注意:关于环境设置,请参考 [README_CN.md](https://github.com/PaddlePaddle/Quantum/blob/master/README_CN.md).**\n\n\n```python\nimport paddle\nimport paddle_quantum.qchem as qchem\nfrom paddle_quantum.utils import Hamiltonian\nfrom paddle_quantum.circuit import UAnsatz\n\nimport os\nimport matplotlib.pyplot as plt\n\nimport numpy\nfrom numpy import pi as PI\nfrom numpy import savez, zeros\n\n# 无视警告\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n```\n\n对于具体需要分析的分子,我们需要其**几何构型** (geometry)、**基组**(basis set,例如 STO-3G 基于高斯函数)、**多重度**(multiplicity)以及**分子的净电荷数** (charge) 等多项信息来建模计算出该分子单体积分 (one-body integrations),双体积分(two-body integrations) 以及哈密顿量等信息。接下来,通过量桨的量子化学工具包将分子的哈密顿量提取出来并储存为 paddle quantum 的 `Hamiltonian` 类,方便我们下一步的操作。\n\n\n```python\ngeo = qchem.geometry(structure=[['H', [-0., 0., 0.0]], ['H', [-0., 0., 0.74]]])\n# geo = qchem.geometry(file='h2.xyz')\n\n# 将分子信息存储在 molecule 里,包括单体积分(one-body integrations),双体积分(two-body integrations),分子的哈密顿量等\nmolecule = qchem.get_molecular_data(\n geometry=geo,\n basis='sto-3g',\n charge=0,\n multiplicity=1,\n method=\"fci\",\n if_save=True,\n if_print=True\n)\n# 提取哈密顿量\nmolecular_hamiltonian = qchem.spin_hamiltonian(molecule=molecule,\n filename=None, \n multiplicity=1, \n mapping_method = 'jordan_wigner',)\n# 打印结果\nprint(\"\\nThe generated h2 Hamiltonian is \\n\", molecular_hamiltonian)\n```\n\n FCI energy for H2_sto-3g_singlet (2 electrons) is -1.137283834485513.\n \n The generated h2 Hamiltonian is \n -0.09706626861762556 I\n -0.04530261550868938 X0, X1, Y2, Y3\n 0.04530261550868938 X0, Y1, Y2, X3\n 0.04530261550868938 Y0, X1, X2, Y3\n -0.04530261550868938 Y0, Y1, X2, X3\n 0.1714128263940239 Z0\n 0.16868898168693286 Z0, Z1\n 0.12062523481381837 Z0, Z2\n 0.16592785032250773 Z0, Z3\n 0.17141282639402394 Z1\n 0.16592785032250773 Z1, Z2\n 0.12062523481381837 Z1, Z3\n -0.2234315367466399 Z2\n 0.17441287610651626 Z2, Z3\n -0.2234315367466399 Z3\n\n\n**注释4:** 生成这个哈密顿量的几何构型中,两个氢原子间的原子间隔(interatomic distance)为 $d = 74$ pm。\n\n除了输入分子的几何结构外,我们还支持读取分子的几何构型文件 (`.xyz` 文件),关于量子化学工具包更多的用法请参考[哈密顿量的构造](./BuildingMolecule_CN.ipynb)教程。如果你需要测试更多分子的几何构型,请移步至这个[数据库](http://smart.sns.it/molecules/index.html)。\n\n### 搭建量子神经网络(QNN)和试探波函数\n\n在实现VQE的过程中,我们首先需要设计量子神经网络QNN(也可以理解为参数化量子电路)来准备试探波函数 $|\\Psi(\\boldsymbol\\theta)\\rangle$。这里,我们提供一个预设好的的深度为 $D$ 层的 4-量子比特的量子电路模板,图中的虚线框内为一层:\n\n\n\n- 我们预设一些该参数化电路的参数,比如宽度为 $N = 4$ 量子位。\n\n- 初始化其中的变量参数,${\\bf{\\theta }}$ 代表我们量子神经网络中的参数组成的向量。\n\n接下来我们根据上图中的电路设计,通过 Paddle Quantum 的 `UAnsatz` 函数和内置的 `real_entangled_layer(theta, D)` 电路模板来高效搭建量子神经网络。 \n\n\n```python\ndef U_theta(theta, Hamiltonian, N, D):\n \"\"\"\n Quantum Neural Network\n \"\"\"\n \n # 按照量子比特数量/网络宽度初始化量子神经网络\n cir = UAnsatz(N)\n \n # 内置的 {R_y + CNOT} 电路模板\n cir.real_entangled_layer(theta[:D], D)\n \n # 铺上最后一列 R_y 旋转门\n for i in range(N):\n cir.ry(theta=theta[D][i][0], which_qubit=i)\n \n # 量子神经网络作用在默认的初始态 |0000> 上\n fin_state = cir.run_state_vector()\n \n # 计算给定哈密顿量的期望值\n expectation_val = cir.expecval(Hamiltonian)\n\n return expectation_val, cir, fin_state\n```\n\n### 配置训练模型 - 损失函数\n\n现在我们已经有了数据和量子神经网络的架构,我们将进一步定义训练参数、模型和损失函数。通过作用量子神经网络 $U(\\theta)$ 在初始态 $|0..0\\rangle$ 上,我们将得到输出态 $\\left| {\\psi \\left( {\\bf{\\theta }} \\right)} \\right\\rangle $。进一步,在VQE模型中的损失函数一般由量子态 $\\left| {\\psi \\left( {\\bf{\\theta }} \\right)} \\right\\rangle$ 关于哈密顿量 $H$ 的期望值 (能量期望值 expectation value) 给出,\n\n$$\n\\min_{\\boldsymbol\\theta} \\mathcal{L}(\\boldsymbol \\theta) = \\min_{\\boldsymbol\\theta} \\langle \\Psi(\\boldsymbol\\theta)|H |\\Psi(\\boldsymbol\\theta)\\rangle\n= \\min_{\\boldsymbol\\theta} \\sum_k c_k~\\langle \\Psi(\\boldsymbol\\theta)| \\bigotimes_j \\sigma_j^{(k)}|\\Psi(\\boldsymbol\\theta)\\rangle.\n\\tag{8}\n$$\n\n\n```python\nclass StateNet(paddle.nn.Layer):\n \"\"\"\n Construct the model net\n \"\"\"\n\n def __init__(self, shape, dtype=\"float64\"):\n super(StateNet, self).__init__()\n \n # 初始化 theta 参数列表,并用 [0, 2*pi] 的均匀分布来填充初始值\n self.theta = self.create_parameter(shape=shape, \n default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2*PI),\n dtype=dtype, is_bias=False)\n \n # 定义损失函数和前向传播机制\n def forward(self, N, D):\n \n # 计算损失函数/期望值\n loss, cir, fin_state = U_theta(self.theta, molecular_hamiltonian.pauli_str, N, D)\n\n return loss, cir, fin_state\n```\n\n### 配置训练模型 - 模型参数\n\n在进行量子神经网络的训练之前,我们还需要进行一些训练的超参数设置,主要是学习速率(LR, learning rate)、迭代次数(ITR, iteration)和量子神经网络计算模块的深度(D, Depth)。这里我们设定学习速率为 0.5, 迭代次数为 50 次。读者不妨自行调整来直观感受下超参数调整对训练效果的影响。\n\n\n```python\nITR = 80 # 设置训练的总迭代次数\nLR = 0.4 # 设置学习速率\nD = 2 # 设置量子神经网络中重复计算模块的深度 Depth\nN = molecular_hamiltonian.n_qubits # 设置参与计算的量子比特数\n```\n\n### 进行训练\n\n当训练模型的各项参数都设置完成后,我们将数据转化为 Paddle 中的张量,进而进行量子神经网络的训练。过程中我们用的是Adam Optimizer,也可以调用Paddle中提供的其他优化器。我们将训练过程中的结果存储在summary_data文件中。\n\n\n```python\n# 确定网络的参数维度\nnet = StateNet(shape=[D + 1, N, 1])\n\n# 一般来说,我们利用Adam优化器来获得相对好的收敛,\n# 当然你可以改成SGD或者是RMS prop.\nopt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n\n# 记录优化结果\nsummary_iter, summary_loss = [], []\n\n# 优化循环\nfor itr in range(1, ITR + 1):\n\n # 前向传播计算损失函数\n loss, cir, fin_state = net(N, D)\n\n # 在动态图机制下,反向传播极小化损失函数\n loss.backward()\n opt.minimize(loss)\n opt.clear_grad()\n\n # 更新优化结果\n summary_loss.append(loss.numpy())\n summary_iter.append(itr)\n\n # 打印结果\n if itr % 20 == 0:\n print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n print(\"iter:\", itr, \"Ground state energy:\", \"%.4f Ha\" \n % loss.numpy())\n if itr == ITR:\n print(\"\\n训练后的电路:\") \n print(cir)\n\n# 储存训练结果到 output 文件夹\nos.makedirs(\"output\", exist_ok=True)\nsavez(\"./output/summary_data\", iter = summary_iter, \n energy=summary_loss)\n```\n\n iter: 20 loss: -1.0621\n iter: 20 Ground state energy: -1.0621 Ha\n iter: 40 loss: -1.1305\n iter: 40 Ground state energy: -1.1305 Ha\n iter: 60 loss: -1.1358\n iter: 60 Ground state energy: -1.1358 Ha\n iter: 80 loss: -1.1370\n iter: 80 Ground state energy: -1.1370 Ha\n \n 训练后的电路:\n --Ry(4.702)----*--------------x----Ry(4.759)----*--------------x----Ry(0.001)--\n | | | | \n --Ry(-1.56)----x----*---------|----Ry(4.698)----x----*---------|----Ry(1.607)--\n | | | | \n --Ry(3.170)---------x----*----|----Ry(1.789)---------x----*----|----Ry(4.817)--\n | | | | \n --Ry(6.365)--------------x----*----Ry(1.562)--------------x----*----Ry(3.178)--\n \n\n\n### 测试效果\n我们现在已经完成了量子神经网络的训练,通过 VQE 得到的基态能量的估计值大致为 $E_0 \\approx -1.137$ Ha,这与通过全价构型相互作用(FCI)$E_0 = -1.13728$ Ha 计算得出的值是在化学精度 $\\varepsilon = 1.6 \\times 10^{-3}$ Ha 内相符合的。\n\n\n```python\nresult = numpy.load('./output/summary_data.npz')\n\neig_val, eig_state = numpy.linalg.eig(\n molecular_hamiltonian.construct_h_matrix())\nmin_eig_H = numpy.min(eig_val.real)\nmin_loss = numpy.ones([len(result['iter'])]) * min_eig_H\n\nplt.figure(1)\nfunc1, = plt.plot(result['iter'], result['energy'], \n alpha=0.7, marker='', linestyle=\"-\", color='r')\nfunc_min, = plt.plot(result['iter'], min_loss, \n alpha=0.7, marker='', linestyle=\":\", color='b')\nplt.xlabel('Number of iteration')\nplt.ylabel('Energy (Ha)')\n\nplt.legend(handles=[\n func1,\n func_min\n],\n labels=[\n r'$\\left\\langle {\\psi \\left( {\\theta } \\right)} '\n r'\\right|H\\left| {\\psi \\left( {\\theta } \\right)} \\right\\rangle $',\n 'Ground-state energy',\n ], loc='best')\n\n#plt.savefig(\"vqe.png\", bbox_inches='tight', dpi=300)\nplt.show()\n```\n\n## 通过 VQE 确定原子间隔\n\n还记得在前面的注释中提到我们默认使用的两个氢原子间原子间隔为 $74$ pm 吗?VQE 的另一个用法便是通过在不同的原子间隔下多次运行然后观察运行结果的最小值是在什么原子间隔发生的,这个间隔即为估计得真实原子间隔。\n\n\n\n从上图可以看出,最小值确实发生在 $d = 74$ pm (1 pm = $1\\times 10^{-12}$m) 附近,这是与[实验测得数据](https://cccbdb.nist.gov/exp2x.asp?casno=1333740&charge=0)相符合的 $d_{exp} (H_2) = 74.14$ pm.\n\n_______\n\n## 参考文献\n\n[1] Cao, Yudong, et al. Quantum Chemistry in the Age of Quantum Computing. [Chemical reviews 119.19 (2019): 10856-10915.](https://pubs.acs.org/doi/10.1021/acs.chemrev.8b00803)\n\n[2] McArdle, Sam, et al. Quantum computational chemistry. [Reviews of Modern Physics 92.1 (2020): 015003.](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.92.015003)\n\n\n[3] Peruzzo, A. et al. A variational eigenvalue solver on a photonic quantum processor. [Nat. Commun. 5, 4213 (2014).](https://www.nature.com/articles/ncomms5213)\n\n[4] Moll, Nikolaj, et al. Quantum optimization using variational algorithms on near-term quantum devices. [Quantum Science and Technology 3.3 (2018): 030503.](https://iopscience.iop.org/article/10.1088/2058-9565/aab822)\n\n[5] 徐光宪, 黎乐民, 王德民. 量子化学: 基本原理和从头计算法(上)[M], 第二版. 北京: 科学出版社, 2012; \n\n[6] Helgaker, Trygve, Poul Jorgensen, and Jeppe Olsen. Molecular electronic-structure theory. John Wiley & Sons, 2014.\n\n[7] Dirac, Paul Adrien Maurice. Quantum mechanics of many-electron systems. [Proceedings of the Royal Society of London. Series A, Containing Papers of a Mathematical and Physical Character 123.792 (1929): 714-733.](https://royalsocietypublishing.org/doi/10.1098/rspa.1929.0094)\n\n[8] Szabo, Attila, and Neil S. Ostlund. Modern quantum chemistry: introduction to advanced electronic structure theory. Courier Corporation, 2012.\n", "meta": {"hexsha": "30b856c3688f5c4eaa5c335dfded68ee2721e088", "size": 38859, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorial/quantum_simulation/VQE_CN.ipynb", "max_stars_repo_name": "gsq7474741/Quantum", "max_stars_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-07-14T14:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-14T14:10:23.000Z", "max_issues_repo_path": "tutorial/quantum_simulation/VQE_CN.ipynb", "max_issues_repo_name": "gsq7474741/Quantum", "max_issues_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/quantum_simulation/VQE_CN.ipynb", "max_forks_repo_name": "gsq7474741/Quantum", "max_forks_repo_head_hexsha": "16e7d3bf2dba7e94e6faf5c853faf0e913e1f268", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 70.3967391304, "max_line_length": 17536, "alphanum_fraction": 0.742196145, "converted": true, "num_tokens": 7521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.32239181661441113}} {"text": "Copyright (c) Microsoft Corporation. All rights reserved.\n\nLicensed under the MIT License.\n\n\n\n# Automated Machine Learning For EconML\n\nThis is a version of the evaluation for running in the cloud, it has settings that leverage greater access to compute.\n\n## Imports\n\n\n```python\nimport logging\nimport sys\n# Main imports\nfrom econml.dml import DMLCateEstimator, LinearDMLCateEstimator,SparseLinearDMLCateEstimator,ForestDMLCateEstimator, NonParamDMLCateEstimator, KernelDMLCateEstimator\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport os\nimport copy\n\nimport azureml.core\nfrom azureml.core.experiment import Experiment\nfrom azureml.core.workspace import Workspace\nfrom azureml.automl.core.featurization import FeaturizationConfig\nfrom azureml.core.dataset import Dataset\nfrom azureml.explain.model._internal.explanation_client import ExplanationClient\n\n#Import scikit-learn model AutoML wrapper\nfrom econml.automated_ml import addAutomatedML,setAutomatedMLWorkspace, EconAutoMLConfig\n# Imports for linear double machine learning evaluation\nfrom econml.dml import LinearDMLCateEstimator\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport os\n# Helper imports\nimport math\nimport numpy as np\nfrom itertools import product\nfrom sklearn.linear_model import Lasso, LassoCV, LogisticRegression, LogisticRegressionCV,LinearRegression,MultiTaskElasticNet,MultiTaskElasticNetCV\nfrom sklearn.ensemble import RandomForestRegressor,RandomForestClassifier\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.model_selection import train_test_split\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n```\n\n C:\\Users\\v-keacqu\\AppData\\Local\\Continuum\\miniconda3\\envs\\azure_automl\\lib\\site-packages\\sklearn\\externals\\joblib\\__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.\n warnings.warn(msg, category=DeprecationWarning)\n\n\n## AutoML Setup\n\nTo begin we will configure our AutoML instance and load environment variable necessary to leverage AutoML.\n\n\n```python\nsetAutomatedMLWorkspace(workspace_name = \"\",\n subscription_id=\"\",\n resource_group=\"\")\n```\n\n Workspace configuration has succeeded.\n\n\nThe first step for using AutoML with double machine learning is to specify the configuration object of your AutoML target, this `AutoMLConfig` object specifies the settings of the AutoML session that will be used to develop your model.\n\n\n```python\n\nautoml_settings_reg = {\n \"experiment_timeout_minutes\" : 1,\n \"enable_early_stopping\" : True,\n \"iteration_timeout_minutes\": 1,\n \"max_cores_per_iteration\": -1,\n \"n_cross_validations\": 2,\n 'preprocess': False,\n \"featurization\": 'off',\n \"verbosity\": logging.INFO,\n \"primary_metric\": 'normalized_mean_absolute_error'\n}\n\nautoml_settings_clf = {\n \"experiment_timeout_minutes\" : 1,\n \"enable_early_stopping\" : True,\n \"iteration_timeout_minutes\": 1,\n \"max_cores_per_iteration\": -1,\n \"n_cross_validations\": 2,\n 'preprocess': False,\n \"featurization\": 'off',\n \"verbosity\": logging.INFO,\n \"primary_metric\": 'AUC_weighted'\n}\n\nautoml_config_reg = EconAutoMLConfig(task = 'regression',\n debug_log = 'automl_errors.log',\n enable_onnx_compatible_models=True,\n model_explainability=True,\n **automl_settings_reg\n )\n\nautoml_config_clf = EconAutoMLConfig(task = 'classification',\n debug_log = 'automl_errors.log',\n enable_onnx_compatible_models=True,\n model_explainability=True,\n **automl_settings_clf\n )\n\n\n```\n\n### Grid Search Baseline\n\nIn order to evaluate our model against a well performing Random Forest Classifier, we need to specify a class that completes grid search CV over the RandomForestRegressor class and chooses the best resulting model. Below is the class definition and as well as two funtions for instantiating our RandomForestRegressor wrapper.\n\n\n```python\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import PolynomialFeatures\n\nclass GridSearchCVList:\n\n def __init__(self, estimator_list, param_grid_list, scoring=None,\n n_jobs=None, iid='warn', refit=True, cv='warn', verbose=0, pre_dispatch='2*n_jobs',\n error_score='raise-deprecating', return_train_score=False):\n self._gcv_list = [GridSearchCV(estimator, param_grid, scoring=scoring,\n n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose,\n pre_dispatch=pre_dispatch, error_score=error_score,\n return_train_score=return_train_score)\n for estimator, param_grid in zip(estimator_list, param_grid_list)]\n return\n\n def fit(self, X, y, sample_weight = None, **fit_params):\n self.best_ind_ = np.argmax([gcv.fit(X, y, sample_weight = sample_weight, **fit_params).best_score_ for gcv in self._gcv_list])\n self.best_estimator_ = self._gcv_list[self.best_ind_].best_estimator_\n self.best_score_ = self._gcv_list[self.best_ind_].best_score_\n self.best_params_ = self._gcv_list[self.best_ind_].best_params_\n return self\n\n def predict(self, X):\n return self.best_estimator_.predict(X)\n\n def predict_proba(self, X):\n return self.best_estimator_.predict_proba(X)\n\nfrom sklearn.linear_model import LassoCV, LogisticRegressionCV\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom econml.sklearn_extensions.linear_model import WeightedLassoCV\n\ndef grid_search_reg():\n return GridSearchCVList([RandomForestRegressor(n_estimators=100, random_state=123),\n GradientBoostingRegressor(random_state=123)],\n param_grid_list=[{'max_depth': [3, None],\n 'min_samples_leaf': [10, 50]},\n {'n_estimators': [50, 100],\n 'max_depth': [3],\n 'min_samples_leaf': [10, 30]}],\n cv=3,\n iid=True,\n scoring='neg_mean_squared_error')\n\n\ndef grid_search_clf():\n return GridSearchCVList([RandomForestClassifier(n_estimators=100, random_state=123),\n GradientBoostingClassifier(random_state=123)],\n param_grid_list=[{'max_depth': [3, 5],\n 'min_samples_leaf': [10, 50]},\n {'n_estimators': [50, 100],\n 'max_depth': [3],\n 'min_samples_leaf': [10, 30]}],\n cv=3,\n iid=True,\n scoring='neg_mean_squared_error')\n```\n\n### DGP \nThe DGP is described by the following equations:\n\n\\begin{align}\nT =& g(W \\cdot \\beta) + \\eta, & \\;\\eta \\sim \\text{Uniform}(-1, 1)\\\\\nY =& T\\cdot \\theta + m(W\\cdot \\beta) + \\epsilon, &\\; \\epsilon \\sim \\text{Uniform}(-1, 1)\\\\\nW \\sim& \\text{Normal}(0,\\, I_{n_w})\\\\\nX \\sim& \\text{Uniform}(0,1)^{n_x}\n\\end{align}\n\nwhere $W$ is a matrix of high-dimensional confounders, $m, g$ can be nonlinear, and $\\beta, \\gamma$ have high sparsity.\n\nFor this DGP, \n\\begin{align}\n\\theta(x) = \\exp(2\\cdot x_1)\\\\\ng(x) = sin^2(x)\\\\\nm(x;\\eta,\\gamma)=\\frac{1}{2\\pi}\\frac{sinh(\\gamma)}{cosh(\\gamma)-cos(x-\\eta)}\n\\end{align}\n\nLet’s keep it simple and set $\\eta = 0$ and $\\gamma = 1$.\n\n### Structural Model for Estimation\n\nThe model we are trying to estimate is as follows\n\n$$t_i = g(w_i\\cdot b) + \\eta$$\n$$y_i = t_i\\cdot \\theta + m(w_i\\cdot b) + \\epsilon$$\n\nFor this example the true value of the causal parameter will be $\\theta = 0.5$\n\n\n```python\n# Treatment effect function\ndef te(x):\n return np.sin(2*math.pi*x[0])/2+0.5\ndef g(x):\n return np.power(np.sin(x),2)\ndef m(x,nu=0.,gamma=1.):\n return 0.5/math.pi*(np.sinh(gamma))/(np.cosh(gamma)-np.cos(x-nu))\n#vectorized g and m for applying to dataset\nvg = np.vectorize(g)\nvm = np.vectorize(m)\n```\n\n\n```python\n# DGP constants\nnp.random.seed(123)\nn = 10000\nn_w = 30\nsupport_size = 5\nn_x = 1\n# Outcome support\nsupport_Y = np.random.choice(np.arange(n_w), size=support_size, replace=False)\ncoefs_Y = np.random.uniform(0, 1, size=support_size)\nepsilon_sample = lambda n: np.random.uniform(-1, 1, size=n)\n# Treatment support\nsupport_T = support_Y\ncoefs_T = np.random.uniform(0, 1, size=support_size)\neta_sample = lambda n: np.random.uniform(-1, 1, size=n)\n\n# Generate controls, covariates, treatments and outcomes\nW = np.random.normal(0, 1, size=(n, n_w))\nX = np.random.uniform(0, 1, size=(n, n_x))\n# Heterogeneous treatment effects\nTE = np.array([te(x_i) for x_i in X])\n\nT = vg(np.dot(W[:, support_T], coefs_T))+ eta_sample(n)\nY = TE * T + vm(np.dot(W[:, support_Y], coefs_Y))+ epsilon_sample(n)\n\nY_train, Y_val, T_train, T_val, X_train, X_val, W_train, W_val = train_test_split(Y, T, X, W, test_size=.2)\n# Generate test data\nX_test = np.array(list(product(np.arange(0, 1, 0.01), repeat=n_x)))\n```\n\n# Train Estimators\nWe train models in three different ways, and compare their performance.\n\n\n# Default Setting\n\n\n```python\nest = LinearDMLCateEstimator(model_y=RandomForestRegressor(),\n model_t=RandomForestRegressor(),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_rf_regressor = est.effect(X_test)\n```\n\n\n```python\nest = LinearDMLCateEstimator(model_y=grid_search_reg(),\n model_t=grid_search_reg(),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_cv_regressor = est.effect(X_test)\n```\n\n\n```python\nAutomatedLinearDMLCateEstimator = addAutomatedML(LinearDMLCateEstimator)\nest = AutomatedLinearDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_reg,\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_aml_regressor = est.effect(X_test)\n```\n\n Experiment model_t_20_01_31-16_34_42 has started.\n Experiment model_t_20_01_31-16_34_42 completed.\n Experiment model_y_20_01_31-16_36_44 has started.\n\n\n## Performance Visualization\n\n\n```python\nplt.figure(figsize=(10,6))\nexpected_te = np.array([te(x_i) for x_i in X_test])\nplt.plot(X_test, expected_te, 'b--', label='True effect')\nplt.plot(X_test, te_pred_rf_regressor, label='DML Polynomial Features with RF Regressor')\nplt.plot(X_test, te_pred_aml_regressor, label='DML Polynomial Features with AML Regressor')\nplt.ylabel('Treatment Effect')\nplt.xlabel('x')\nplt.legend()\nplt.show()\n```\n\n# Polynomial Features with Regularization\n\n\n```python\nest = DMLCateEstimator(model_y=RandomForestRegressor(),\n model_t=RandomForestRegressor(),\n model_final=Lasso(alpha=0.0001, fit_intercept=False),\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_rf_regressor_2=est.effect(X_test)\n```\n\n\n```python\nest = DMLCateEstimator(model_y=grid_search_reg(),\n model_t=grid_search_reg(),\n model_final=Lasso(alpha=0.0001, fit_intercept=False),\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_cv_regressor_2 = est.effect(X_test)\n```\n\n\n```python\nAutomatedDMLCateEstimator = addAutomatedML(DMLCateEstimator)\nest = AutomatedDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_reg,\n model_final=Lasso(alpha=0.0001, fit_intercept=False),\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_aml_regressor_2=est.effect(X_test)\n```\n\n Experiment model_t_20_01_28-13_56_29 has started.\n Experiment model_t_20_01_28-13_56_29 completed.\n Experiment model_y_20_01_28-13_58_02 has started.\n Experiment model_y_20_01_28-13_58_02 completed.\n Experiment model_t_20_01_28-13_59_42 has started.\n Experiment model_t_20_01_28-13_59_42 completed.\n Experiment model_y_20_01_28-14_01_18 has started.\n Experiment model_y_20_01_28-14_01_18 completed.\n\n\n\n```python\nplt.figure(figsize=(10,6))\nplt.plot(X_test, te_pred_rf_regressor_2, label='DML Polynomial Features with RF Regressor')\n#plt.plot(X_test, te_pred_cv_regressor_2, label='DML Polynomial Features with Grid Search Regressor')\nplt.plot(X_test, te_pred_aml_regressor_2, label='DML Polynomial Features with AML Regressor')\nexpected_te = np.array([te(x_i) for x_i in X_test])\nplt.plot(X_test, expected_te, 'b--', label='True effect')\nplt.ylabel('Treatment Effect')\nplt.xlabel('x')\nplt.legend()\nplt.show()\n```\n\n## Random Forest Final Stage\n\n\n\n```python\nest = ForestDMLCateEstimator(model_y=RandomForestRegressor(),\n model_t=RandomForestRegressor(),\n discrete_treatment=False,\n n_estimators=1000,\n subsample_fr=.8,\n min_samples_leaf=10,\n min_impurity_decrease=0.001,\n verbose=0, min_weight_fraction_leaf=.01)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_rf_regressor_3 = est.effect(X_test)\n```\n\n\n```python\nest = ForestDMLCateEstimator(model_y=grid_search_reg(),\n model_t=grid_search_reg(),\n discrete_treatment=False,\n n_estimators=1000,\n subsample_fr=.8,\n min_samples_leaf=10,\n min_impurity_decrease=0.001,\n verbose=0, min_weight_fraction_leaf=.01)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pcdred_cv_regressor_3 = est.effect(X_test)\n```\n\n\n```python\nAutomatedForestDMLCateEstimator = addAutomatedML(ForestDMLCateEstimator)\nest = AutomatedForestDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_reg,\n discrete_treatment=False,\n n_estimators=1000,\n subsample_fr=.8,\n min_samples_leaf=10,\n min_impurity_decrease=0.001,\n verbose=0, min_weight_fraction_leaf=.01)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_aml_regressor_3 = est.effect(X_test)\n```\n\n Experiment model_t_20_01_28-14_03_08 has started.\n Experiment model_t_20_01_28-14_03_08 completed.\n Experiment model_y_20_01_28-14_04_43 has started.\n Experiment model_y_20_01_28-14_04_43 completed.\n Experiment model_t_20_01_28-14_06_20 has started.\n Experiment model_t_20_01_28-14_06_20 completed.\n Experiment model_y_20_01_28-14_07_56 has started.\n Experiment model_y_20_01_28-14_07_56 completed.\n\n\n### Performance Visualization\n\n\n```python\nplt.figure(figsize=(10,6))\nexpected_te = np.array([te(x_i) for x_i in X_test])\nplt.plot(X_test, expected_te, 'b--', label='True effect')\nplt.plot(X_test, te_pred_rf_regressor_3, label='DML Polynomial Features with RF Regressor')\n#plt.plot(X_test, te_pred_cv_regressor_3, label='DML Polynomial Features with Grid Search Regressor')\nplt.plot(X_test, te_pred_aml_regressor_3, label='DML Polynomial Features with AML Regressor')\nplt.ylabel('Treatment Effect')\nplt.xlabel('x')\nplt.legend()\nplt.show()\n```\n\n## AutoML Final Stage Parametric Estimator\n\nFor correctness, all parametric double machine learning estimators (all estimators besides ``NonParamDMLEstimator``) must be trained on linear models. We can specify that using a the parameter ``linear_model_required``.\n\n\n\n```python\nautoml_settings_reg = {\n \"experiment_timeout_minutes\" : 10,\n \"enable_early_stopping\" : True,\n \"iteration_timeout_minutes\": 2,\n \"max_cores_per_iteration\": -1,\n \"n_cross_validations\": 2,\n 'preprocess': False,\n \"featurization\": 'off',\n \"verbosity\": logging.INFO,\n \"primary_metric\": 'normalized_mean_absolute_error'\n}\nautoml_config_final = EconAutoMLConfig(task = 'regression',\n debug_log = 'automl_errors.log',\n #For correctness, parametric DML must be linear models\n linear_model_required = True,\n **automl_settings_reg\n )\n```\n\n\n```python\nest = DMLCateEstimator(model_y=RandomForestRegressor(),\n model_t=RandomForestRegressor(),\n model_final=RandomForestRegressor(),\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_rf_regressor_4 = est.effect(X_test)\n```\n\n\n```python\nest = DMLCateEstimator(model_y=grid_search_reg(),\n model_t=grid_search_reg(),\n model_final=grid_search_reg(),\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_cv_regressor_4 = est.effect(X_test)\n```\n\n\n```python\nAutomatedDMLCateEstimator = addAutomatedML(DMLCateEstimator)\nest = AutomatedDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_reg,\n model_final=automl_config_final,\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_aml_regressor_4 = est.effect(X_test)\n```\n\n Experiment model_t_20_01_28-15_50_01 has started.\n Experiment model_t_20_01_28-15_50_01 completed.\n Experiment model_y_20_01_28-15_51_44 has started.\n Experiment model_y_20_01_28-15_51_44 completed.\n Experiment model_t_20_01_28-15_53_26 has started.\n Experiment model_t_20_01_28-15_53_26 completed.\n Experiment model_y_20_01_28-15_55_30 has started.\n Experiment model_y_20_01_28-15_55_30 completed.\n Experiment model_final_20_01_28-15_57_16 has started.\n Experiment model_final_20_01_28-15_57_16 completed.\n\n\n### Performance Visualization\n\n\n```python\nplt.figure(figsize=(10,6))\nplt.plot(X_test, te_pred_rf_regressor_4, label='DML Polynomial Features with RF Regressor')\nplt.plot(X_test, te_pred_cv_regressor_4, label='DML Polynomial Features with Grid Search Regressor')\nplt.plot(X_test, te_pred_aml_regressor_4, label='DML Polynomial Features with AML Regressor')\nexpected_te = np.array([te(x_i) for x_i in X_test])\nplt.plot(X_test, expected_te, 'b--', label='True effect')\nplt.ylabel('Treatment Effect')\nplt.xlabel('x')\nplt.legend()\nplt.show()\n```\n\n## With Nonlinear Models Allowed\n\n\n```python\nAutomatedDMLCateEstimator = addAutomatedML(DMLCateEstimator)\nest = AutomatedDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_reg,\n model_final=automl_config_reg,\n featurizer=PolynomialFeatures(degree=5),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_aml_regressor_4 = est.effect(X_test)\n```\n\n Experiment model_t_20_01_28-14_48_12 has started.\n Experiment model_t_20_01_28-14_48_12 completed.\n Experiment model_y_20_01_28-14_50_04 has started.\n Experiment model_y_20_01_28-14_50_04 completed.\n Experiment model_t_20_01_28-14_51_45 has started.\n Experiment model_t_20_01_28-14_51_45 completed.\n Experiment model_y_20_01_28-14_53_35 has started.\n Experiment model_y_20_01_28-14_53_35 completed.\n Experiment model_final_20_01_28-14_55_18 has started.\n Experiment model_final_20_01_28-14_55_18 completed.\n\n\n### Performance Visualization\n\n\n```python\nplt.figure(figsize=(10,6))\nplt.plot(X_test, te_pred_rf_regressor_4, label='DML Polynomial Features with RF Regressor')\nplt.plot(X_test, te_pred_aml_regressor_4, label='DML Polynomial Features with AML Regressor')\nexpected_te = np.array([te(x_i) for x_i in X_test])\nplt.plot(X_test, expected_te, 'b--', label='True effect')\nplt.ylabel('Treatment Effect')\nplt.xlabel('x')\nplt.legend()\nplt.show()\n```\n\n## AutoML Final Stage Nonparametric Estimator\n\nFor correctness, all nonparametric double machine learning estimators (all estimators besides ``NonParamDMLEstimator``) must be trained on models that enable sample weights. We can specify that using a the parameter ``sample_weights_required``.\n\n\n\n```python\nautoml_config_final = EconAutoMLConfig(task = 'regression',\n debug_log = 'automl_errors.log',\n enable_onnx_compatible_models=True,\n model_explainability=True,\n #For correctness, parametric DML must have sample weight\n sample_weights_required = True,\n **automl_settings_reg\n )\n```\n\n\n```python\nest = NonParamDMLCateEstimator(model_y=RandomForestRegressor(),\n model_t=RandomForestRegressor(),\n model_final=RandomForestRegressor(),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_rf_regressor_6 = est.effect(X_test)\n```\n\n\n```python\nest = NonParamDMLCateEstimator(model_y=grid_search_reg(),\n model_t=grid_search_reg(),\n model_final=grid_search_reg(),\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_cv_regressor_6 = est.effect(X_test)\n```\n\n\n```python\nAutomatedNonParamDMLCateEstimator = addAutomatedML(NonParamDMLCateEstimator)\nest = AutomatedNonParamDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_reg,\n model_final=automl_config_final,\n random_state=123)\nest.fit(Y_train, T_train, X_train, W_train)\nte_pred_aml_regressor_6 = est.effect(X_test)\n```\n\n Experiment model_t_20_01_28-14_36_01 has started.\n Experiment model_t_20_01_28-14_36_01 completed.\n Experiment model_y_20_01_28-14_37_57 has started.\n Experiment model_y_20_01_28-14_37_57 completed.\n Experiment model_t_20_01_28-14_39_43 has started.\n Experiment model_t_20_01_28-14_39_43 completed.\n Experiment model_y_20_01_28-14_41_26 has started.\n Experiment model_y_20_01_28-14_41_26 completed.\n Experiment model_final_20_01_28-14_43_03 has started.\n Experiment model_final_20_01_28-14_43_03 completed.\n\n\n### Performance Visualization\n\n\n```python\nplt.figure(figsize=(10,6))\nplt.plot(X_test, te_pred_cv_regressor_6, label='DML Polynomial Features with Grid Search Regressor')\nplt.plot(X_test, te_pred_aml_regressor_6, label='DML Polynomial Features with AML Regressor')\nexpected_te = np.array([te(x_i) for x_i in X_test])\nplt.plot(X_test, expected_te, 'b--', label='True effect')\nplt.ylabel('Treatment Effect')\nplt.xlabel('x')\nplt.ylim(-0.5, 1.5) \nplt.legend()\nplt.show()\n```\n\n## Automated ML for Metalearners\n\n### DGP\n\nWe use the Response Surface B from [Hill (2011)](https://www.tandfonline.com/doi/pdf/10.1198/jcgs.2010.08162) to generate sythetic outcome surfaces from real-world covariates and treatment assignments (Infant Health Development Program data). Since the original data was part of a randomized trial, a subset of the treated infants (those with non-white mothers) has been removed from the data in order to mimic the observational data setting. For more details, see [Hill (2011)](https://www.tandfonline.com/doi/pdf/10.1198/jcgs.2010.08162).\n\n\nThe DGP is described by the following equations:\n\n$\nY(0) = e^{(X+W)\\beta} + \\epsilon_0, \\;\\epsilon_0 \\sim N(0, 1)\\\\\nY(1) = X\\beta - \\omega + \\epsilon_1, \\;\\epsilon_1 \\sim N(0, 1)\\\\\n$\n\nwhere $X$ is a covariate matrix, $W$ is a constant matrix with entries equal to $0.5$ and $w$ is a constant calculated such that the CATT equals $4$.\n\n\n```python\nfrom econml.metalearners import TLearner, SLearner, XLearner, DomainAdaptationLearner\nfrom econml.data.dgps import ihdp_surface_B\nY, T, X, expected_te = ihdp_surface_B()\n```\n\n\n```python\n# Instantiate T learner\nT_learner_rf = TLearner(grid_search_reg())\n# Train T_learner\nT_learner_rf.fit(Y, T, X)\n# Estimate treatment effects on test data\nT_te_rf = T_learner_rf.effect(X)\n```\n\n\n```python\n# Instantiate T learner\nAutomatedTLearner = addAutomatedML(TLearner)\nT_learner_aml = AutomatedTLearner(models = automl_config_reg)\n# Train T_learner\nT_learner_aml.fit(Y, T, X)\n# Estimate treatment effects on test data\nT_te_aml = T_learner_aml.effect(X)\n```\n\n Experiment models_20_01_27-12_04_27 has started.\n Experiment models_20_01_27-12_04_27 completed.\n Experiment models_20_01_27-12_06_04 has started.\n Experiment models_20_01_27-12_06_04 completed.\n\n\n\n```python\n# Visualization of bias distribution\nplt.violinplot([np.abs(T_te_rf - expected_te),\n np.abs(T_te_aml - expected_te)\n ], showmeans=True)\nplt.ylabel(\"Bias distribution\")\nplt.xticks([1, 2], ['Grid Search', 'AutoML'])\nplt.show()\n```\n\n# S Learner\n\n\n```python\n# Instantiate S learner\noverall_model = grid_search_reg()\nS_learner_rf = SLearner(overall_model)\n# Train S_learner\nS_learner_rf.fit(Y, T, X)\n# Estimate treatment effects on test data\nS_te_rf = S_learner_rf.effect(X)\n```\n\n\n```python\n# Instantiate S learner\nAutomatedSLearner = addAutomatedML(SLearner)\nS_learner_aml = AutomatedSLearner(overall_model= automl_config_reg)\n# Train S_learner\nS_learner_aml.fit(Y, T, X)\n# Estimate treatment effects on test data\nS_te_aml = S_learner_aml.effect(X)\n```\n\n Experiment overall_model_20_01_27-12_16_18 has started.\n Experiment overall_model_20_01_27-12_16_18 completed.\n\n\n\n```python\n# Visualization of bias distribution\nplt.violinplot([np.abs(S_te_rf - expected_te),\n np.abs(S_te_aml - expected_te)\n ], showmeans=True)\nplt.ylabel(\"Bias distribution\")\nplt.xticks([1, 2], ['Grid Search', 'AutoML'])\nplt.show()\n```\n\n# Domain Adaptation Learner\n\n\n```python\nmodels = grid_search_reg()\nfinal_models = grid_search_reg()\nDA_learner_rf = DomainAdaptationLearner(models=models, final_models=final_models)\n# Train DA_learner\nDA_learner_rf.fit(Y, T, X)\n# Estimate treatment effects on test data\nDA_rf_te = DA_learner_rf.effect(X)\n```\n\n\n```python\nmodels = automl_config_reg\nfinal_models = automl_config_reg\nAutomatedDomainAdaptationLearner = addAutomatedML(DomainAdaptationLearner)\nDA_learner_aml = AutomatedDomainAdaptationLearner(models=models, final_models=final_models)\n# Train X_learner\nDA_learner_aml.fit(Y, T, X)\n# Estimate treatment effects on test data\nDA_te_aml = DA_learner_aml.effect(X)\n```\n\n Experiment models_20_01_27-13_19_40 has started.\n Experiment models_20_01_27-13_19_40 completed.\n Experiment models_20_01_27-13_21_20 has started.\n Experiment models_20_01_27-13_21_20 completed.\n Experiment final_models_20_01_27-13_23_01 has started.\n Experiment final_models_20_01_27-13_23_01 completed.\n\n\n\n```python\n# Visualization of bias distribution\nplt.violinplot([np.abs(DA_rf_te - expected_te),\n np.abs(DA_te_aml - expected_te)\n ], showmeans=True)\nplt.ylabel(\"Bias distribution\")\nplt.xticks([1, 2], ['Grid Search', 'AutoML'])\nplt.show()\n```\n\n\n```python\nY, T, X, _ = ihdp_surface_B()\nest = AutomatedNonParamDMLCateEstimator(model_y=automl_config_reg,\n model_t=automl_config_clf,\n model_final=automl_config_reg, featurizer=None,\n discrete_treatment=True)\nest.fit(Y, T, X)\n_ = est.effect(X)\n```\n\n Experiment model_t_20_01_27-17_24_47 has started.\n Experiment model_t_20_01_27-17_24_47 completed.\n Experiment model_y_20_01_27-17_27_27 has started.\n Experiment model_y_20_01_27-17_27_27 completed.\n Experiment model_t_20_01_27-17_29_51 has started.\n Experiment model_t_20_01_27-17_29_51 completed.\n Experiment model_y_20_01_27-17_32_20 has started.\n\n\n WARNING - Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProtocolError('Connection aborted.', OSError(\"(10054, 'WSAECONNRESET')\",))': /azureml/ExperimentRun/dcid.AutoML_ddd4742b-4d4c-46bc-b036-e42e9a60b9a1_2/outputs/scoring_file_v_1_0_0.py?sv=2019-02-02&sr=b&sig=Z%2FSYw75Z5M38OuM6L4l3run1WpF%2BB6tr5%2FIdiJkJumM%3D&st=2020-01-27T22%3A24%3A24Z&se=2020-01-28T22%3A34%3A24Z&sp=rcw&comp=block&blockid=TURBd01EQXdNREF3TURBd01EQXdNREF3TURBd01EQXdNREF3TURBd01EQSUzRA%3D%3D&timeout=30\n\n\n Experiment model_y_20_01_27-17_32_20 completed.\n Experiment model_final_20_01_27-17_34_55 has started.\n Experiment model_final_20_01_27-17_34_55 completed.\n\n", "meta": {"hexsha": "6e2eb81790accddee717b3837115a28599d97983", "size": 311064, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/AutomatedML/Automated Machine Learning For EconML.ipynb", "max_stars_repo_name": "khwilson/EconML", "max_stars_repo_head_hexsha": "80264390106a8c57e2286177a2c4f8a47b51a32e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-18T04:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T04:07:07.000Z", "max_issues_repo_path": "notebooks/AutomatedML/Automated Machine Learning For EconML.ipynb", "max_issues_repo_name": "khwilson/EconML", "max_issues_repo_head_hexsha": "80264390106a8c57e2286177a2c4f8a47b51a32e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/AutomatedML/Automated Machine Learning For EconML.ipynb", "max_forks_repo_name": "khwilson/EconML", "max_forks_repo_head_hexsha": "80264390106a8c57e2286177a2c4f8a47b51a32e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:29:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T21:29:36.000Z", "avg_line_length": 235.833206975, "max_line_length": 72580, "alphanum_fraction": 0.910430008, "converted": true, "num_tokens": 7675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3221610130544784}} {"text": "\n\n# **The Reformer - Pushing the limits of language modeling**\n\n***How the Reformer uses less than 8GB of RAM to train on sequences of half a million tokens***\n\nThe Reformer model as introduced by [Kitaev, Kaiser et al. (2020)](https://arxiv.org/pdf/2001.04451.pdf) is one of the most memory-efficient transformer models for long sequence modeling as of today.\n\nRecently, long sequence modeling has experienced a surge of interest as can be seen by the many submissions from this year alone - [Beltagy et al. (2020)](https://arxiv.org/abs/2004.05150), [Roy et al. (2020)](https://arxiv.org/abs/2003.05997), [Tay et al.](https://arxiv.org/abs/2002.11296), [Wang et al.](https://arxiv.org/abs/2006.04768) to name a few. \nThe motivation behind long sequence modeling is that many tasks in NLP, *e.g.* summarization, question answering, require the model to process longer input sequences than models, such as BERT, are able to handle. In tasks that require the model to process a large input sequence, long sequence models do not have to cut the input sequence to avoid memory overflow and thus have been shown to outperform standard \"BERT\"-like models *cf.* [Beltagy et al. (2020)](https://arxiv.org/abs/2004.05150). \n\nThe Reformer pushes the limit of longe sequence modeling by its ability to process up to half a million tokens at once as shown in this [demo](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb). As a comparison, a conventional `bert-base-uncased` model limits the input length to only 512 tokens. In Reformer, each part of the standard transformer architecture is re-engineered to optimize for minimal memory requirement without a significant drop in performance.\n\nThe memory improvements can be attributed to **4** features which the Reformer authors introduced to the transformer world:\n\n1. **Reformer Self-Attention Layer** - *How to efficiently implement self-attention without being restricted to a local context?*\n2. **Chunked Feed Forward Layers** - *How to get a better time-memory trade-off for large feed forward layers?*\n3. **Reversible Residual Layers** - *How to drastically reduce memory consumption in training by a smart residual architecture?*\n4. **Axial Positional Encodings** - *How to make positional encodings usable for extremely large input sequences?*\n\nThe goal of this blog post is to give the reader an **in-depth** understanding of each of the four Reformer features mentioned above. While the explanations are focussed on the Reformer, the reader should get a better intuition under which circumstances each of the four features can be effective for other transformer models as well. \nThe four sections are only loosely connected, so they can very well be read individually.\n\nReformer is part of the 🤗Transformers library. For all users of the Reformer, it is advised to go through this very detailed blog post to better understand how the model works and how to correctly set its configuration. All equations are accompanied by their equivalent name for the Reformer config, *e.g.* `config.`, so that the reader can quickly relate to the official docs and configuration file.\n\n**Note**: *Axial Positional Encodings* are not explained in the official Reformer paper, but are extensively used in the official codebase. This blog post gives the first in-depth explanation of Axial Positional Encodings.\n\n## **1. Reformer Self-Attention Layer**\n\nReformer uses two kinds of special self-attention layers: *local* self-attention layers and Locality Sensitive Hashing (*LSH*) self-attention layers.\n\nTo better introduce these new self-attention layers, we will briefly recap \nconventional self-attention as introduced in [Vaswani et al. 2017](https://arxiv.org/abs/1706.03762).\n\nThis blog post uses the same notation and coloring as the popular blog post [The illustrated transformer](http://jalammar.github.io/illustrated-transformer/), so the reader is strongly advised to read this blog first. \n\n**Important**: While Reformer was originally introduced for causal self-attention, it can very well be used for bi-directional self-attention as well. In this post, Reformer's self-attention is presented for *bidirectional* self-attention.\n\n### **Recap Global Self-Attention**\n\nThe core of every Transformer model is the **self-attention** layer. To recap the conventional self-attention layer, which we refer to here as the **global self-attention** layer, let us assume we apply a transformer layer on the embedding vector sequence $\\mathbf{X} = \\mathbf{x}_1, \\ldots, \\mathbf{x}_n$ where each vector $\\mathbf{x}_i$ is of size `config.hidden_size`, *i.e.* $d_h$. \n\nIn short, a global self-attention layer projects $\\mathbf{X}$ to the query, key and value matrices $\\mathbf{Q}, \\mathbf{K}, \\mathbf{V}$ and computes the output $\\mathbf{Z}$ using the *softmax* operation as follows:\n$\\mathbf{Z} = \\text{SelfAttn}(\\mathbf{X}) = \\text{softmax}(\\mathbf{Q}\\mathbf{K}^T) \\mathbf{V}$ with $\\mathbf{Z}$ being of dimension $d_h \\times n$ (leaving out the key normalization factor and self-attention weights $\\mathbf{W}^{O}$ for simplicity). For more detail on the complete transformer operation, see [the illustrated transformer](http://jalammar.github.io/illustrated-transformer/).\n\nVisually, we can illustrate this operation as follows for $n=16, d_h=3$:\n\n\n\n*Note*: For all visualizations `batch_size` and `config.num_attention_heads` is assumed to be 1. Some vectors, *e.g.* $\\mathbf{x_3}$ and its corresponding output vector $\\mathbf{z_3}$ are marked so that *LSH self-attention* can later be better explained. The presented logic can effortlessly be extended for multi-head self-attention (`config.num_attention_heads` > 1). The reader is advised to read [the illustrated transformer](http://jalammar.github.io/illustrated-transformer/) as a reference for multi-head self-attention.\n\nImportant to remember is that for each output vector $\\mathbf{z}_i$, the whole input sequence $\\mathbf{X}$ is processed. The tensor of the inner dot-product $\\mathbf{Q}\\mathbf{K}^T$ has an asymptotic memory complexity of $\\mathcal{O}(n^2)$ which usually represents the memory bottleneck in a transformer model. \n\nThis is also the reason why `bert-base-cased` has a `config.max_position_embedding_size` of only 512.\n\n### **Local Self-Attention**\n\n**Local self-attention** is the obvious solution to reducing the $\\mathcal{O}(n^2)$ memory bottleneck, allowing us to model longer sequences with a reduced computational cost. In local self-attention the input $\\mathbf{X} = \\mathbf{X}_{1:n} = \\mathbf{x}_1, ... \\mathbf{x}_n$ is cut into $n_c$ chunks: $\\mathbf{X} = \\left[\\mathbf{X}_{1:l_c}, \\ldots, \\mathbf{X}_{(n_c - 1) * l_c : n_c * l_c}\\right]$ each of length `config.local_chunk_length`, *i.e.* $l_c$, and subsequently global self-attention is applied on each chunk separately.\n\nLet's take our input sequence for $n=16, d_h=3$ again for visualization:\n\n\n\nAssuming $l_c = 4, n_c = 4$, chunked attention can be illustrated as follows:\n\n\n\nAs can be seen, the attention operation is applied for each chunk $\\mathbf{X}_{1:4}, \\mathbf{X}_{5:8}, \\mathbf{X}_{9:12}, \\mathbf{X}_{13:16}$ individually.\nThe first drawback of this architecture becomes obvious: Some input vectors have no access to their immediate context, *e.g.* $\\mathbf{x}_9$ has no access to $\\mathbf{x}_8$ and vice-versa in our example. This is problematic because these tokens are not able to learn word representations that take their immediate context into account.\n\nA simple remedy is to augment each chunk with `config.local_num_chunks_before`, *i.e.* $n_p$, chunks and `config.local_num_chunks_after`, *i.e.* $n_a$, so that every input vector has at least access to $n_p$ previous input vectors and $n_a$ following input vectors. This can also be understood as chunking with overlap whereas $n_p$ and $n_a$ define the amount of overlap each chunk has with all previous chunks and following chunks. We denote this extended local self-attention as follows: \n\n$\\mathbf{Z}^{\\text{loc}} = \\left[\\mathbf{Z}_{1:l_c}^{\\text{loc}}, \\ldots, \\mathbf{Z}_{(n_c - 1) * l_c : n_c * l_c}^{\\text{loc}}\\right]$ with $\\mathbf{Z}_{l_c * (i - 1) + 1 : l_c * i}^{\\text{loc}} = \\text{SelfAttn}(\\mathbf{X}_{l_c * (i - 1 - n_p) + 1: l_c * (i + n_a)})\\left[n_p * l_c: -n_a * l_c\\right], \\forall i \\in \\{1, \\ldots, n_c \\}$.\n\nOkay, this formula looks quite complicated. Let's make it easier.\nIn Reformer's self-attention layers $n_a$ is usually set to 0 and $n_p$ is set to 1, so let's write down the formula again for $i = 1$:\n\n$\\mathbf{Z}_{1:l_c}^{\\text{loc}} = \\text{SelfAttn}(\\mathbf{X}_{-l_c + 1: l_c})\\left[l_c:\\right]$\n\nWe notice that we have a circular relationship so that the first segment can attend the last segment as well. Let's illustrate this slightly enhanced local attention again. First, we apply self-attention within each windowed segment and keep only the central output segment.\n\n\n\nFinally, the relevant output is concatenated to $\\mathbf{Z}^{\\text{loc}}$ and looks as follows.\n\n\n\n*Note that local self-attention is implemented efficiently way so that no output is computed and subsequently \"thrown-out\" as shown here for illustration purposes by the red cross.*\n\nIt's important to note here that extending the input vectors for each chunked self-attention function allows *each* single output vector $\\mathbf{z}_i$ of this self-attention function to learn better vector representations. *E.g.* each of the output vectors $\\mathbf{z}_{5}^{\\text{loc}}, \\mathbf{z}_{6}^{\\text{loc}}, \\mathbf{z}_{7}^{\\text{loc}}, \\mathbf{z}_{8}^{\\text{loc}}$ can take into account all of the input vectors $\\mathbf{X}_{1:8}$ to learn better representations.\n\nThe gain in memory consumption is quite obvious: The $\\mathcal{O}(n^2)$ memory complexity is broken down for each segment individually so that the total asymptotic memory consumption is reduced to $\\mathcal{O}(n_c * l_c^2) = \\mathcal{O}(n * l_c)$.\n\nThis enhanced local self-attention is better than the vanilla local self-attention architecture but still has a major drawback in that every input vector can only attend to a local context of predefined size. For NLP tasks that do not require the transformer model to learn long-range dependencies between the input vectors, which include arguably *e.g.* speech recognition, named entity recognition and causal language modeling of short sentences, this might not be a big issue. Many NLP tasks do require the model to learn long-range dependencies, so that local self-attention could lead to significant performance degradation, *e.g.* \n* *Question-answering*: the model has to learn the relationship between the question tokens and relevant answer tokens which will most likely not be in the same local range\n* *Multiple-Choice*: the model has to compare multiple answer token segments to each other which are usually separated by a significant length\n* *Summarization*: the model has to learn the relationship between a long sequence of context tokens and a shorter sequence of summary tokens, whereas the relevant relationships between context and summary can most likely not be captured by local self-attention\n* etc...\n\nLocal self-attention on its own is most likely not sufficient for the transformer model to learn the relevant relationships of input vectors (tokens) to each other.\n\nTherefore, Reformer additionally employs an efficient self-attention layer that approximates global self-attention, called *LSH self-attention*.\n\n### **LSH Self-Attention**\n\nAlright, now that we have understood how local self-attention works, we can take a stab at the probably most innovative piece of Reformer: **Locality sensitive hashing (LSH) Self-Attention**. \n\nThe premise of LSH self-attention is to be more or less as efficient as local self-attention while approximating global self-attention.\n\nLSH self-attention relies on the LSH algorithm as presented in [Andoni et al (2015)](https://arxiv.org/abs/1509.02897), hence its name.\n\nThe idea behind LSH self-attention is based on the insight that if $n$ is large, the softmax applied on the $\\mathbf{Q}\\mathbf{K}^T$ attention dot-product weights only very few value vectors with values significantly larger than 0 for each query vector. \n\nLet's explain this in more detail.\nLet $\\mathbf{k}_i \\in \\mathbf{K} = \\left[\\mathbf{k}_1, \\ldots, \\mathbf{k}_n \\right]^T$ and $\\mathbf{q}_i \\in \\mathbf{Q} = \\left[\\mathbf{q}_1, \\ldots, \\mathbf{q}_n\\right]^T$ be the key and query vectors. For each $\\mathbf{q}_i$, the computation $\\text{softmax}(\\mathbf{q}_i^T \\mathbf{K}^T)$ can be approximated by using only those key vectors of $\\mathbf{k}_j$ that have a high cosine similarity with $\\mathbf{q}_i$. This owes to the fact that the softmax function puts exponentially more weight on larger input values.\nSo far so good, the next problem is to efficiently find the vectors that have a\nhigh cosine similarity with $\\mathbf{q}_i$ for all $i$.\n\nFirst, the authors of Reformer notice that sharing the query and key projections: $\\mathbf{Q} = \\mathbf{K}$ does not impact the performance of a transformer model${}^1$. Now, instead of having to find the key vectors of high cosine similarity for each query vector $q_i$, only the cosine similarity of query vectors to each other has to be found. \nThis is important because there is a transitive property to the query-query vector dot product approximation: If $\\mathbf{q}_i$ has a high cosine similarity to the query vectors $\\mathbf{q}_j$ and $\\mathbf{q}_k$, then $\\mathbf{q}_j$ also has a high cosine similarity to $\\mathbf{q}_k$. Therefore, the query vectors can be clustered into buckets, such that all query vectors that belong to the same bucket have a high cosine similarity to each other. Let's define $C_m$ as the *mth* set of position indices, such that their corresponding query vectors are in the same bucket: $C_m = \\{ i | \\text{ s.t. } \\mathbf{q}_i \\in \\text{mth cluster}\\}$ and `config.num_buckets`, *i.e.* $n_b$, as the number of buckets.\n\nFor each set of indices $C_m$, the softmax function on the corresponding bucket of query vectors $\\text{softmax}(\\mathbf{Q}_{i \\in C_m} \\mathbf{Q}^T_{i \\in C_m})$ approximates the softmax function of global self-attention with shared query and key projections $\\text{softmax}(\\mathbf{q}_i^T \\mathbf{Q}^T)$ for all position indices $i$ in $C_m$.\n\nSecond, the authors make use of the **LSH** algorithm to cluster the query vectors into a predefined number of buckets $n_b$. The LSH algorithm is an ideal choice here because it is very efficient and is an approximation of the nearest neighbor algorithm for cosine similarity. Explaining the LSH scheme is out-of-scope for this notebook, so let's just keep in mind that for each vector $\\mathbf{q}_i$ the LSH algorithm attributes its position index $i$ to one of $n_b$ predefined buckets, *i.e.* $\\text{LSH}(\\mathbf{q}_i) = m$ with $i \\in \\{1, \\ldots, n\\}$ and $m \\in \\{1, \\ldots, n_b\\}$.\n\nVisually, we can illustrate this as follows for our original example:\n\n\n\nThird, it can be noted that having clustered all query vectors in $n_b$ buckets, the corresponding set of indices $C_m$ can be used to permute the input vectors $\\mathbf{x}_1, \\ldots, \\mathbf{x}_n$ accordingly${}^2$ so that shared query-key self-attention can be applied piecewise similar to local attention. \n\nLet's clarify with our example input vectors $\\mathbf{X} = \\mathbf{x}_1, ..., \\mathbf{x}_{16}$ and assume `config.num_buckets=4` and `config.lsh_chunk_length = 4`. Looking at the graphic above we can see that we have assigned each query vector $\\mathbf{q}_1, \\ldots, \\mathbf{q}_{16}$ to one of the clusters $\\mathcal{C}_1, \\mathcal{C}_2, \\mathcal{C}_3, \\mathcal{C}_4$. If we now sort the corresponding input vectors $\\mathbf{x}_1, \\ldots, \\mathbf{x}_{16}$ accordingly, we get the following permuted input $\\mathbf{X'}$:\n\n\n\nThe self-attention mechanism should be applied for each cluster individually so that for each cluster $\\mathcal{C}_m$ the corresponding output is calculated as follows: $\\mathbf{Z}^{\\text{LSH}}_{i \\in \\mathcal{C}_m} = \\text{SelfAttn}_{\\mathbf{Q}=\\mathbf{K}}(\\mathbf{X}_{i \\in \\mathcal{C}_m})$.\n\nLet's illustrate this again for our example.\n\n\n\nAs can be seen, the self-attention function operates on different sizes of matrices, which is suboptimal for efficient batching in GPU and TPU. \n\nTo overcome this problem, the permuted input can be chunked the same way it is done for local attention so that each chunk is of size `config.lsh_chunk_length`. By chunking the permuted input, a bucket might be split into two different chunks. To remedy this problem, in LSH self-attention each chunk attends to its previous chunk `config.lsh_num_chunks_before=1` in addition to itself, the same way local self-attention does (`config.lsh_num_chunks_after` is usually set to 0). This way, we can be assured that all vectors in a bucket attend to each other with a high probability${}^3$.\n\nAll in all for all chunks $k \\in \\{1, \\ldots, n_c\\}$, LSH self-attention can be noted down as follows:\n\n$\\mathbf{Z'}_{l_c * k + 1:l_c * (k + 1)}^{\\text{LSH}} = \\text{SelfAttn}_{\\mathbf{Q} = \\mathbf{K}}(\\mathbf{X'}_{l_c * k + 1): l_c * (k + 1)})\\left[l_c:\\right]$\n\nwith $\\mathbf{X'}$ and $\\mathbf{Z'}$ being the input and output vectors permuted according to the LSH algorithm.\nEnough complicated formulas, let's illustrate LSH self-attention.\n\nThe permuted vectors $\\mathbf{X'}$ as shown above are chunked and shared query key self-attention is applied to each chunk.\n\n\n\nFinally, the output $\\mathbf{Z'}^{\\text{LSH}}$ is reordered to its original permutation.\n\n\n\nOne important feature to mention here as well is that the accuracy of LSH self-attention can be improved by running LSH self-attention `config.num_hashes`, *e.g.* $n_h$ times in parallel, each with a different random LSH hash. \nBy setting `config.num_hashes > 1`, for each output position $i$, multiple output vectors $\\mathbf{z}^{\\text{LSH}, 1}_i, \\ldots, \\mathbf{z}^{\\text{LSH}, n_h}_i$ are computed and subsequently merged: $\\mathbf{z}^{\\text{LSH}}_i = \\sum_k^{n_h} \\mathbf{Z}^{\\text{LSH}, k}_i * \\text{weight}^k_i$. The $\\text{weight}^k_i$ represents the importance of the output vectors $\\mathbf{z}^{\\text{LSH}, k}_i$ of hashing round $k$ in comparison to the other hashing rounds, and is exponentially proportional to the normalization term of their softmax computation. The intuition behind this is that if the corresponding query vector $\\mathbf{q}_i^{k}$ have a high cosine similarity with all other query vectors in its respective chunk, then the softmax normalization term of this chunk tends to be high, so that the corresponding output vectors $\\mathbf{q}_i^{k}$ should be a better approximation to global attention and thus receive more weight than output vectors of hashing rounds with a lower softmax normalization term. For more detail see Appendix A of the [paper](https://arxiv.org/pdf/2001.04451.pdf). For our example, multi-round LSH self-attention can be illustrated as follows.\n\n\n\nGreat. That's it. Now we know how LSH self-attention works in Reformer. \n\nRegarding the memory complexity, we now have two terms that compete which each other to be the memory bottleneck: the dot-product: $\\mathcal{O}(n_h * n_c * l_c^2) = \\mathcal{O}(n * n_h * l_c)$ and the required memory for LSH bucketing: $\\mathcal{O}(n * n_h * \\frac{n_b}{2})$ with $l_c$ being the chunk length. Because for large $n$, the number of buckets $\\frac{n_b}{2}$ grows much faster than the chunk length $l_c$, the user can again factorize the number of buckets `config.num_buckets` as explained [here](https://huggingface.co/transformers/model_doc/reformer.html#lsh-self-attention).\n\nLet's recap quickly what we have gone through above:\n\n1. We want to approximate global attention using the knowledge that the softmax operation only puts significant weights on very few key vectors.\n2. If key vectors are equal to query vectors this means that *for each* query vector $\\mathbf{q}_i$, the softmax only puts significant weight on other query vectors that are similar in terms of cosine similarity.\n3. This relationship works in both ways, meaning if $\\mathbf{q}_j$ is similar to $\\mathbf{q}_i$ than $\\mathbf{q}_j$ is also similar to $\\mathbf{q}_i$, so that we can do a global clustering before applying self-attention on a permuted input.\n4. We apply local self-attention on the permuted input and re-order the output to its original permutation.\n\n---\n${}^{1}$ The authors run some preliminary experiments confirming that shared query key self-attention performs more or less as well as standard self-attention.\n\n${}^{2}$ To be more exact the query vectors within a bucket are sorted according to their original order. This means if, *e.g.* the vectors $\\mathbf{q}_1, \\mathbf{q}_3, \\mathbf{q}_7$ are all hashed to bucket 2, the order of the vectors in bucket 2 would still be $\\mathbf{q}_1$, followed by $\\mathbf{q}_3$ and $\\mathbf{q}_7$.\n\n${}^3$ On a side note, it is to mention the authors put a mask on the query vector $\\mathbf{q}_i$ to prevent the vector from attending to itself. Because the cosine similarity of a vector to itself will always be as high or higher than the cosine similarity to other vectors, the query vectors in shared query key self-attention are strongly discouraged to attend to themselves.\n\n\n\n### **Benchmark**\n\nBenchmark tools were recently added to Transformers - see [here](https://github.com/huggingface/transformers/blob/master/notebooks/05-benchmark.ipynb) for a more detailed explanation.\n\nTo show how much memory can be saved using \"local\" + \"LSH\" self-attention, the Reformer model `google/reformer-enwik8` is benchmarked for different `local_attn_chunk_length` and `lsh_attn_chunk_length`. The default configuration and usage of the `google/reformer-enwik8` model can be checked in more detail [here](https://huggingface.co/google/reformer-enwik8).\n\nLet's first do some necessary imports and installs.\n\n\n```\n#@title Installs and Imports\n# pip installs\n!pip -qq install git+https://github.com/huggingface/transformers.git\n!pip install -qq py3nvml\n\nfrom transformers import ReformerConfig, PyTorchBenchmark, PyTorchBenchmarkArguments\n```\n\nFirst, let's benchmark the memory usage of the Reformer model using *global* self-attention. This can be achieved by setting `lsh_attn_chunk_length` = `local_attn_chunk_length` = 8192 so that for all input sequences smaller or equal to 8192, the model automatically switches to global self-attention.\n\n\n```\nconfig = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", lsh_attn_chunk_length=16386, local_attn_chunk_length=16386, lsh_num_chunks_before=0, local_num_chunks_before=0)\nbenchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[2048, 4096, 8192, 16386], batch_sizes=[1], models=[\"Reformer\"], no_speed=True, no_env_print=True)\nbenchmark = PyTorchBenchmark(configs=[config], args=benchmark_args)\nresult = benchmark.run()\n```\n\n\n HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1279.0, style=ProgressStyle(description…\n\n\n \n 1 / 1\n Doesn't fit on GPU. CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 11.17 GiB total capacity; 8.87 GiB already allocated; 1.92 GiB free; 8.88 GiB reserved in total by PyTorch)\n \n ==================== INFERENCE - MEMORY - RESULT ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Reformer 1 2048 1465 \n Reformer 1 4096 2757 \n Reformer 1 8192 7893 \n Reformer 1 16386 N/A \n --------------------------------------------------------------------------------\n\n\nThe longer the input sequence, the more visible is the quadratic relationship $\\mathcal{O}(n^2)$ between input sequence and peak memory usage. As can be seen, in practice it would require a much longer input sequence to clearly observe that doubling the input sequence quadruples the peak memory usage.\n\nFor this a `google/reformer-enwik8` model using global attention, a sequence length of over 16K results in a memory overflow.\n\nNow, let's activate *local* and *LSH* self-attention by using the model's default parameters.\n\n\n```\n config = ReformerConfig.from_pretrained(\"google/reformer-enwik8\")\n benchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[2048, 4096, 8192, 16384, 32768, 65436], batch_sizes=[1], models=[\"Reformer\"], no_speed=True, no_env_print=True)\n benchmark = PyTorchBenchmark(configs=[config], args=benchmark_args)\n result = benchmark.run()\n```\n\n 1 / 1\n Doesn't fit on GPU. CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 11.17 GiB total capacity; 7.85 GiB already allocated; 1.74 GiB free; 9.06 GiB reserved in total by PyTorch)\n Doesn't fit on GPU. CUDA out of memory. Tried to allocate 4.00 GiB (GPU 0; 11.17 GiB total capacity; 6.56 GiB already allocated; 3.99 GiB free; 6.81 GiB reserved in total by PyTorch)\n \n ==================== INFERENCE - MEMORY - RESULT ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Reformer 1 2048 1785 \n Reformer 1 4096 2621 \n Reformer 1 8192 4281 \n Reformer 1 16384 7607 \n Reformer 1 32768 N/A \n Reformer 1 65436 N/A \n --------------------------------------------------------------------------------\n\n\nAs expected using local and LSH self-attention is much more memory efficient for longer input sequences, so that the model runs out of memory only at 16K tokens for a 11GB RAM GPU in this notebook.\n\n## **2. Chunked Feed Forward Layers**\n\nTransformer-based models often employ very large feed forward layers after the self-attention layer in parallel. Thereby, this layer can take up a significant amount of the overall memory and sometimes even represent the memory bottleneck of a model.\nFirst introduced in the Reformer paper, feed forward chunking is a technique that allows to effectively trade better memory consumption for increased time consumption.\n\n\n### **Chunked Feed Forward Layer in Reformer**\n\nIn Reformer, the *LSH*- or *local* self-attention layer is usually followed by a residual connection, which then defines the first part in a *transformer block*. For more detail on this please refer to this [blog](http://jalammar.github.io/illustrated-transformer/). \n\nThe output of the first part of the *transformer block*, called *normed self-attention* output can be written as $\\mathbf{\\overline{Z}} = \\mathbf{Z} + \\mathbf{X}$, with $\\mathbf{Z}$ being either $\\mathbf{Z}^{\\text{LSH}}$ or $\\mathbf{Z}^\\text{loc}$ in Reformer.\n\nFor our example input $\\mathbf{x}_1, \\ldots, \\mathbf{x}_{16}$, we illustrate the normed self-attention output as follows.\n\n\n\nNow, the second part of a *transformer block* usually consists of two feed forward layers$^{1}$, defined as $\\text{Linear}_{\\text{int}}(\\ldots)$ that processes $\\mathbf{\\overline{Z}}$, to an intermediate output $\\mathbf{Y}_{\\text{int}}$ and $\\text{Linear}_{\\text{out}}(\\ldots)$ that processes the intermediate output to the output $\\mathbf{Y}_{\\text{out}}$. The two feed forward layers can be defined by $\\mathbf{Y}_{\\text{out}} = \\text{Linear}_{\\text{out}}(\\mathbf{Y}_\\text{int}) = \n\\text{Linear}_{\\text{out}}(\\text{Linear}_{\\text{int}}(\\mathbf{\\overline{Z}}))$.\n\nIt is important to remember at this point that mathematically the output of a feed forward layer at position $\\mathbf{y}_{\\text{out}, i}$ only depends on the input at this position $\\mathbf{\\overline{y}}_i$. In contrast to the self-attention layer, every output $\\mathbf{y}_{\\text{out}, i}$ is therefore completely independent of all inputs $\\mathbf{\\overline{y}}_{j \\ne i}$ of different positions. \n\nLet's illustrate the feed forward layers for $\\mathbf{\\overline{z}}_1, \\ldots, \\mathbf{\\overline{z}}_{16}$.\n\n\n\nAs can be depicted from the illustration, all input vectors $\\mathbf{\\overline{z}}_i$ are processed by the same feed forward layer in parallel.\n\nIt becomes interesting when one takes a look at the output dimensions of the feed forward layers. In Reformer, the output dimension of $\\text{Linear}_{\\text{int}}$ is defined as `config.feed_forward_size`, *e.g.* $d_f$, and the output dimension of $\\text{Linear}_{\\text{int}}$ is defined as `config.hidden_size`, *i.e.* $d_h$. \n\nThe Reformer authors observed that in a transformer model the intermediate dimension $d_f$ usually tends to be much larger than the output dimension$^{2}$ $d_h$. This means that the tensor $\\mathbf{\\mathbf{Y}}_\\text{int}$ of dimension $d_f \\times n$ allocates a significant amount of the total memory and can even become the memory bottleneck.\n\nTo get a better feeling for the differences in dimensions let's picture the matrices $\\mathbf{Y}_\\text{int}$ and $\\mathbf{Y}_\\text{out}$ for our example.\n\n\n\nIt is becoming quite obvious that the tensor $\\mathbf{Y}_\\text{int}$ holds much more memory ($\\frac{d_f}{d_h} \\times n$ as much to be exact) than $\\mathbf{Y}_{\\text{out}}$. But, is it even necessary to compute the full intermediate matrix $\\mathbf{Y}_\\text{int}$ ? Not really, because relevant is only the output matrix $\\mathbf{Y}_\\text{out}$. \nTo trade memory for speed, one can thus chunk the linear layers computation to only process one chunk at the time. Defining `config.chunk_size_feed_forward` as $c_f$, chunked linear layers are defined as $\\mathbf{Y}_{\\text{out}} = \\left[\\mathbf{Y}_{\\text{out}, 1: c_f}, \\ldots, \\mathbf{Y}_{\\text{out}, (n - c_f): n}\\right]$ with $\\mathbf{Y}_{\\text{out}, (c_f * i): (i * c_f + i)} = \\text{Linear}_{\\text{out}}(\\text{Linear}_{\\text{int}}(\\mathbf{\\overline{Z}}_{(c_f * i): (i * c_f + i)}))$. \nIn practice, it just means that the output is incrementally computed and concatenated to avoid having to store the whole intermediate tensor $\\mathbf{Y}_{\\text{int}}$ in memory.\n\nAssuming $c_f=1$ for our example we can illustrate the incremental computation of the output for position $i=9$ as follows. \n\n\n\nBy processing the inputs in chunks of size 1, the only tensors that have to be stored in memory at the same time are $\\mathbf{Y}_\\text{out}$ of a maximum size of $16 \\times d_h$, $\\mathbf{y}_{\\text{int}, i}$ of size $d_f$ and the input $\\mathbf{\\overline{Z}}$ of size $16 \\times d_h$, with $d_h$ being `config.hidden_size`$^{3}$.\n\nFinally, it is important to remember that *chunked linear layers* yield a mathematically equivalent output to conventional linear layers and can therefore be applied to all transformer linear layers. Making use of `config.chunk_size_feed_forward` therefore allows a better trade-off between memory and speed in certain use cases.\n\n---\n${}^1$ For a simpler explanation, the layer norm layer which is normally applied to $\\mathbf{\\overline{Z}}$ before being processed by the feed forward layers is omitted for now.\n\n${}^2$ In `bert-base-uncased`, *e.g.* the intermediate dimension $d_f$ is with 3072 four times larger than the output dimension $d_h$.\n\n${}^3$ As a reminder, the output `config.num_attention_heads` is assumed to be 1 for the sake of clarity and illustration in this notebook, so that the output of the self-attention layers can be assumed to be of size `config.hidden_size`.\n\nMore information on chunked linear / feed forward layers can also be found [here](https://huggingface.co/transformers/glossary.html#feed-forward-chunking) on the 🤗Transformers docs.\n\n\n### **Benchmark**\n\nLet's test how much memory can be saved by using chunked feed forward layers.\n\n\n```\n#@title Installs and Imports\n# pip installs\n!pip -qq install git+https://github.com/huggingface/transformers.git\n!pip install -qq py3nvml\n\nfrom transformers import ReformerConfig, PyTorchBenchmark, PyTorchBenchmarkArguments\n```\n\n Building wheel for transformers (setup.py) ... \u001b[?25l\u001b[?25hdone\n\n\nFirst, let's compare the default `google/reformer-enwik8` model without chunked feed forward layers to the one with chunked feed forward layers.\n\n\n```\nconfig_no_chunk = ReformerConfig.from_pretrained(\"google/reformer-enwik8\") # no chunk\nconfig_chunk = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", chunk_size_feed_forward=1) # feed forward chunk\nbenchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[1024, 2048, 4096], batch_sizes=[8], models=[\"Reformer-No-Chunk\", \"Reformer-Chunk\"], no_speed=True, no_env_print=True)\nbenchmark = PyTorchBenchmark(configs=[config_no_chunk, config_chunk], args=benchmark_args)\nresult = benchmark.run()\n```\n\n 1 / 2\n Doesn't fit on GPU. CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 11.17 GiB total capacity; 7.85 GiB already allocated; 1.74 GiB free; 9.06 GiB reserved in total by PyTorch)\n 2 / 2\n Doesn't fit on GPU. CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 11.17 GiB total capacity; 7.85 GiB already allocated; 1.24 GiB free; 9.56 GiB reserved in total by PyTorch)\n \n ==================== INFERENCE - MEMORY - RESULT ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Reformer-No-Chunk 8 1024 4281 \n Reformer-No-Chunk 8 2048 7607 \n Reformer-No-Chunk 8 4096 N/A \n Reformer-Chunk 8 1024 4309 \n Reformer-Chunk 8 2048 7669 \n Reformer-Chunk 8 4096 N/A \n --------------------------------------------------------------------------------\n\n\nInteresting, chunked feed forward layers do not seem to help here at all. The reason is that `config.feed_forward_size` is not sufficiently large to make a real difference. Only at longer sequence lengths of 4096, a slight decrease in memory usage can be seen. \n\nLet's see what happens to the memory peak usage if we increase the size of the feed forward layer by a factor of 4 and reduce the number of attention heads also by a factor of 4 so that the feed forward layer becomes the memory bottleneck.\n\n\n```\nconfig_no_chunk = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", chunk_size_feed_forward=0, num_attention_heads=2, feed_forward_size=16384) # no chuck\nconfig_chunk = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", chunk_size_feed_forward=1, num_attention_heads=2, feed_forward_size=16384) # feed forward chunk\nbenchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[1024, 2048, 4096], batch_sizes=[8], models=[\"Reformer-No-Chunk\", \"Reformer-Chunk\"], no_speed=True, no_env_print=True)\nbenchmark = PyTorchBenchmark(configs=[config_no_chunk, config_chunk], args=benchmark_args)\nresult = benchmark.run()\n```\n\n 1 / 2\n 2 / 2\n \n ==================== INFERENCE - MEMORY - RESULT ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Reformer-No-Chunk 8 1024 3743 \n Reformer-No-Chunk 8 2048 5539 \n Reformer-No-Chunk 8 4096 9087 \n Reformer-Chunk 8 1024 2973 \n Reformer-Chunk 8 2048 3999 \n Reformer-Chunk 8 4096 6011 \n --------------------------------------------------------------------------------\n\n\nNow a clear decrease in peak memory usage can be seen for longer input sequences. \nAs a conclusion, it should be noted chunked feed forward layers only makes sense for models having few attention heads and large feed forward layers.\n\n## **3. Reversible Residual Layers**\n\nReversible residual layers were first introduced in [N. Gomez et al](https://arxiv.org/abs/1707.04585) and used to reduce memory consumption when training the popular *ResNet* model. Mathematically, reversible residual layers are slightly different \nto \"real\" residual layers but do not require the activations to be saved during the forward pass, which can drastically reduce memory consumption for training.\n\n### **Reversible Residual Layers in Reformer**\n\nLet's start by investigating why training a model requires \nmuch more memory than the inference of the model.\n\nWhen running a model in inference, the required memory equals more or less the memory it takes to compute the **single** largest tensor in the model.\nOn the other hand, when training a model, the required memory equals more or less the **sum** of all differentiable tensors.\n\nThis is not surprising when considering how auto differentiation works in deep learning frameworks. These lecture [slides](https://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/slides/lec10.pdf) by Roger Grosse of the University of Toronto are great to better understand auto differentiation.\n\nIn a nutshell, in order to calculate the gradient of a differentiable function (*e.g.* a layer), auto differentiation requires the gradient of the function's output and the function's input and output tensor. While the gradients are dynamically computed and subsequently discarded, the input and output tensors (*a.k.a* activations) of a function are stored during the forward pass.\n\nAlright, let's apply this to a transformer model. A transformer model includes a stack of multiple so-called transformer layers. Each additional transformer layer forces the model to store more activations during the forward pass and thus increases the required memory for training. \nLet's take a more detailed look. A transformer layer essentially consists of two residual layers. The first residual layer represents the *self-attention* mechanism as explained in section 1) and the second residual layer represents the *linear* or feed-forward layers as explained in section 2).\n\nUsing the same notation as before, the input of a transformer layer *i.e.* $\\mathbf{X}$ is first normalized$^{1}$ and subsequently processed by the self-attention layer to get the output $\\mathbf{Z} = \\text{SelfAttn}(\\text{LayerNorm}(\\mathbf{X}))$. We will abbreviate these two layers with $G$ so that $\\mathbf{Z} = G(\\mathbf{X})$. \nNext, the residual $\\mathbf{Z}$ is added to the input $\\mathbf{\\overline{Z}} = \\mathbf{Z} + \\mathbf{X}$ and the sum is fed into the second residual layer - the two linear layers. $\\mathbf{\\overline{Z}}$ is processed by a second normalization layer, followed by the two linear layers to get $\\mathbf{Y} = \\text{Linear}(\\text{LayerNorm}(\\mathbf{Z} + \\mathbf{X}))$. We will abbreviate the second normalization layer and the two linear layers with $F$ yielding $\\mathbf{Y} = F(\\mathbf{\\overline{Z}})$. \nFinally, the residual $\\mathbf{Y}$ is added to $\\mathbf{\\overline{Z}}$ to give the output of the transformer layer $\\mathbf{\\overline{Y}} = \\mathbf{Y} + \\mathbf{\\overline{Z}}$.\n\nLet's illustrate a complete transformer layer using the example of $\\mathbf{x}_1, \\ldots, \\mathbf{x}_{16}$.\n\n\n\nTo calculate the gradient of *e.g.* the self-attention block $G$, three tensors have to be known beforehand: the gradient $\\partial \\mathbf{Z}$, the output $\\mathbf{Z}$, and the input $\\mathbf{X}$. While $\\partial \\mathbf{Z}$ can be calculated on-the-fly and discarded afterward, the values for $\\mathbf{Z}$ and $\\mathbf{X}$ have to be calculated and stored during the forward pass since it is not possible to recalculate them easily on-the-fly during backpropagation. Therefore, during the forward pass, large tensor outputs, such as the query-key dot product matrix $\\mathbf{Q}\\mathbf{K}^T$ or the intermediate output of the linear layers $\\mathbf{Y}^{\\text{int}}$, have to be stored in memory $^{2}$.\n\nHere, reversible residual layers come to our help. The idea is relatively straight-forward. The residual block is designed in a way so that instead of having to store the input and output tensor of a function, both can easily be recalculated during the backward pass so that no tensor has to be stored in memory during the forward pass. \nThis is achieved by using two input streams $\\mathbf{X}^{(1)}, \\mathbf{X}^{(2)}$, and two output streams $\\mathbf{\\overline{Y}}^{(1)}, \\mathbf{\\overline{Y}}^{(2)}$. The first residual $\\mathbf{Z}$ is computed by the first output stream $\\mathbf{Z} = G(\\mathbf{X}^{(1)})$ and subsequently added to the input of the second input stream, so that $\\mathbf{\\overline{Z}} = \\mathbf{Z} + \\mathbf{X}^{(2)}$. \nSimilarly, the residual $\\mathbf{Y} = F(\\mathbf{\\overline{Z}})$ is added to the first input stream again, so that the two output streams are defined by $\\mathbf{Y}^{(1)} = \\mathbf{Y} + \\mathbf{X}^{(1)}$ and $\\mathbf{Y}^{(2)} = \\mathbf{X}^{(2)} + \\mathbf{Z} = \\mathbf{\\overline{Z}}$.\n\nThe reversible transformer layer can be visualized for $\\mathbf{x}_1, \\ldots, \\mathbf{x}_{16}$ as follows.\n\n\n\nAs can be seen, the outputs $\\mathbf{\\overline{Y}}^{(1)}, \\mathbf{\\overline{Y}}^{(2)}$ are calculated in a very similar way than $\\mathbf{\\overline{Y}}$ of the non-reversible layer, but they are mathematically different. The authors of Reformer observe in some initial experiments that the performance of a reversible transformer model matches the performance of a standard transformer model. \nThe first visible difference to the standard transformer layer is that there are two input streams and output streams $^{3}$, which at first slightly increases the required memory for both the forward pass.\nThe two-stream architecture is crucial though for not having to save any activations during the forward pass. Let's explain. For backpropagation, the reversible transformer layer has to calculate the gradients $\\partial G$ and $\\partial F$. In addition to the gradients $\\partial \\mathbf{Y}$ and $\\partial \\mathbf{Z}$ which can be calculated on-the-fly, the tensor values $\\mathbf{Y}$, $\\mathbf{\\overline{Z}}$ have to be known for $\\partial F$ and the tensor values $\\mathbf{Z}$ and $\\mathbf{X}^{(1)}$ for $\\partial G$ to make auto-differentiation work.\n\nIf we assume to know $\\mathbf{\\overline{Y}}^{(1)}, \\mathbf{\\overline{Y}}^{(2)}$, it can easily be depicted from the graph that one can calculate $\\mathbf{X}^{(1)}, \\mathbf{X}^{(2)}$ as follows. $\\mathbf{X}^{(1)} = F(\\mathbf{\\overline{Y}}^{(1)}) - \\mathbf{\\overline{Y}}^{(1)}$. Great, now that $\\mathbf{X}^{(1)}$ is known, $\\mathbf{X}^{(2)}$ can be computed by $\\mathbf{X}^{(2)} = \\mathbf{\\overline{Y}}^{(1)} - G(\\mathbf{X}^{(1)})$. Alright now, $\\mathbf{Z}$ and $\\mathbf{Y}$ are trivial to compute via $\\mathbf{Y} = \\mathbf{\\overline{Y}}^{(1)} - \\mathbf{X}^{(1)}$ and $\\mathbf{Z} = \\mathbf{\\overline{Y}}^{(2)} - \\mathbf{X}^{(2)}$. So as a conclusion, if only the outputs $\\mathbf{\\overline{Y}}^{(1)}, \\mathbf{\\overline{Y}}^{(2)}$ of the **last** reversible transformer layer are stored during the forward pass, all other relevant activations can be derived by making use of $G$ and $F$ during the backward pass and passing $\\mathbf{X}^{(1)}$ and $\\mathbf{X}^{(2)}$. The overhead of two forward passes of $G$ and $F$ per reversible transformer layer during the backpropagation is traded against not having to store any activations during the forward pass. Not a bad deal!\n\n**Note**: Since recently, major deep learning frameworks have released code that allows to store only certain activations and recompute larger ones during the backward propagation (Tensoflow [here](https://www.tensorflow.org/api_docs/python/tf/recompute_grad) and PyTorch [here](https://pytorch.org/docs/stable/checkpoint.html)). For standard reversible layers, this still means that at least one activation has to be stored for each transformer layer, but by defining which activations can dynamically be recomputed a lot of memory can be saved.\n\n---\n$^{1}$ In the previous two sections, we have omitted the layer norm layers preceding both the self-attention layer and the linear layers. The reader should know that both $\\mathbf{X}$ and $\\mathbf{\\overline{Z}}$ are both processed by layer normalization before being fed into self-attention and the linear layers respectively.\n$^{2}$ While in the design the dimension of $\\mathbf{Q}\\mathbf{K}$ is written as $n \\times n$, in a *LSH self-attention* or *local self-attention* layer the dimension would only be $n \\times l_c \\times n_h$ or $n \\times l_c$ respectively with $l_c$ being the chunk length and $n_h$ the number of hashes\n$^{3}$ In the first reversible transformer layer $\\mathbf{X}^{(2)}$ is set to be equal to $\\mathbf{X}^{(1)}$.\n\n\n### **Benchmark**\n\nIn order to measure the effect of reversible residual layers, we will compare the memory consumption of BERT with Reformer in training for an increasing number of layers.\n\n\n```\n#@title Installs and Imports\n# pip installs\n!pip -qq install git+https://github.com/huggingface/transformers.git\n!pip install -qq py3nvml\n\nfrom transformers import ReformerConfig, BertConfig, PyTorchBenchmark, PyTorchBenchmarkArguments\n```\n\nLet's measure the required memory for the standard `bert-base-uncased` BERT model by increasing the number of layers from 4 to 12.\n\n\n```\nconfig_4_layers_bert = BertConfig.from_pretrained(\"bert-base-uncased\", num_hidden_layers=4)\nconfig_8_layers_bert = BertConfig.from_pretrained(\"bert-base-uncased\", num_hidden_layers=8)\nconfig_12_layers_bert = BertConfig.from_pretrained(\"bert-base-uncased\", num_hidden_layers=12)\nbenchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[512], batch_sizes=[8], models=[\"Bert-4-Layers\", \"Bert-8-Layers\", \"Bert-12-Layers\"], training=True, no_inference=True, no_speed=True, no_env_print=True)\nbenchmark = PyTorchBenchmark(configs=[config_4_layers_bert, config_8_layers_bert, config_12_layers_bert], args=benchmark_args)\nresult = benchmark.run()\n```\n\n\n HBox(children=(FloatProgress(value=0.0, description='Downloading', max=433.0, style=ProgressStyle(description_…\n\n\n \n 1 / 3\n 2 / 3\n 3 / 3\n \n ==================== TRAIN - MEMORY - RESULTS ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Bert-4-Layers 8 512 4103 \n Bert-8-Layers 8 512 5759 \n Bert-12-Layers 8 512 7415 \n --------------------------------------------------------------------------------\n\n\nIt can be seen that adding a single layer of BERT linearly increases the required memory by more than 400MB.\n\n\n```\nconfig_4_layers_reformer = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", num_hidden_layers=4, num_hashes=1)\nconfig_8_layers_reformer = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", num_hidden_layers=8, num_hashes=1)\nconfig_12_layers_reformer = ReformerConfig.from_pretrained(\"google/reformer-enwik8\", num_hidden_layers=12, num_hashes=1)\nbenchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[512], batch_sizes=[8], models=[\"Reformer-4-Layers\", \"Reformer-8-Layers\", \"Reformer-12-Layers\"], training=True, no_inference=True, no_speed=True, no_env_print=True)\nbenchmark = PyTorchBenchmark(configs=[config_4_layers_reformer, config_8_layers_reformer, config_12_layers_reformer], args=benchmark_args)\nresult = benchmark.run()\n```\n\n 1 / 3\n 2 / 3\n 3 / 3\n \n ==================== TRAIN - MEMORY - RESULTS ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Reformer-4-Layers 8 512 4607 \n Reformer-8-Layers 8 512 4987 \n Reformer-12-Layers 8 512 5367 \n --------------------------------------------------------------------------------\n\n\nFor Reformer, on the other hand, adding a layer adds significantly less memory in practice. Adding a single layer increases the required memory on average by less than 100MB so that a much larger 12-Layer `reformer-enwik8` model requires less memory than a 12-Layer `bert-base-uncased` model.\n\n## **4. Axial Positional Encodings**\n\nReformer makes it possible to process huge input sequences. However, for such long input sequences standard positional encoding weight matrices alone would use more than 1GB to store its weights.\nTo prevent such large positional encoding matrices, the official Reformer code introduced *Axial Position Encodings*. \n\n**Important:** *Axial Position Encodings were not explained in the official paper, but can be well understood from looking into the code and talking to the authors*\n\n\n### **Axial Positional Encodings in Reformer**\n\nTransformers need positional encodings to account for the order of words in the input because self-attention layers have *no notion of order*. \nPositional encodings are usually defined by a simple look-up matrix $\\mathbf{E} = \\left[\\mathbf{e}_1, \\ldots, \\mathbf{e}_{n_\\text{max}}\\right]$ The positional encoding vector $\\mathbf{e}_i$ is then simply added to the *ith* input vector $\\mathbf{x}_i + \\mathbf{e}_i$ so that the model can distinguish if an input vector (*a.k.a* token) is at position $i$ or $j$. \nFor every input position, the model needs to be able to look up the corresponding positional encoding vector so that the dimension of $\\mathbf{E}$ is defined by the maximum length of input vectors the model can process `config.max_position_embeddings`, *i.e.* $n_\\text{max}$, and the `config.hidden_size`, *i.e.* $d_h$ of the input vectors. \n\nAssuming $d_h=4$ and $n_\\text{max}=49$, such a positional encoding matrix can be visualized as follows:\n\n\n\nHere, we showcase only the positional encodings $\\mathbf{e}_1$, $\\mathbf{e}_2$, and $\\mathbf{e}_{49}$ each of dimension, *a.k.a* height 4.\n\nLet's imagine, we want to train a Reformer model on sequences of a length of up to 0.5M tokens and an input vector `config.hidden_size` of 1024 (see notebook [here](https://github.com/patrickvonplaten/notebooks/blob/master/PyTorch_Reformer.ipynb)). The corresponding positional embeddings have a size of $0.5M \\times 1024 \\sim 512M$ parameters, which corresponds to a size of 2GB.\n\nSuch positional encodings would use an unnecessarily large amount of memory both when loading the model in memory and when saving the model on a hard drive.\n\nThe Reformer authors managed to drastically shrink the positional encodings in size by cutting the `config.hidden_size` dimension in two and smartly factorizing the $n_\\text{max}$ dimension. In Transformer, the user can decide into which shape $n_\\text{max}$ can be factorized into by setting `config.axial_pos_shape` to an appropriate list of two values $n_\\text{max}^1$ and $n_\\text{max}^2$ so that $n_\\text{max}^1 \\times n_\\text{max}^2 = n_\\text{max}$. By setting `config.axial_pos_embds_dim` to an appropriate list of two values $d_h^1$ and $d_h^2$ so that $d_h^1 + d_h^2 = d_h$, the user can decide how the hidden size dimension should be cut. \nNow, let's visualize and explain more intuitively.\n\nOne can think of factorizing $n_\\text{max}$ as folding the dimension into a third axis, which is shown in the following for the factorization `config.axial_pos_shape = [7, 7]`:\n\n\n\nEach of the three standing rectangular prisms corresponds to one of the encoding vectors $\\mathbf{e}_1, \\mathbf{e}_2, \\mathbf{e}_{49}$, but we can see that the 49 encoding vectors are divided into 7 rows of 7 vectors each.\nNow the idea is to use only one row of 7 encoding vectors and expand those vectors to the other 6 rows, essentially reusing their values. \nBecause it is discouraged to have the same values for different encoding vectors, each vector of dimension (*a.k.a* height) `config.hidden_size=4` is cut into the lower encoding vector $\\mathbf{e}_\\text{down}$ of size $1$ and $\\mathbf{e}_\\text{up}$ of size $3$, so that the lower part can be expanded along the row dimension and the upper part can be expanded along the column dimension.\nLet's visualize for more clarity.\n\n\n\nWe can see that we have cut the embedding vectors into $\\mathbf{e}_\\text{down}$ (*in blue*) and $\\mathbf{e}_\\text{up}$ (*in yellow*).\nNow for the \"sub\"-vectors $\\mathbf{E}_\\text{down} = \\left[\\mathbf{e}_{\\text{down},1}, \\ldots, \\mathbf{e}_{\\text{down},49}\\right]$ only the first row, *a.k.a.* the width in the graphic, of $7$ is kept and expanded along the column dimension, *a.k.a.* the depth of the graphic. Inversely, for the \"sub\"-vectors $\\mathbf{E}_\\text{up} = \\left[\\mathbf{e}_{\\text{up},1}, \\ldots, \\mathbf{e}_{\\text{up},49}\\right]$ only the first column of $7$ is kept and expanded along the row dimension.\nThe resulting embedding vectors $\\mathbf{e'}_i$ then correspond to\n\n \\begin{align}\n \\mathbf{e'}_i &= \\begin{bmatrix}\n \\mathbf{e}_{\\text{down, } i \\% n_\\text{max}^1} \\\\\n \\mathbf{e}_{\\text{up, } \\left \\lfloor{\\frac{i}{n_\\text{max}^2}}\\right \\rceil}\n \\end{bmatrix}\n \\end{align}\nwhereas $n_\\text{max}^1 = 7$ and $n_\\text{max}^2 = 7$ in our example.\nThese new encodings $\\mathbf{E'} = \\left[\\mathbf{e'}_1, \\ldots, \\mathbf{e'}_{n_\\text{max}}\\right]$ are called **Axial Position Encodings**. \n\nIn the following, these axial position encodings are illustrated in more detail for our example.\n\n\n\nNow it should be more understandable how the final positional encoding vectors $\\mathbf{E'}$ are calculated only from $\\mathbf{E}_{\\text{down}}$ of dimension $d_h^1 \\times n_\\text{max}^1$ and $\\mathbf{E}_{\\text{up}}$ of dimension $d_h^2 \\times n_\\text{max}^2$.\n\nThe crucial aspect to see here is that Axial Positional Encodings make sure that none of the vectors $\\left[\\mathbf{e'}_1, \\ldots, \\mathbf{e'}_{n_\\text{max}}\\right]$ are equal to each other by design and that the overall size of the encoding matrix is reduced from $n_\\text{max} \\times d_h$ to $n_\\text{max}^1 \\times d_h^1 + n_\\text{max}^2 \\times d_h^2$.\nBy allowing each axial positional encoding vector to be different by design the model is given much more flexibility to learn efficient positional representations if axial positional encodings are learned by the model.\n\nTo demonstrate the drastic reduction in size, \nlet's assume we would have set `config.axial_pos_shape = [1024, 512]` and `config.axial_pos_embds_dim = [512, 512]` for a Reformer model that can process inputs up to a length of 0.5M tokens. The resulting axial positional encoding matrix would have had a size of only $1024 \\times 512 + 512 \\times 512 \\sim 800K$ parameters which corresponds to roughly 3MB. This is a drastic reduction from the 2GB a standard positional encoding matrix would require in this case.\n\nFor a more condensed and math-heavy explanation please refer to the 🤗Transformers docs [here](https://huggingface.co/transformers/model_doc/reformer.html#axial-positional-encodings).\n\n### **Benchmark**\n\nLastly, let's also compare the peak memory consumption of conventional positional embeddings to *axial positional embeddings*.\n\n\n```\n#@title Installs and Imports\n# pip installs\n!pip -qq install git+https://github.com/huggingface/transformers.git\n!pip install -qq py3nvml\n\nfrom transformers import ReformerConfig, PyTorchBenchmark, PyTorchBenchmarkArguments, ReformerModel\n```\n\nPositional embeddings depend only on two configuration parameters: The maximum allowed length of input sequences `config.max_position_embeddings` and `config.hidden_size`. Let's use a model that pushes the maximum allowed length of input sequences to half a million tokens, called `google/reformer-crime-and-punishment`, to see the effect of using axial positional embeddings.\n\nTo begin with, we will compare the shape of axial position encodings with standard positional encodings and the number of parameters in the model.\n\n\n```\nconfig_no_pos_axial_embeds = ReformerConfig.from_pretrained(\"google/reformer-crime-and-punishment\", axial_pos_embds=False) # disable axial positional embeddings\nconfig_pos_axial_embeds = ReformerConfig.from_pretrained(\"google/reformer-crime-and-punishment\", axial_pos_embds=True, axial_pos_embds_dim=(64, 192), axial_pos_shape=(512, 1024)) # enable axial positional embeddings\n\nprint(\"Default Positional Encodings\")\nprint(20 * '-')\nmodel = ReformerModel(config_no_pos_axial_embeds)\nprint(f\"Positional embeddings shape: {model.embeddings.position_embeddings}\")\nprint(f\"Num parameters of model: {model.num_parameters()}\")\nprint(20 * '-' + '\\n\\n')\n\nprint(\"Axial Positional Encodings\")\nprint(20 * '-')\nmodel = ReformerModel(config_pos_axial_embeds)\nprint(f\"Positional embeddings shape: {model.embeddings.position_embeddings}\")\nprint(f\"Num parameters of model: {model.num_parameters()}\")\nprint(20 * '-' + '\\n\\n')\n```\n\n\n HBox(children=(FloatProgress(value=0.0, description='Downloading', max=1151.0, style=ProgressStyle(description…\n\n\n \n Default Positional Encodings\n --------------------\n Positional embeddings shape: PositionEmbeddings(\n (embedding): Embedding(524288, 256)\n )\n Num parameters of model: 136572416\n --------------------\n \n \n Axial Positional Encodings\n --------------------\n Positional embeddings shape: AxialPositionEmbeddings(\n (weights): ParameterList(\n (0): Parameter containing: [torch.FloatTensor of size 512x1x64]\n (1): Parameter containing: [torch.FloatTensor of size 1x1024x192]\n )\n )\n Num parameters of model: 2584064\n --------------------\n \n \n\n\nHaving read the theory, the shape of the axial positional encoding weights should not be a surprise to the reader.\n\nRegarding the results, it can be seen that for models being capable of processing such long input sequences, it is not practical to use default positional encodings. \nIn the case of `google/reformer-crime-and-punishment`, standard positional encodings alone contain more than 100M parameters. \nAxial positional encodings reduce this number to just over 200K.\n\nLastly, let's also compare the required memory at inference time.\n\n\n```\nbenchmark_args = PyTorchBenchmarkArguments(sequence_lengths=[512], batch_sizes=[8], models=[\"Reformer-No-Axial-Pos-Embeddings\", \"Reformer-Axial-Pos-Embeddings\"], no_speed=True, no_env_print=True)\nbenchmark = PyTorchBenchmark(configs=[config_no_pos_axial_embeds, config_pos_axial_embeds], args=benchmark_args)\nresult = benchmark.run()\n```\n\n 1 / 2\n 2 / 2\n \n ==================== INFERENCE - MEMORY - RESULT ====================\n --------------------------------------------------------------------------------\n Model Name Batch Size Seq Length Memory in MB \n --------------------------------------------------------------------------------\n Reformer-No-Axial-Pos-Embeddin 8 512 959 \n Reformer-Axial-Pos-Embeddings 8 512 447 \n --------------------------------------------------------------------------------\n\n\nIt can be seen that using axial positional embeddings reduces the memory requirement to approximately half in the case of `google/reformer-crime-and-punishment`.\n", "meta": {"hexsha": "88b844857ba935ddb646b1d3505600132c413550", "size": 109027, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/03_reformer.ipynb", "max_stars_repo_name": "Phoenix4582/Machine-Learning-Collection", "max_stars_repo_head_hexsha": "e471414b4a1fc351ebbf259be0567e4faa93bbd4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/03_reformer.ipynb", "max_issues_repo_name": "Phoenix4582/Machine-Learning-Collection", "max_issues_repo_head_hexsha": "e471414b4a1fc351ebbf259be0567e4faa93bbd4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/03_reformer.ipynb", "max_forks_repo_name": "Phoenix4582/Machine-Learning-Collection", "max_forks_repo_head_hexsha": "e471414b4a1fc351ebbf259be0567e4faa93bbd4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.9622541201, "max_line_length": 1216, "alphanum_fraction": 0.5792785273, "converted": true, "num_tokens": 15144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3219494999607148}} {"text": "```python\n# Preload matplotlib, julia and sympy\nimport matplotlib.pyplot as plt\nimport numpy\nimport sympy\nfrom BondGraphTools.config import config\nsympy.init_printing()\n%matplotlib inline\n_ = config.julia # This preloads julia.\n```\n\n \n\n\n# _Systems all the way down_\n## Managing Complexity with BondGraphTools\n\nhttps://github.com/peter-cudmore/seminars/AustMS-2018\n\n \n\n Dr. Peter Cudmore. \n Systems Biology Labratory, \n The School of Chemical and Biomedical Engineering, \n The University of Melbourne. \n\nAbstract\n----------\n\nMany problems in biology, ecology and engineering involve predicting and controlling complex systems, loosely defined as interconnected system-of-systems. Such systems can exhibit a variety of interesting non-equilibrium features such as emergence, phase transitions and other multi-scale phenomenon which result from mutual interactions between subsystems.\n\nConstructing and analysing models of complex systems is often a non-trivial task due to the high dimensionality, heterogeneity and nonlinearity of the system in question. Mathematicians and scientists alike need tools, computational tools in particular, to manage the complexity of their dynamical systems models.\n\nIn this talk we introduce `BondGraphTools` a systems modelling framework, and discuss how to model and simulate complex physical systems without making the models unwieldy, breaking the laws of physics, or doing any of the tedious stuff by hand.\n\n## Outline of talk\n\n* Prediction and control of complex systems necessary.\n* For heterogenous systems specifity is required and scale is a problem.\n* The initial problem is how to capture and represent these systems.\n* The solution is `BondGraphTools` which \n\n a) bases our model on physical principals (extension of portHamiltonians)\n \n b) use modelling paradigms build on multi-scale abstraction (object oriented programming)\n \n c) implement our solution in a sustainable framework (python/julia) \n\n\n\n## Table of Contents\n\n1. Introduciton\n2. Hamiltonian, portHamiltonians and Energetic Systems\n3. BondGraphTools\n\n# Section 1: Introduction\n\n
\n\nMetabolism\n--------------\n* Intel 8086 cpu has 29,000 transistors. (wiki)\n* Current Metabolites w/Proteins (Enzymes and Transporters) of 23,478 see [2]\n* *At least* as difficult as reverse engineering a microprocessor.\n* 'phase transitions' i,e; disease->healthy.\n* Secondary effects of intervention.\n\nSysten features: network toplogy, dynamics, nonlinear, feed-back/forward loops.\n\nMetabolism is the power source of the cell and is responsible for turning raw materials, such glucose, into resources for other cellular action. Metabolism engineering is already a staple in synthetic biology but there are great difficulties translating results obtained from flux-balance analysis (FBA), which are suitable in stritcly controlled lab environments, to real-world situations where steady-state and optimal growth assumptions are clearly invalid.\nUnderstanding how metabolism works in of great interest for cancer theraputics, since a reprogrammed metabolism is a 'hallmark of cancer mutations'. \n\nMetabolic maps are a repsentation of a _network_ in that each node represents a metabolite, and each edge usually represent a protien that cataylses the reaction from one metabolite to another. When spatial effects are ignored, the reactions are often described by nonlinear differential equations. Clearly observable are instances of cycles, feedback and feed-forward loops.\n\nModern metabolohmics [2] puts the number of metabolics with associated protiens in tens-of-thousands each corresponding to a dynamic process. As a point of refernce, the 8086 cpu, an early precursor to the modern digital computer and the beginning of very-large scale integration (VLSI) fabrication for integrated circtuis, had approximately 30,000 transistor. The implication is that reverse engineering metabolic network (let alone any of the other celluar processes) is _at least_ as difficult as reverse engineering early cpus.\n\nEssential, one wishes to understand non-equilibrium states of a metabolic system which can be understood traditional problems in non-autonomous nonlinear dynamics; finding critical manifolds and making parameter (and forcing) dependanices clear, so as to predicable be able to control the dynamics of the system. For example to optimise metabolic throughput, to identify protiens required to move the metabolism from a 'diseased' dynamic state to a 'health' state, or to predict the systemic outcome of pharmaceutical interventions.\n\nIt is obvious then that one great challenge for a systems-level description of metabolism comes from the _scale_ of the problem. One can think of this as a question of 'emergence', how macro-scale phenomonom depend on the network configuration parameters. \n\nA separate great challenge is the question of how to mathematically manipulate large hetereogenous systems and how to navigate between the different levels of abstraction; from statistical, to simplified, to sucessively detailed. \nThat is, how does one handle a system of systems. \n\n\n \n \n \n \n \n \n \n \n
\n

\n
Smart Grids

\n

Techno-Ecological processes

\n
\n\nSmart Grids\n-------------\n\n* Confliting issues: energy->well being (See [5,6]) esp. education, mortality, poverty, etc. \n* carbon emissions->climate change.\n* Smart grids integrate new renewables with 'base-line' power supply.\n* Many sources, storage, and sinks; need for automatic control and stabilisation.\n\n\nFeatures: multiple-time scale, correlated noise, feedback, very heterogenous.\n\nProcess Engineering\n---------\n* Cooperatively coupling processes for 'techno-ecological synergies'.\n* Sustainable, economical and efficient.\n* Ecosystems many moving parts. Need to know how to engineer and optimise.\n\nManaging the impact of anthropogenic climate change appears to be one of the biggest challenges facing humanity over the coming decade, and is further complicated by the mounting evidence that cheap, readily available electricity is highly correlated with many measures of human well being [5,6] particularly access to education, poverity and mortality as well as seemingly unrelated metrics like levels of gender equality and personal freedom.\n\nThere has been considerable interest in augmenting base-line power supply (which makes up the bulk of Co2 production), with decentralised renewable technologies and mass storage so as to reduce the carbon footprint of national powergrids [3]. Balancing energy security with carbon foorprint then becomes a prediction and control problem involving the system dynamics of a noisy, heteroenous network of energy sources, storage and sinks; systems in their own right.\n\nThere are many other examples of large, networked dynamical systems we would like to understand including but not limited to; ecosystems, markets, public infrastrucure and large scale industrial/engineering processes. Understanding how these systems work, and most importantly, how to pair parameter changes with qualitative behaviour is an active area of reseach in applied dynamical systems and interdisciplinary science.\n\n*We want to predict and control energetic systems-of-systems*\n-------\n\nFor our purposes a dynamic system is *system-of-systems* when:\n\n* It is made up of many moving parts, or subsystems (High-dimensional).\n* The subsystems are not all of the same type (Heterogenenous).\n* The subsystems are complicated (Nonlinear and/or Noisy).\n* There are well defined boundaries between the subsystems (Network Topology).\n\nBy *energetic system*, we mean that *energy* is the quantity that is exchanged between subsystems.\n\n> There is a fact, or if you wish, a law, governing all natural phenomena that are known to date. There is no known exception to this law—it is exact so far as we know. The law is called the conservation of energy. \n\n\\- R. Feynman, 1963. http://www.feynmanlectures.caltech.edu/I_04.html\n\nHetereogeneity and High Dimension means it is often difficult to apply statistical techniques.\n\nNecessary for\n\n* engineering biological systems,\n* ensuring energy security in a changing climate,\n* managing macroeconomics and organisation behaviour,\n* large scale industrial design and construction.\n\nFor our purposes, an example of a system-of-systems that is not _complex_ is a coupled oscillator system.\nWhist a coupled oscillator system is indeed nonlinear and high dimensional, and often networked and/or noisy they are however usually only weakly hetereogenous. Coupled oscillator systems can nonethelesss produce interesting and relavent behaviour.\n\nWithout the heterogeneity condition, one might be able to at least formulate how to navigate between mechanism and system level statistics. Actually doing this is often not even slightly trivial, and is of great interest to mathematicians in the nonlinear sciences.\n\nWith the heterogeneity condition there are not yet clear ways to simplify the relationship between mechanisms and macroscopic statistics.\n\n*We want to predict and control complex energetic systems*\n-------\n\nFor a _particular_ system-of-systems we want to:\n* Talk about qualitative properties such as existence, stability and bifucations of macroscopic phenomena.\n* Estimate parameters and states from limited, noisy datasets so as to make predictions. \n* Design, evaluate and optimise control schemes.\n\nIn the case of large systems-of-systems we need: \n* _Representations_ of networked dynamical systems that are manageable.\n* _Automation tools_ for system capture, simplification and analysis.\n\nThe essential question in complex system science is: _given a complex system, how can we identify the system topology, describe the subsystem dynamics, and control the emergent phenomonom._\n\nFor complex heteroenous systems, the first big problem one must contend with is _how to represent them_. For example, if a system has 1000 components, we would prefer not to have to write 1000 equations out. \n\nIn other words, we need some way to bundle together funcionally related, or _encapsulate_ subsystems. Since we're talking about systems-of-systems, we clearly must also have _composition_ (has-a relationships) and _inheritance_ (is-a relationships).\n\nDue to the scope and scale of the problems, we don't want to be doing this by hand!\n\n## Existing Approaches to Energetic Modelling\n\nExisting approaches seek to integrate port based approaches with classical mechanics, which are often solved in either specialised toolkits inside mathematical software suites, or inside computer aided design (CAD) software.\n\nEnergetic system representations include:\n- Ad-hoc modelling.\n- Bond Graphs.\n- Port Hamiltonians.\n\nImplementations include:\n- Simulink(MATLAB)\n- SystemsModeller (Mathematica)\n- MapleSim (Maple)\n- Dymola, 20-sim, openModelica, MTT\n\nIssues:\n- pH enforce a particular structure to the model equations; that may not match observations\n- Bond Graphs, which can be thought of a generalisation of 2-port passive circutis, have some features that preclude some desired properties; 'the nodes care about the orientation of the edges'.\n- Maths software lack the features of a GP programming language.\n- Closed source/CAD software lack the ability to integrate with other software; 'they do too much'.\n\n## A solution (representation)\n\n### 'Energetic Systems' as OOP\n\nObject Oriented Programming (OOP) is a software development paradigm that seeks to manage large, complicated projects by breaking problems into _data_ plus _methods_ that act on the data. \n\nThree big ideas in OOP are:\n1. _Inheritance_ or is-a relationships. \n2. _Composition_ or has-a relationships.\n3. _Encapsulation_ or infomation hiding.\n\n\nThis allows for _hierarchical_ and _modular_ design which reduces model complexity.\n\n## A solution (automation)\n\n### Sustainable Software via `BondGraphTools`\n\nSustainable software is:\n- Open source\n- Easy to install and use.\n- In a common language with standard dependencies.\n- Well documented.\n- Iteratively developed \n- Limited in scope.\n- Continuously tested.\n- Version controlled.\n\n\n\n  \n\n  \n\n  \n\n\n# Object Oriented Modelling for Dynamical Systems \n\n \n\nInheritance, Composition and Encapsulation\n\n\n\n## Inheritance\n\n \n\nFor networked dynamic systems, _inheritance_ means we have:\n- conditions on the dynamical sub-systems.\n- a description of the interface between nodes.\n\n\n\n\n\n\n### Definition (Energetic System)\n\nAn energetic system is a tuple $(M, \\mathcal{D}, U,\\Phi)$\nwhere the\n* *state space* $M$ is a manifold of $\\dim(M) = m\\ge 0$\n* *port space* $\\mathcal{D} \\subset \\mathcal{F} \\times \\mathcal{E}$ where, $\\mathcal{E} = \\mathcal{F}^*$ and $ \\dim{\\mathcal{D}} = \\mathcal{F}|_\\mathcal{D} =n$. \n* *control space* $U \\subset C^r:\\mathbb{R}_+ \\rightarrow \\mathbb{R^k}$ with $k\\ge 0$ \n* *constitutive relation* is a smooth map $\\Phi: TM \\times \\mathcal{D} \\times U\\times\\mathbb{R}_+ \\rightarrow\n \\mathbb{R}^{m+n}$ \n such that\n $$\\Phi\\left(\\frac{dx}{dt},x,f,e,u,t\\right)=0.$$\n\n$\\Phi$ relates the _internal state_ $M$ and the _external environment_ (via $\\mathcal{D}$). \n\n\n\n \n\n\n \n\n\n\n\n \n\n \n\nThe incoming *power* is $P_\\text{in} = \\left$ for $(f,e)\\in \\mathcal{D}$\n\n* Energetic system is a 'Dynamic System' in the traditional sense if e,f are empty. CR is a evolution rule\n* generalisation of Port-Hamiltonians, which itself is a generalisation of 'Bond Graph' modelling, see [8].\n* state space -> local co-oridnates of a system.\n* port space -> effort amnd flow, much like voltage/current, force/velocity analogies.\n* control space differentiability depends on 'index' of DAE\n* CR is a relationship between the diff'able manifold and power variables\n* CR in a sense defines a component\n\n\n## Inheritance\n\nFor energetic systems-of-systems:\n### Nodes are particular _energetic systems_ \nEach node is described by a set of differential-algebraic equations $\\Phi(\\dot{x},x,e,f) = 0$.\n\n### Edges are constraints on port variables.\n\nAn edge represents how state is shared between systems.\n\n\n\nTalk about examples.\n\n## Composition\n\n \n\nFor networked dynamic systems _composition_ means that we can replace nodes with subgraphs and vice-versa.\n\n\n\n\n\n## Corollary (Composition)\nIf $\\Psi_1 = (M_1, \\mathcal{D}_1, U_1,\\Phi_1)$ and $\\Psi_2 = (M_2, \\mathcal{D}_2, U_2,\\Phi_2)$ are energetic systems, then \n\n$$\\begin{eqnarray}\\Psi_0 &=& \\Psi_1 \\oplus\\Psi_2\\\\\n&=& \n\\left(M_1\\oplus M_2,\\mathcal{D}_1 \\oplus\\mathcal{D}_2,U_1\\oplus U_2, \\Phi_1\\oplus\\Phi_2\\right)\n\\end{eqnarray}$$\nis also an energetic system.\n\nSuppose (abusing notation) $\\Psi_0 = (\\Psi_1,\\Psi_2)$ is an energetic system with ports \n\n$$(e_i, f_i) \\in \\mathcal{D}_1, \\quad (e_j,f_j) \\in \\mathcal{D}_2$$\n\nThen $\\Phi_0$ with the additional power conserving constraint \n\n$$e_i - e_j = 0\\qquad f_i+f_j=0$$\n\nis also a energetic system.\n\n\n\n\n\n## Encapsulation\n\n \n\nFor a networked dynamical system _encapsulation_ means that we can apply simplification methods to a subgraph so that the replacement system is less complicated, while representing the same behaviour.\n\n \n\nOne can also go the other way by replacing a node with a more complicated subgraph.\n\n \n\n\n...hence _systems all the way down_.\n\n\n\n\n\n## Example (Duffing Oscillator)\n### Composed System\nThe composition of \n\n$$\\Phi_1^T =\\left(\\dot{x_1} - f_1,\\ e_1 - \\frac{x_1}{\\omega} - \\frac{x_1^3}{\\mu}\\right)$$ \n$$\n\\Phi_2^T =\\left(\\dot{x_2} - e_2,\\ f_2 - x_2\\right)\n$$ \n\nwith the port mapping \n\n$$e_1 - e_2 = 0 \\qquad f_1 + f_2 = 0$$ \n\nis the system is given by \n\n$$\\Phi_0^T = \\left(\\dot{x}_1 + x_2,\\ \\dot{x}_2 - \\frac{x_1}{\\omega} - \\frac{x_1^3}{\\mu}\\right) = 0 $$\n\n\n\n\n\n## Object Oriented Modelling and Energetic Systems\n\nEnergetic systems provide:\n- _Inheritance_; an abstract base representation of energetic systems.\n- _Composition_; a way to hierarchically compose systems of systems.\n- _Encapsulation_; a framework inside which simplifications can occur.\n\n  \n\n  \n\n  \n\n# Introducing `BondGraphTools`\n\n## `BondGraphTools` a `python` library for energetic systems.\n\n`BondGraphTools` (https://github.com/BondGraphTools) a framework for modelling energetic systems.\n* Based upon an extension of bond graph and port-Hamiltonian modelling.\n* Provies a simple, *minimal* object-oriented interface for constructing, composing and simulating models.\n* Implemented in `python` and uses the standard `scipy` stack.\n* Computational 'grunt' is provided via `julia` and `DifferentialEquations.jl`.\n* Developed with sustainable software practices.\n* Intended to be used in _conjunction_ with other tools.\n\n'Bond Graphs' are a multi-domain port-based graphical modelling technique used predominantly in mechatronics. \nPort-Hamiltonian systems integrate geometric approaches from classical mechanics and control theory with port based modelling. \n\n\n\n## Example (Duffing Oscillator)\n\nThe Duffing oscillator consists of the conservation of force between kinetic energy and a nonlinear potential.\n\n \n\n\n\n\n```python\n# Import Tools\nfrom BondGraphTools import new, add, connect\n\n# Nonlinear Potential Energy\nphi_1 = new(\"PH\", value=\"x^2/2 +x^4/4\")\n\n# Linear Kinetic Energy\nphi_2 = new(\"I\", value=1) \n\n# Conservation Law\nphi_3 = new(\"0\") \n\n# Control Source\nsource = new(\"Sf\") \n\n# Composed system\nphi_0 = new(name=\"Duffing Model\")\nadd(phi_0, phi_1, phi_2, phi_3, source) \n\n# Constraints\nconnect(source, phi_3)\nconnect(phi_3, phi_2)\nconnect(phi_3, phi_1)\n\nphi_0.constitutive_relations\n```\n\n\n\n\n [dx_0 - u_0 + x_1, dx_1 - x_0**3 - x_0]\n\n\n\n\n\n## Example (Duffing Osc)\n\nNumerical solvers respect constraints!\n\n\n\n\n\n```python\nfrom BondGraphTools import simulate\nfrom matplotlib.pyplot import plot\n\nu = \"0.3*sin(0.6*t)\"\nt,x = simulate(phi_0, \n x0=[0, 1], \n timespan=[0,100], \n control_vars=[u])\n\n_ = plot(x[40:,0], x[40:,1]) \n```\n\n\n\n## Automation\n\nIf you can build one, you can build many!\n\nBy wrapping the Duffing example inside a method, defining a port, and returning the resulting system-of-systems, one can implement a _factory_ method, that creates new Duffing oscillators. \n\n\n\n\n```python\nfrom BondGraphTools import *\n\ndef duffing_factory(name=\"Duffing Osc\", freq=1):\n \"\"\"Makes Duffing Oscillators!\"\"\"\n\n potential = \"x^2/(2*w) + 0.00025*x^4\"\n \n phi_1 = new(\"PH\", value={\"hamiltonian\": potential,\n \"params\":{\"w\": 1/freq}})\n\n phi_2 = new(\"I\", value=1) \n phi_3 = new(\"1\") \n phi_4 = new(\"R\", value=0.001)\n port = new(\"SS\")\n\n phi_0 = new(name=name)\n add(phi_0, phi_1, phi_2, phi_3, phi_4, port) \n connect(port, phi_3)\n connect(phi_3, phi_4)\n connect(phi_3, phi_2)\n connect(phi_3, phi_1)\n expose(port)\n\n return phi_0\n\nmodel = duffing_factory()\nmodel.constitutive_relations\n```\n\n\n\n\n [dx_0 - x_1, dx_1 - e_0 + x_0**3/1000 + x_0 + x_1/1000, f_0 - x_1]\n\n\n\n\n\n## Batteries Included!\n\n`BondGraphTools` is built on the scientific python ecosystem.\n\n\n```python\nimport sympy \noscillator_array = new(name=\"All-to-all Duffing\")\n\njunction_law = new(\"0\")\ncommon_field = new(\"C\", value=sympy.S('K'))\n\nadd(oscillator_array, common_field, junction_law)\nconnect(common_field, junction_law)\n\nfrequencies = [1/2,1/3,1/4,1/5,1/6]\n\nfor i, freq in enumerate(frequencies): \n # Create a new oscillator\n osc_i = duffing_factory(f\"Osc{i}\", freq=freq)\n\n # Add it to the array\n add(oscillator_array, osc_i)\n \n # Connect it to the junciton law\n connect(junction_law, osc_i)\n```\n\n\n```python\neqns = oscillator_array.constitutive_relations\nfor eqn in eqns:\n print(sympy.latex(eqn))\n```\n\n dx_{0} + x_{10} + x_{2} + x_{4} + x_{6} + x_{8}\n dx_{1} - x_{2}\n dx_{2} + \\frac{x_{1}^{3}}{1000} + \\frac{x_{1}}{2} + \\frac{x_{2}}{1000} - \\frac{x_{0}}{K}\n dx_{3} - x_{4}\n dx_{4} + \\frac{x_{3}^{3}}{1000} + \\frac{x_{3}}{3} + \\frac{x_{4}}{1000} - \\frac{x_{0}}{K}\n dx_{5} - x_{6}\n dx_{6} + \\frac{x_{5}^{3}}{1000} + \\frac{x_{5}}{4} + \\frac{x_{6}}{1000} - \\frac{x_{0}}{K}\n dx_{7} - x_{8}\n dx_{8} + \\frac{x_{7}^{3}}{1000} + \\frac{x_{7}}{5} + \\frac{x_{8}}{1000} - \\frac{x_{0}}{K}\n dx_{9} - x_{10}\n dx_{10} + \\frac{x_{10}}{1000} + \\frac{x_{9}^{3}}{1000} + \\frac{x_{9}}{6} - \\frac{x_{0}}{K}\n\n\n## Example (Exploring Synch in Duffing Arrays)\n\n\n\n```python\n# Define state\nx_0 = {x:'1.0' for x in oscillator_array.state_vars}\ntimespan = [0,40]\n```\n\n\n```python\n# Set a numerical paramter for K\ncommon_field.set_param(\"C\", 100)\n\nt, x = simulate(oscillator_array, \n x0=x_0, timespan=timespan)\n\nfig_1 = plot(t, x[:,1:])\n```\n\n\n```python\n# Change the Parameter, simulate again!\ncommon_field.set_param(\"C\", 10)\n\nt, x = simulate(oscillator_array,\n x0=x_0, timespan=timespan)\n\nfig_2 = plot(t, x[:,1:])\n```\n\n \n\n \n\n \n\n\n# Conclusion\n\n## Current State of `BondGraphTools`\n\n- Current version on PyPI is 0.3.6 https://pypi.org/project/BondGraphTools/\n- Documentation at https://bondgraphtools.readthedocs.io\n- Source at https://github.com/BondGraphTools/\n- In active use inside the Systems Biology Lab @ UniMelb\n- Can _programmatically_ build arbitrarily large models and simplify network constraints.\n\n## Plans for v0.4 and v0.5\n- Robust parameter and control value network.\n- Interface for measuring port space.\n- Algorithmic model reduction (particularly manifold reductions).\n- Bifurcation analysis (particularly fixed point tracking).\n\n# Thanks for listening\n\nThanks to\n- Prof. Edmund Crampin \n- The Systems Biology Lab at The University of Melbourne\n- Cecilia Gonzalez-Tokman and Robby Marangell\n- AustMS 2018 Organisers\n\n\n\n\n \n \n \n \n
\n\n \n\n \n\n \n\n# Please check out `BondGraphTools`\n\n# https://github.com/BondGraphTools/\n\nReferences\n--------------\n[1] Human Metabolism Map https://www.vmh.life\n\nAlberto Noronha, Anna Dröfn Daníelsdóttir, Piotr Gawron, Freyr Jóhannsson, Soffía Jónsdóttir, Sindri Jarlsson, Jón Pétur Gunnarsson, Sigurður Brynjólfsson, Reinhard Schneider, Ines Thiele, Ronan M T Fleming; ReconMap: an interactive visualization of human metabolism, *Bioinformatics*, Volume 33, Issue 4, 15 February 2017, Pages 605–607, https://doi.org/10.1093/bioinformatics/btw667\n\n[2] Human Metabolome database: http://www.hmdb.ca\n\nWishart DS, Tzur D, Knox C, et al., \nHMDB: the Human Metabolome Database. \nNucleic Acids Res. \n2007 Jan;\n35(Database issue):D521-6. 17202168 \n\n[3] Smart Grid Map: http://smartgrid.epri.com\nImage courtesy of the Electric Power Research Institute.\n\n[4] Techno-Ecological Synergies\n\nRobert A. Urban, Bhavik R. Bakshi, Geoffrey F. Grubb, Anil Baral, William J. Mitsch,\nTowards sustainability of engineered processes: Designing self-reliant networks of technological–ecological systems,\nComputers & Chemical Engineering,\nVolume 34, Issue 9,\n2010,\nPages 1413-1420,\nhttps://doi.org/10.1016/j.compchemeng.2010.02.026.\n\n[5] Jessica G. Lambert, Charles A.S. Hall, Stephen Balogh, Ajay Gupta, Michelle Arnold,\nEnergy, EROI and quality of life,\nEnergy Policy,\nVolume 64,\n2014,\nPages 153-167,\nhttps://doi.org/10.1016/j.enpol.2013.07.001.\n\n[6] Cesar Pasten, Juan Carlos Santamarina,\nEnergy and quality of life,\nEnergy Policy,\nVolume 49,\n2012,\nPages 468-476,\nhttps://doi.org/10.1016/j.enpol.2012.06.051.\n\n[7]\nFeynmann Lectures: http://www.feynmanlectures.caltech.edu/I_04.html\n\n[8] Port Hamiltonians and Dirac Structures\nhttp://www.math.rug.nl/arjan/DownloadVarious/PHbook.pdf\n\nA.J. van der Schaft, D. Jeltsema, \nPort-Hamiltonian Systems: An Introductory Overview, \nNOW Publishers, Boston/Dordrecht, 2014.\n\n[9] San Miguel, M., Johnson, J.H., Kertesz, J. et al. Challenges in complex systems science. Eur. Phys. J. Spec. Top. (2012) 214: 245. https://doi.org/10.1140/epjst/e2012-01694-y\n\n[10] N. N. Pavlova, C. B. Thompson, The emerging hallmarks of cancer metabolism. Cell Metab. 23, 27–47 (2016). https://doi.org/10.1016/j.cmet.2015.12.006\n\n[11] Hiroaki Yoshimura, Jerrold E. Marsden, Dirac structures in Lagrangian mechanics Part I: Implicit Lagrangian systems, Journal of Geometry and Physics, Volume 57, Issue 1, 2006, Pages 133-156.\nhttps://doi.org/10.1016/j.geomphys.2006.02.009.\n\n[12] M. Dalsmo and A.J. van der Schaft. A Hamiltonian Framework For Inteconnected Physical Systems\n", "meta": {"hexsha": "7bbd5ffdb0b802cac0baf6f4659ce56f1fb45da8", "size": 326756, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "AustMS-2018/AustMS 2018.ipynb", "max_stars_repo_name": "peter-cudmore/seminars", "max_stars_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AustMS-2018/AustMS 2018.ipynb", "max_issues_repo_name": "peter-cudmore/seminars", "max_issues_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AustMS-2018/AustMS 2018.ipynb", "max_forks_repo_name": "peter-cudmore/seminars", "max_forks_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 227.2294853964, "max_line_length": 103500, "alphanum_fraction": 0.9170726781, "converted": true, "num_tokens": 6438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.3219494999607148}} {"text": "```python\ntry:\n import openmdao.api as om\n import dymos as dm\nexcept ImportError:\n !python -m pip install openmdao[notebooks]\n !python -m pip install dymos[docs]\n import openmdao.api as om\n import dymos as dm\n```\n\n# Water Rocket\n\nAuthor: Bernardo Bahia Monteiro (bbahia@umich.edu)\n\nIn this example, we will optimize a water rocket for range and height at the apogee, using design variables that are easily modifiable just before launch: the empty mass, the initial water volume and the launch angle.\nThis example builds on [multi-phase cannonball](../multi_phase_cannonball/multi_phase_cannonball.md) ane is adapted from _Optimization of a Water Rocket in OpenMDAO/Dymos_ {cite}`bbahia_2020`.\n\n## Nomenclature\n\n| Symbol | definition |\n|----------------------|----------------------------------------|\n| $v_\\text{out}$ | water exit speed at the nozzle |\n| $A_\\text{out}$ | nozzle area |\n| $V_w$ | water volume in the rocket |\n| $p$ | pressure in the rocket |\n| $p_a$ | ambient pressure |\n| $\\dot{\\,}$ | time derivative |\n| $k$ | polytropic constant |\n| $V_b$ | internal volume of the rocket |\n| $\\rho_w$ | water density |\n| $T$ | thrust |\n| $q$ | dynamic pressure |\n| $S$ | cross sectional area |\n| $(\\cdot)_0$ | value of $(\\cdot)$ at $t=0$ |\n| $t$ | time |\n\n## Problem Formulation\n\nA natural objective function for a water rocket is the maximum height achieved by the rocket during flight, or the horizontal distance it travels, i.e. its range.\nThe design of a water rocket is somewhat constrained by the soda bottle used as its engine.\nThis means that the volume available for water and air is fixed, the initial launch pressure is limited by the bottle's strength (since the pressure is directly related to the energy available for the rocket, it is easy to see that it should be as high as possible) and the nozzle throat area is also fixed.\nGiven these manufacturing constraints, the design variables we are left with are the empty mass (it can be easily changed through adding ballast), the water volume at the launch, and the launch angle.\nWith this considerations in mind, a natural formulation for the water rocket problem is\n\n\\begin{align}\n \\text{maximize} &\\quad \\text{range or height} \\\\\n \\text{w.r.t.} &\\quad \\text{empty mass, initial water volume, launch angle, trajectory} \\\\\n \\text{subject to} &\\quad \\text{flight dynamics} \\\\\n &\\quad \\text{fluid dynamics inside the rocket} \\\\\n &\\quad 0 < \\text{initial water volume} < \\text{volume of bottle} \\\\\n &\\quad 0^\\circ < \\text{launch angle} < 90^\\circ \\\\\n &\\quad 0 < \\text{empty mass}\n\\end{align}\n\n## Model\n\nThe water rocket model is divided into three basic components: a *water engine*, responsible for modelling the fluid dynamics inside the rocket and returning its thrust; the *aerodynamics*, responsible for calculating the atmospheric drag of the rocket; and the *equations of motion*, responsible for propagating the rocket's trajectory in time, using Newton's laws and the forces provided by the other two components.\n\nIn order to integrate these three basic components, some additional interfacing components are necessary: an atmospheric model to provide values of ambient pressure for the water engine and air density to the calculation of the dynamic pressure for the aerodynamic model, and a component that calculates the instantaneous mass of the rocket by summing the water mass with the rocket's empty mass.\nThe high level layout of this model is shown in below.\n\n
\n \n
N2 diagram for the water rocket model
\n
\n\n`atmos`, `dynamic_pressure`, `aero` and `eom` are the same models used in [multi-phase cannonball](../multi_phase_cannonball/multi_phase_cannonball.md).\nThe remaining components are discussed below.\n\n```{Warning}\nThe `eom` component has a singularity in the flight path angle derivative when the flight speed is zero.\nThis happens because the rotational dynamics are not modelled.\nThis can cause convergence problems if the launch velocity is set to zero or the launch angle is set to $90^\\circ$\n```\n\n```{Note}\nSince the range of altitudes achieved by the water rocket is very small (100m), the air density and pressure are practically constant, thus the use of an atmospheric model is not necessary. However, using it makes it easier to reuse code from [multi-phase cannonball (../multi_phase_cannonball/multi_phase_cannonball.md).\n```\n\n### Water engine\n\nThe water engine is modelled by assuming that the air expansion in the rocket\nfollows an adiabatic process and the water flow is incompressible and inviscid,\ni.e. it follows Bernoulli's equation. We also make the following simplifying\nassumptions:\n\n1. The thrust developed after the water is depleted is negligible\n2. The area inside the bottle is much smaller than the nozzle area\n3. The inertial forces do not affect the fluid dynamics inside the bottle\n\nThis simplified modelling can be found in Prusa[@Prusa2000].\nA more rigorous formulation, which drops all these simplifying assumptions can be found in Wheeler[@Wheeler2002], Gommes[@Gommes2010], and Barria-Perotti[@BarrioPerotti2010].\n\nThe first assumption leads to an underestimation of the rocket performance, since the air left in the bottle after it is out of water is known to generate appreciable thrust[@Thorncroft2009].\nThis simplified model, however, produces physically meaningful results.\n\nThere are two states in this dynamical model, the water volume in the rocket $V_w$ and the gauge pressure inside the rocket $p$.\nThe constitutive equations and the N2 diagram showing the model organization are shown below.\n\n### Constitutive equations of the water engine model\n| Component | Equation |\n| -----------------------|-------------------------------------------------------------|\n| water_exhaust_speed | $v_\\text{out} = \\sqrt{2(p-p_a)/\\rho_w}$ |\n| water_flow_rate | $\\dot{V}_w = -v_\\text{out} A_\\text{out}$ |\n| pressure_rate | $\\dot{p} = kp\\frac{\\dot{V_w}}{(V_b-V_w)}$ |\n| water_thrust | $T = (\\rho_w v_\\text{out})(v_\\text{out}A_\\text{out})$ |\n\n
\n \n
N2 diagram for the water engine group
\n
\n\n### Water engine\n\nThe water engine is modelled by assuming that the air expansion in the rocket\nfollows an adiabatic process and the water flow is incompressible and inviscid,\ni.e. it follows Bernoulli's equation. We also make the following simplifying\nassumptions:\n\n1. The thrust developed after the water is depleted is negligible\n2. The area inside the bottle is much smaller than the nozzle area\n3. The inertial forces do not affect the fluid dynamics inside the bottle\n\nThis simplified modelling can be found in Prusa {cite}`Prusa2000`.\nA more rigorous formulation, which drops all these simplifying assumptions can be found in Wheeler {cite}`Wheeler2002`, Gommes {cite}`Gommes2010`, and Barria-Perotti {cite}`BarrioPerotti2010`.\n\nThe first assumption leads to an underestimation of the rocket performance, since the air left in the bottle after it is out of water is known to generate appreciable thrust {cite}`Thorncroft2009`.\nThis simplified model, however, produces physically meaningful results.\n\nThere are two states in this dynamical model, the water volume in the rocket $V_w$ and the gauge pressure inside the rocket $p$.\nThe constitutive equations and the N2 diagram showing the model organization are shown below.\n\n### Constitutive equations of the water engine model\n| Component | Equation |\n| -----------------------|-------------------------------------------------------------|\n| water_exhaust_speed | $v_\\text{out} = \\sqrt{2(p-p_a)/\\rho_w}$ |\n| water_flow_rate | $\\dot{V}_w = -v_\\text{out} A_\\text{out}$ |\n| pressure_rate | $\\dot{p} = kp\\frac{\\dot{V_w}}{(V_b-V_w)}$ |\n| water_thrust | $T = (\\rho_w v_\\text{out})(v_\\text{out}A_\\text{out})$ |\n\n
\n \n
N2 diagram for the water engine group
\n
\n\n\n```python\nimport numpy as np\n\nimport openmdao.api as om\n\n\nclass WaterEngine(om.Group):\n \"\"\"\n Computes thrust and water flow for a water.\n\n Simplifications:\n - the pressure due to the water column in the non inertial frame (i.e.\n under a+g acceleration) is insignificant compared to the air pressure\n - the water does not have appreciable speed inside the bottle\n \"\"\"\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_subsystem(name='water_exhaust_speed',\n subsys=_WaterExhaustSpeed(num_nodes=nn),\n promotes=['p', 'p_a', 'rho_w'])\n\n self.add_subsystem(name='water_flow_rate',\n subsys=_WaterFlowRate(num_nodes=nn),\n promotes=['A_out', 'Vdot'])\n\n self.add_subsystem(name='pressure_rate',\n subsys=_PressureRate(num_nodes=nn),\n promotes=['p', 'k', 'V_b', 'V_w', 'Vdot', 'pdot'])\n\n self.add_subsystem(name='water_thrust',\n subsys=_WaterThrust(num_nodes=nn),\n promotes=['rho_w', 'A_out', 'F'])\n\n self.connect('water_exhaust_speed.v_out', 'water_flow_rate.v_out')\n self.connect('water_exhaust_speed.v_out', 'water_thrust.v_out')\n\n```\n\n\n```python\nclass _WaterExhaustSpeed(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_input(name='rho_w', val=1e3*np.ones(nn), desc='water density', units='kg/m**3')\n self.add_input(name='p', val=6.5e5*np.ones(nn), desc='air pressure', units='N/m**2') # 5.5bar = 80 psi\n self.add_input(name='p_a', val=1.01e5*np.ones(nn), desc='air pressure', units='N/m**2')\n\n self.add_output(name='v_out', shape=(nn,), desc='water exhaust speed', units='m/s')\n\n ar = np.arange(nn)\n\n self.declare_partials(of='*', wrt='*', rows=ar, cols=ar)\n\n def compute(self, inputs, outputs):\n p = inputs['p']\n p_a = inputs['p_a']\n rho_w = inputs['rho_w']\n\n outputs['v_out'] = np.sqrt(2*(p-p_a)/rho_w)\n\n def compute_partials(self, inputs, partials):\n p = inputs['p']\n p_a = inputs['p_a']\n rho_w = inputs['rho_w']\n\n v_out = np.sqrt(2*(p-p_a)/rho_w)\n\n partials['v_out', 'p'] = 1/v_out/rho_w\n partials['v_out', 'p_a'] = -1/v_out/rho_w\n partials['v_out', 'rho_w'] = dv_outdrho_w = 1/v_out*(-(p-p_a)/rho_w**2)\n```\n\n\n```python\nclass _PressureRate(om.ExplicitComponent):\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_input(name='p', val=np.ones(nn), desc='air pressure', units='N/m**2')\n self.add_input(name='k', val=1.4*np.ones(nn), desc='polytropic coefficient for expansion', units=None)\n self.add_input(name='V_b', val=2e-3*np.ones(nn), desc='bottle volume', units='m**3')\n self.add_input(name='V_w', val=1e-3*np.ones(nn), desc='water volume', units='m**3')\n self.add_input(name='Vdot', shape=(nn,), desc='water flow', units='m**3/s')\n\n self.add_output(name='pdot', shape=(nn,), desc='pressure derivative', units='N/m**2/s')\n\n ar = np.arange(nn)\n\n self.declare_partials(of='*', wrt='*', rows=ar, cols=ar)\n\n def compute(self, inputs, outputs):\n p = inputs['p']\n k = inputs['k']\n V_b = inputs['V_b']\n V_w = inputs['V_w']\n Vdot = inputs['Vdot']\n\n pdot = p*k*Vdot/(V_b-V_w)\n\n outputs['pdot'] = pdot\n\n def compute_partials(self, inputs, partials):\n p = inputs['p']\n k = inputs['k']\n V_b = inputs['V_b']\n V_w = inputs['V_w']\n Vdot = inputs['Vdot']\n\n partials['pdot', 'p'] = k*Vdot/(V_b-V_w)\n partials['pdot', 'k'] = p*Vdot/(V_b-V_w)\n partials['pdot', 'V_b'] = -p*Vdot/(V_b-V_w)**2\n partials['pdot', 'V_w'] = p*Vdot/(V_b-V_w)**2\n partials['pdot', 'Vdot'] = p*k/(V_b-V_w)\n```\n\n\n```python\nclass _WaterFlowRate(om.ExplicitComponent):\n \"\"\" Computer water flow rate\"\"\"\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_input(name='A_out', val=np.ones(nn), desc='nozzle outlet area', units='m**2')\n self.add_input(name='v_out', val=np.zeros(nn), desc='water exhaust speed', units='m/s')\n\n self.add_output(name='Vdot', shape=(nn,), desc='water flow', units='m**3/s')\n\n ar = np.arange(nn)\n\n self.declare_partials(of='*', wrt='*', rows=ar, cols=ar)\n\n def compute(self, inputs, outputs):\n A_out = inputs['A_out']\n v_out = inputs['v_out']\n\n outputs['Vdot'] = -v_out*A_out\n\n def compute_partials(self, inputs, partials):\n A_out = inputs['A_out']\n v_out = inputs['v_out']\n\n partials['Vdot', 'A_out'] = -v_out\n partials['Vdot', 'v_out'] = -A_out\n\n```\n\nThe `_MassAdder` component calculates the rocket's instantaneous mass by\nsumming the water mass with the rockets empty mass, i.e.\n\n\\begin{align}\n m = m_\\text{empty}+\\rho_w V_w\n\\end{align}\n\n\n```python\nclass _MassAdder(om.ExplicitComponent):\n\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_input('m_empty', val=np.zeros(nn), desc='empty mass', units='kg')\n self.add_input('V_w', val=1e-3*np.ones(nn), desc='water volume', units='m**3')\n self.add_input('rho_w', val=1e3*np.ones(nn), desc=\"water density\", units='kg/m**3')\n\n self.add_output('m', val=np.zeros(nn), desc='total mass', units='kg')\n\n ar = np.arange(nn)\n self.declare_partials('*', '*', cols=ar, rows=ar)\n\n def compute(self, inputs, outputs):\n outputs['m'] = inputs['m_empty'] + inputs['rho_w']*inputs['V_w']\n\n def compute_partials(self, inputs, jacobian):\n jacobian['m', 'm_empty'] = 1\n jacobian['m', 'rho_w'] = inputs['V_w']\n jacobian['m', 'V_w'] = inputs['rho_w']\n```\n\nNow these components are joined in a single group\n\n\n```python\nclass WaterPropulsionODE(om.Group):\n\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n self.options.declare('ballistic', types=bool, default=False,\n desc='If True, neglect propulsion system.')\n\n def setup(self):\n nn = self.options['num_nodes']\n\n self.add_subsystem(name='atmos',\n subsys=USatm1976Comp(num_nodes=nn))\n\n if not self.options['ballistic']:\n self.add_subsystem(name='water_engine',\n subsys=WaterEngine(num_nodes=nn))\n\n self.add_subsystem(name='mass_adder',\n subsys=_MassAdder(num_nodes=nn))\n\n self.add_subsystem(name='dynamic_pressure',\n subsys=DynamicPressureComp(num_nodes=nn))\n\n self.add_subsystem(name='aero',\n subsys=LiftDragForceComp(num_nodes=nn))\n\n self.add_subsystem(name='eom',\n subsys=FlightPathEOM2D(num_nodes=nn))\n\n self.connect('atmos.rho', 'dynamic_pressure.rho')\n self.connect('dynamic_pressure.q', 'aero.q')\n\n self.connect('aero.f_drag', 'eom.D')\n self.connect('aero.f_lift', 'eom.L')\n\n if not self.options['ballistic']:\n self.connect('atmos.pres', 'water_engine.p_a')\n self.connect('water_engine.F', 'eom.T')\n self.connect('mass_adder.m', 'eom.m')\n```\n\n## Phases\n\nThe flight of the water rocket is split in three distinct phases: propelled ascent, ballistic ascent and ballistic descent.\nIf the simplification of no thrust without water were lifted, there would be an extra \"air propelled ascent\" phase between the propelled ascent and ballistic ascent phases.\n\n**Propelled ascent:** is the flight phase where the rocket still has water inside, and hence it is producing thrust.\nThe thrust is given by the water engine model, and fed into the flight dynamic equations.\nIt starts at launch and finishes when the water is depleted, i.e. $V_w=0$.\n\n**Ballistic ascent:** is the flight phase where the rocket is ascending ($\\gamma>0$) but produces no thrust.\nThis phase begins at the end of thepropelled ascent phase and ends at the apogee, defined by $\\gamma=0$.\n\n**Descent:** is the phase where the rocket is descending without thrust.\nIt begins at the end of the ballistic ascent phase and ends with ground impact, i.e. $h=0$.\n\n\n```python\ndef new_propelled_ascent_phase(transcription):\n propelled_ascent = dm.Phase(ode_class=WaterPropulsionODE,\n transcription=transcription)\n\n # All initial states except flight path angle and water volume are fixed\n # Final flight path angle is fixed (we will set it to zero so that the phase ends at apogee)\n # Final water volume is fixed (we will set it to zero so that phase ends when bottle empties)\n propelled_ascent.set_time_options(\n fix_initial=True, duration_bounds=(0.001, 0.5), duration_ref=0.1, units='s')\n propelled_ascent.add_state('r', units='m', rate_source='eom.r_dot',\n fix_initial=True, fix_final=False, ref=1.0, defect_ref=1.0)\n propelled_ascent.add_state('h', units='m', rate_source='eom.h_dot', targets=['atmos.h'],\n fix_initial=True, fix_final=False, ref=1.0, defect_ref=1.0)\n propelled_ascent.add_state('gam', units='deg', rate_source='eom.gam_dot', targets=['eom.gam'],\n fix_initial=False, fix_final=False, lower=0, upper=85.0, ref=90)\n propelled_ascent.add_state('v', units='m/s', rate_source='eom.v_dot', targets=['dynamic_pressure.v', 'eom.v'],\n fix_initial=True, fix_final=False, ref=100, defect_ref=100)\n\n propelled_ascent.add_state('p', units='bar', rate_source='water_engine.pdot',\n targets=['water_engine.p'], fix_initial=True, fix_final=False,\n lower=1.02)\n propelled_ascent.add_state('V_w', units='L', rate_source='water_engine.Vdot',\n targets=['water_engine.V_w', 'mass_adder.V_w'],\n fix_initial=False, fix_final=True, ref=10, defect_ref=10)\n\n propelled_ascent.add_parameter(\n 'S', targets=['aero.S'], units='m**2')\n propelled_ascent.add_parameter(\n 'm_empty', targets=['mass_adder.m_empty'], units='kg')\n propelled_ascent.add_parameter(\n 'V_b', targets=['water_engine.V_b'], units='m**3')\n\n propelled_ascent.add_timeseries_output('water_engine.F', 'T', units='N')\n\n return propelled_ascent\n```\n\n\n```python\ndef new_ballistic_ascent_phase(transcription):\n ballistic_ascent = dm.Phase(ode_class=WaterPropulsionODE, transcription=transcription,\n ode_init_kwargs={'ballistic': True})\n\n # All initial states are free (they will be linked to the final stages of propelled_ascent).\n # Final flight path angle is fixed (we will set it to zero so that the phase ends at apogee)\n ballistic_ascent.set_time_options(\n fix_initial=False, initial_bounds=(0.001, 1), duration_bounds=(0.001, 10),\n duration_ref=1, units='s')\n\n ballistic_ascent.add_state('r', units='m', rate_source='eom.r_dot', fix_initial=False,\n fix_final=False)\n ballistic_ascent.add_state('h', units='m', rate_source='eom.h_dot', targets=['atmos.h'],\n fix_initial=False, fix_final=False)\n ballistic_ascent.add_state('gam', units='deg', rate_source='eom.gam_dot', targets=['eom.gam'],\n fix_initial=False, fix_final=True, upper=89)\n ballistic_ascent.add_state('v', units='m/s', rate_source='eom.v_dot',\n targets=['dynamic_pressure.v', 'eom.v'], fix_initial=False,\n fix_final=False)\n\n ballistic_ascent.add_parameter('S', targets=['aero.S'], units='m**2')\n ballistic_ascent.add_parameter('m_empty', targets=['eom.m'], units='kg')\n\n return ballistic_ascent\n```\n\n\n```python\ndef new_descent_phase(transcription):\n descent = dm.Phase(ode_class=WaterPropulsionODE, transcription=transcription,\n ode_init_kwargs={'ballistic': True})\n\n # All initial states and time are free (they will be linked to the final states of ballistic_ascent).\n # Final altitude is fixed (we will set it to zero so that the phase ends at ground impact)\n descent.set_time_options(initial_bounds=(.5, 100), duration_bounds=(.5, 100),\n duration_ref=10, units='s')\n\n descent.add_state('r', units='m', rate_source='eom.r_dot', fix_initial=False, fix_final=False)\n descent.add_state('h', units='m', rate_source='eom.h_dot', targets=['atmos.h'],\n fix_initial=False, fix_final=True)\n descent.add_state('gam', units='deg', rate_source='eom.gam_dot', targets=['eom.gam'],\n fix_initial=False, fix_final=False)\n descent.add_state('v', units='m/s', rate_source='eom.v_dot',\n targets=['dynamic_pressure.v', 'eom.v'], fix_initial=False, fix_final=False)\n\n descent.add_parameter('S', targets=['aero.S'], units='m**2')\n descent.add_parameter('mass', targets=['eom.m'], units='kg')\n\n return descent\n```\n\n## Model parameters\n\nThe model requires a few constant parameters.\nThe values used are shown in the following table.\n\nValues for parameters in the water rocket model\n\n| Parameter | Value | Unit | Reference |\n|--------------------|----------------------|--------------|-----------------------------------------------------|\n| $C_D$ | 0.3450 | - | {cite}`BarrioPerotti2009` |\n| $S$ | $\\pi 106^2/4$ | $mm^2$ | {cite}`BarrioPerotti2009` |\n| $k$ | 1.2 | - | {cite}`Thorncroft2009` {cite}`Fischer2020` {cite}`Romanelli2013` |\n| $A_\\text{out}$ | $\\pi22^2/4$ | $mm^2$ | {cite}`aircommand_nozzle` |\n| $V_b$ | 2 | L | |\n| $\\rho_w$ | 1000 | $kg/m^3$ | |\n| $p_0$ | 6.5 | bar | |\n| $v_0$ | 0.1 | $m/s$ | |\n| $h_0$ | 0 | $m$ | |\n| $r_0$ | 0 | $m$ | |\n\nValues for the bottle volume $V_b$, its cross-sectional area $S$ and the nozzle area $A_\\text{out}$ are determined by the soda bottle that makes the rocket primary structure, and thus are not easily modifiable by the designer.\nThe polytropic coefficient $k$ is a function of the moist air characteristics inside the rocket.\nThe initial speed $v_0$ must be set to a value higher than zero, otherwise the flight dynamic equations become singular.\nThis issue arises from the angular dynamics of the rocket not being modelled.\nThe drag coefficient $C_D$ is sensitive to the aerodynamic design, but can be optimized by a single discipline analysis.\nThe initial pressure $p_0$ should be maximized in order to obtain the maximum range or height for the rocket.\nIt is limited by the structural properties of the bottle, which are modifiable by the designer, since the bottle needs to be available commercially.\nFinally, the starting point of the rocket is set to the origin.\n\n## Putting it all together\n\nThe different phases must be combined in a single trajectory, and linked in a sequence.\nHere we also define the design variables.\n\n\n```python\ndef new_water_rocket_trajectory(objective):\n tx_prop = dm.Radau(num_segments=50, order=3, compressed=True)\n tx_bal = dm.Radau(num_segments=10, order=3, compressed=True)\n tx_desc = dm.Radau(num_segments=10, order=3, compressed=True)\n traj = dm.Trajectory()\n\n # Add phases to trajectory\n propelled_ascent = traj.add_phase('propelled_ascent', new_propelled_ascent_phase(tx_prop))\n ballistic_ascent = traj.add_phase('ballistic_ascent', new_ballistic_ascent_phase(tx_bal))\n descent = traj.add_phase('descent', new_descent_phase(tx_desc))\n\n # Link phases\n traj.link_phases(phases=['propelled_ascent', 'ballistic_ascent'], vars=['*'])\n traj.link_phases(phases=['ballistic_ascent', 'descent'], vars=['*'])\n\n # Set objective function\n if objective == 'height':\n ballistic_ascent.add_objective('h', loc='final', ref=-1.0)\n elif objective == 'range':\n descent.add_objective('r', loc='final', ref=-0.01)\n else:\n raise ValueError(f\"objective='{objective}' is not defined. Try using 'height' or 'range'\")\n\n # Add design parameters to the trajectory.\n traj.add_parameter('CD',\n targets={'propelled_ascent': ['aero.CD'],\n 'ballistic_ascent': ['aero.CD'],\n 'descent': ['aero.CD']},\n val=0.3450, units=None, opt=False)\n traj.add_parameter('CL',\n targets={'propelled_ascent': ['aero.CL'],\n 'ballistic_ascent': ['aero.CL'],\n 'descent': ['aero.CL']},\n val=0.0, units=None, opt=False)\n traj.add_parameter('T',\n targets={'ballistic_ascent': ['eom.T'],\n 'descent': ['eom.T']},\n val=0.0, units='N', opt=False)\n traj.add_parameter('alpha',\n targets={'propelled_ascent': ['eom.alpha'],\n 'ballistic_ascent': ['eom.alpha'],\n 'descent': ['eom.alpha']},\n val=0.0, units='deg', opt=False)\n\n traj.add_parameter('m_empty', units='kg', val=0.15,\n targets={'propelled_ascent': 'm_empty',\n 'ballistic_ascent': 'm_empty',\n 'descent': 'mass'},\n lower=0, upper=1, ref=0.1,\n opt=True)\n traj.add_parameter('V_b', units='m**3', val=2e-3,\n targets={'propelled_ascent': 'V_b'},\n opt=False)\n\n traj.add_parameter('S', units='m**2', val=np.pi*106e-3**2/4, opt=False)\n traj.add_parameter('A_out', units='m**2', val=np.pi*22e-3**2/4.,\n targets={'propelled_ascent': ['water_engine.A_out']},\n opt=False)\n traj.add_parameter('k', units=None, val=1.2, opt=False,\n targets={'propelled_ascent': ['water_engine.k']})\n\n return traj, {'propelled_ascent': propelled_ascent,\n 'ballistic_ascent': ballistic_ascent,\n 'descent': descent}\n```\n\n## Helper Functions to Access the Results\n\n\n```python\ndef summarize_results(water_rocket_problem):\n p = water_rocket_problem\n Entry = namedtuple('Entry', 'value unit')\n summary = {\n 'Launch angle': Entry(p.get_val('traj.propelled_ascent.timeseries.states:gam', units='deg')[0, 0], 'deg'),\n 'Flight angle at end of propulsion': Entry(p.get_val('traj.propelled_ascent.timeseries.states:gam',\n units='deg')[-1, 0], 'deg'),\n 'Empty mass': Entry(p.get_val('traj.parameters:m_empty', units='kg')[0], 'kg'),\n 'Water volume': Entry(p.get_val('traj.propelled_ascent.timeseries.states:V_w', 'L')[0, 0], 'L'),\n 'Maximum range': Entry(p.get_val('traj.descent.timeseries.states:r', units='m')[-1, 0], 'm'),\n 'Maximum height': Entry(p.get_val('traj.ballistic_ascent.timeseries.states:h', units='m')[-1, 0], 'm'),\n 'Maximum velocity': Entry(p.get_val('traj.propelled_ascent.timeseries.states:v', units='m/s')[-1, 0], 'm/s'),\n }\n\n return summary\n\n```\n\n\n```python\ndef plot_propelled_ascent(p, exp_out):\n fig, ax = plt.subplots(5, 1, sharex=True, figsize=(4, 8))\n t_imp = p.get_val('traj.propelled_ascent.time', 's')\n t_exp = exp_out.get_val('traj.propelled_ascent.time', 's')\n\n ax[0].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:p', 'bar'), 'ro', markerfacecolor='None')\n ax[0].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:p', 'bar'), 'r-')\n ax[0].set_ylabel('p (bar)')\n ax[0].set_ylim(bottom=0)\n\n ax[1].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:V_w', 'L'), 'ro', markerfacecolor='None')\n ax[1].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:V_w', 'L'), 'r-')\n ax[1].set_ylabel('$V_w$ (L)')\n ax[1].set_ylim(0, p.get_val('traj.parameters:V_b', 'L')[0])\n\n ax[2].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.T', 'N'), 'ro', markerfacecolor='None')\n ax[2].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.T', 'N'), 'r-')\n ax[2].set_ylabel('T (N)')\n ax[2].set_ylim(bottom=0)\n\n ax[3].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:v', 'm/s'), 'ro', markerfacecolor='None')\n ax[3].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:v', 'm/s'), 'r-')\n ax[3].set_ylabel('v (m/s)')\n ax[3].set_ylim(bottom=0)\n\n ax[4].plot(t_imp, p.get_val('traj.propelled_ascent.timeseries.states:gam', 'deg'), 'ro', markerfacecolor='None')\n ax[4].plot(t_exp, exp_out.get_val('traj.propelled_ascent.timeseries.states:gam', 'deg'), 'r-')\n ax[4].set_ylabel('$\\gamma$ (deg)')\n ax[4].yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins='auto', steps=[1, 1.5, 3, 4.5, 6, 9, 10]))\n\n ax[-1].set_xlabel('t (s)')\n\n fig.tight_layout()\n```\n\n\n```python\ndef plot_states(p, exp_out):\n fig, axes = plt.subplots(nrows=4, ncols=1, figsize=(4, 8), sharex=True)\n\n states = ['r', 'h', 'v', 'gam']\n units = ['m', 'm', 'm/s', 'deg']\n phases = ['propelled_ascent', 'ballistic_ascent', 'descent']\n\n time_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.time'),\n 'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.time'),\n 'descent': p.get_val('traj.descent.timeseries.time')}\n\n time_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.time'),\n 'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.time'),\n 'descent': exp_out.get_val('traj.descent.timeseries.time')}\n\n x_imp = {phase: {state: p.get_val(f\"traj.{phase}.timeseries.states:{state}\", unit)\n for state, unit in zip(states, units)\n }\n for phase in phases\n }\n\n x_exp = {phase: {state: exp_out.get_val(f\"traj.{phase}.timeseries.states:{state}\", unit)\n for state, unit in zip(states, units)\n }\n for phase in phases\n }\n\n for i, (state, unit) in enumerate(zip(states, units)):\n axes[i].set_ylabel(f\"{state} ({unit})\" if state != 'gam' else f'$\\gamma$ ({unit})')\n\n axes[i].plot(time_imp['propelled_ascent'], x_imp['propelled_ascent'][state], 'ro', markerfacecolor='None')\n axes[i].plot(time_imp['ballistic_ascent'], x_imp['ballistic_ascent'][state], 'mo', markerfacecolor='None')\n axes[i].plot(time_imp['descent'], x_imp['descent'][state], 'bo', markerfacecolor='None')\n axes[i].plot(time_exp['propelled_ascent'], x_exp['propelled_ascent'][state], 'r-', label='Propelled Ascent')\n axes[i].plot(time_exp['ballistic_ascent'], x_exp['ballistic_ascent'][state], 'm-', label='Ballistic Ascent')\n axes[i].plot(time_exp['descent'], x_exp['descent'][state], 'b-', label='Descent')\n\n if state == 'gam':\n axes[i].yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins='auto', steps=[1, 1.5, 3, 4.5, 6, 9, 10]))\n axes[i].set_yticks(np.arange(-90, 91, 45))\n\n axes[i].set_xlabel('t (s)')\n axes[0].legend()\n\n fig.tight_layout()\n```\n\n\n```python\ndef plot_trajectory(p, exp_out):\n fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 8))\n\n time_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.time'),\n 'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.time'),\n 'descent': p.get_val('traj.descent.timeseries.time')}\n\n time_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.time'),\n 'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.time'),\n 'descent': exp_out.get_val('traj.descent.timeseries.time')}\n\n r_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.states:r'),\n 'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.states:r'),\n 'descent': p.get_val('traj.descent.timeseries.states:r')}\n\n r_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.states:r'),\n 'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.states:r'),\n 'descent': exp_out.get_val('traj.descent.timeseries.states:r')}\n\n h_imp = {'ballistic_ascent': p.get_val('traj.ballistic_ascent.timeseries.states:h'),\n 'propelled_ascent': p.get_val('traj.propelled_ascent.timeseries.states:h'),\n 'descent': p.get_val('traj.descent.timeseries.states:h')}\n\n h_exp = {'ballistic_ascent': exp_out.get_val('traj.ballistic_ascent.timeseries.states:h'),\n 'propelled_ascent': exp_out.get_val('traj.propelled_ascent.timeseries.states:h'),\n 'descent': exp_out.get_val('traj.descent.timeseries.states:h')}\n\n axes.plot(r_imp['propelled_ascent'], h_imp['propelled_ascent'], 'ro', markerfacecolor='None')\n axes.plot(r_imp['ballistic_ascent'], h_imp['ballistic_ascent'], 'mo', markerfacecolor='None')\n axes.plot(r_imp['descent'], h_imp['descent'], 'bo', markerfacecolor='None')\n\n axes.plot(r_exp['propelled_ascent'], h_exp['propelled_ascent'], 'r-')\n axes.plot(r_exp['ballistic_ascent'], h_exp['ballistic_ascent'], 'm-')\n axes.plot(r_exp['descent'], h_exp['descent'], 'b-')\n\n axes.set_xlabel('r (m)')\n axes.set_ylabel('h (m)')\n axes.set_aspect('equal', 'box')\n\n fig.tight_layout()\n```\n\n## Optimizing for Height\n\n\n```python\nfrom dymos.models.atmosphere import USatm1976Comp\nfrom dymos.examples.aircraft_steady_flight.dynamic_pressure_comp import DynamicPressureComp\nfrom dymos.examples.min_time_climb.aero.lift_drag_force_comp import LiftDragForceComp\nfrom dymos.models.eom.flight_path_eom_2d import FlightPathEOM2D\nfrom dymos.examples.water_rocket.water_engine_comp import _WaterThrust\nfrom dymos.examples.water_rocket.phases import set_sane_initial_guesses\nfrom dymos.examples.water_rocket.water_propulsion_ode import WaterPropulsionODE\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom collections import namedtuple\n\np = om.Problem(model=om.Group())\n\ntraj, phases = new_water_rocket_trajectory(objective='height')\ntraj = p.model.add_subsystem('traj', traj)\n\np.driver = om.pyOptSparseDriver(optimizer='IPOPT')\np.driver.opt_settings['print_level'] = 4\np.driver.opt_settings['max_iter'] = 1000\np.driver.declare_coloring()\n\n# Finish Problem Setup\np.model.linear_solver = om.DirectSolver()\n\np.setup()\nset_sane_initial_guesses(p, phases)\n\np.run_driver()\n\nsummary = summarize_results(p)\nfor key, entry in summary.items():\n print(f'{key}: {entry.value:6.4f} {entry.unit}')\n\nexp_out = traj.simulate(times_per_seg=200)\n\n# NOTE: only the last figure is shown in the generated docs\nplot_propelled_ascent(p, exp_out)\nplot_trajectory(p, exp_out)\nplot_states(p, exp_out)\n\nplt.show()\n\n# Check results (tolerance is relative unless value is zero)\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\n# Check results (tolerance is relative unless value is zero)\nassert_near_equal(summary['Launch angle'].value, 85, .02)\nassert_near_equal(summary['Flight angle at end of propulsion'].value, 85, .02)\nassert_near_equal(summary['Empty mass'].value, 0.1425114, 1e-3)\nassert_near_equal(summary['Water volume'].value, 0.868281, 1e-3)\nassert_near_equal(summary['Maximum range'].value, 15.78, 5)\nassert_near_equal(summary['Maximum height'].value, 54.133184, 1e-3)\nassert_near_equal(summary['Maximum velocity'].value, 47.320298, 1e-3)\n```\n\n# Optimizing for Range\n\n\n```python\np = om.Problem(model=om.Group())\n\ntraj, phases = new_water_rocket_trajectory(objective='range')\ntraj = p.model.add_subsystem('traj', traj)\n\np.driver = om.pyOptSparseDriver(optimizer='IPOPT')\np.driver.opt_settings['print_level'] = 4\np.driver.opt_settings['max_iter'] = 1000\np.driver.opt_settings['nlp_scaling_method'] = 'gradient-based'\np.driver.declare_coloring(tol=1.0E-12)\n\n# Finish Problem Setup\np.model.linear_solver = om.DirectSolver()\n# p.driver.add_recorder(om.SqliteRecorder('ex_water_rocket.db'))\n\np.setup()\nset_sane_initial_guesses(p, phases)\n\np.run_driver()\n\nsummary = summarize_results(p)\nfor key, entry in summary.items():\n print(f'{key}: {entry.value:6.4f} {entry.unit}')\n\nexp_out = traj.simulate(times_per_seg=200)\n\n# NOTE: only the last figure is shown in the generated docs\nplot_propelled_ascent(p, exp_out)\nplot_trajectory(p, exp_out)\nplot_states(p, exp_out)\n\nplt.show()\n\n# Check results (tolerance is relative unless value is zero)\n```\n\n\n```python\nfrom openmdao.utils.assert_utils import assert_near_equal\n\n# Check results (tolerance is relative unless value is zero)\nassert_near_equal(summary['Launch angle'].value, 46, 0.02)\nassert_near_equal(summary['Flight angle at end of propulsion'].value, 38, 0.02)\nassert_near_equal(summary['Empty mass'].value, 0.189, 1e-2)\nassert_near_equal(summary['Water volume'].value, 1.026, 1e-2)\nassert_near_equal(summary['Maximum range'].value, 85.11, 1e-2)\nassert_near_equal(summary['Maximum height'].value, 23.08, 1e-2)\nassert_near_equal(summary['Maximum velocity'].value, 41.31, 1e-2)\n```\n\n## References\n\n```{bibliography}\n:filter: docname in docnames\n```\n", "meta": {"hexsha": "87e81d739fcd5a680a760b0eec746d1ca4a5fa68", "size": 50249, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/examples/water_rocket/water_rocket.ipynb", "max_stars_repo_name": "kaushikponnapalli/dymos", "max_stars_repo_head_hexsha": "3fba91d0fc2c0e8460717b1bec80774676287739", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 104, "max_stars_repo_stars_event_min_datetime": "2018-09-08T16:52:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T23:35:30.000Z", "max_issues_repo_path": "docs/examples/water_rocket/water_rocket.ipynb", "max_issues_repo_name": "kaushikponnapalli/dymos", "max_issues_repo_head_hexsha": "3fba91d0fc2c0e8460717b1bec80774676287739", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 628, "max_issues_repo_issues_event_min_datetime": "2018-06-27T20:32:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:24:32.000Z", "max_forks_repo_path": "docs/examples/water_rocket/water_rocket.ipynb", "max_forks_repo_name": "kaushikponnapalli/dymos", "max_forks_repo_head_hexsha": "3fba91d0fc2c0e8460717b1bec80774676287739", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 46, "max_forks_repo_forks_event_min_datetime": "2018-06-27T20:54:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T07:23:32.000Z", "avg_line_length": 47.4494806421, "max_line_length": 428, "alphanum_fraction": 0.5432346912, "converted": true, "num_tokens": 9906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.32146962893669445}} {"text": "# Muography\n#### Roland Grinis - Researcher at MIPT Nuclear Physics Methods lab - CTO at GrinisRIT (grinisrit.com)\n#### Danila Riazanov - Sudent at MIPT, JetBrains Research trainee\n\nCode available within `NOA` [github.com/grinisrit/noa](https://github.com/grinisrit/noa) - Non-linear Optimisation Algorithms in `C++17` over [LibTorch](https://pytorch.org/cppdocs)\n\n## Installation\n\nThe `conda` environment provided with the repository has all the required dependencies. For this particular tutorial we will need the following `python` packages:\n\n\n```python\nimport torch\nfrom torch.utils.cpp_extension import load\n```\n\nNow we need to build and load `C++17/CUDA` extensions for `PyTorch`, set up the locations:\n\n\n```python\n!mkdir -p build\nnoa_location = '../..'\n```\n\nIf you are running this on Google Colab, you need to clone `NOA` and set `noa_location` accordingly:\n```python\n!git clone https://github.com/grinisrit/noa.git\nnoa_location = 'noa'\n```\n\nAlso, make sure that `ninja` and `g++-9` or higher are available. The following commands will do that for you:\n```python\n!pip install Ninja\n!add-apt-repository ppa:ubuntu-toolchain-r/test -y\n!apt update\n!apt install gcc-9 g++-9\n!update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 100 --slave /usr/bin/g++ g++ /usr/bin/g++-9\n!apt upgrade -y\n!gcc --version\n!g++ --version\n!nvcc --version\n```\nFinally, you get the extensions into `python` by calling `load`:\n\n\n```python\n!git clone https://github.com/grinisrit/noa.git\nnoa_location = 'noa'\n```\n\n Cloning into 'noa'...\n remote: Enumerating objects: 2374, done.\u001b[K\n remote: Counting objects: 100% (422/422), done.\u001b[K\n remote: Compressing objects: 100% (250/250), done.\u001b[K\n remote: Total 2374 (delta 245), reused 293 (delta 166), pack-reused 1952\u001b[K\n Receiving objects: 100% (2374/2374), 20.64 MiB | 23.85 MiB/s, done.\n Resolving deltas: 100% (1431/1431), done.\n\n\n\n```python\n!pip install Ninja\n!add-apt-repository ppa:ubuntu-toolchain-r/test -y\n!apt update\n!apt install gcc-9 g++-9\n!update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 100 --slave /usr/bin/g++ g++ /usr/bin/g++-9\n!apt upgrade -y\n!gcc --version\n!g++ --version\n!nvcc --version\n```\n\n Collecting Ninja\n Downloading ninja-1.10.2-py2.py3-none-manylinux_2_5_x86_64.manylinux1_x86_64.whl (108 kB)\n \u001b[K |████████████████████████████████| 108 kB 4.0 MB/s \n \u001b[?25hInstalling collected packages: Ninja\n Successfully installed Ninja-1.10.2\n Get:1 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/ InRelease [3,626 B]\n Ign:2 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 InRelease\n Get:3 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]\n Ign:4 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 InRelease\n Hit:5 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 Release\n Hit:6 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 Release\n Hit:7 http://archive.ubuntu.com/ubuntu bionic InRelease\n Get:9 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic InRelease [15.9 kB]\n Get:10 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]\n Hit:12 http://ppa.launchpad.net/cran/libgit2/ubuntu bionic InRelease\n Get:13 http://security.ubuntu.com/ubuntu bionic-security/restricted amd64 Packages [543 kB]\n Get:14 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]\n Hit:15 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease\n Get:16 http://archive.ubuntu.com/ubuntu bionic-updates/restricted amd64 Packages [575 kB]\n Get:17 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [1,424 kB]\n Hit:18 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease\n Get:19 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [2,294 kB]\n Get:20 http://archive.ubuntu.com/ubuntu bionic-updates/multiverse amd64 Packages [34.4 kB]\n Get:21 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [2,730 kB]\n Get:22 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic InRelease [20.8 kB]\n Get:23 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 Packages [2,199 kB]\n Get:24 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main Sources [1,792 kB]\n Get:25 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main amd64 Packages [917 kB]\n Get:26 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 Packages [50.4 kB]\n Fetched 12.9 MB in 8s (1,631 kB/s)\n Reading package lists... Done\n Hit:1 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran40/ InRelease\n Ign:2 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 InRelease\n Ign:3 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 InRelease\n Hit:4 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 Release\n Hit:5 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 Release\n Hit:6 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic InRelease\n Hit:8 http://security.ubuntu.com/ubuntu bionic-security InRelease\n Hit:9 http://archive.ubuntu.com/ubuntu bionic InRelease\n Hit:11 http://archive.ubuntu.com/ubuntu bionic-updates InRelease\n Hit:12 http://ppa.launchpad.net/cran/libgit2/ubuntu bionic InRelease\n Hit:13 http://archive.ubuntu.com/ubuntu bionic-backports InRelease\n Hit:14 http://ppa.launchpad.net/deadsnakes/ppa/ubuntu bionic InRelease\n Hit:15 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease\n Hit:16 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic InRelease\n Reading package lists... Done\n Building dependency tree \n Reading state information... Done\n 62 packages can be upgraded. Run 'apt list --upgradable' to see them.\n Reading package lists... Done\n Building dependency tree \n Reading state information... Done\n The following package was automatically installed and is no longer required:\n libnvidia-common-460\n Use 'apt autoremove' to remove it.\n The following additional packages will be installed:\n cpp-9 gcc-11-base gcc-9-base libasan5 libatomic1 libcc1-0 libgcc-9-dev\n libgcc-s1 libgomp1 libitm1 liblsan0 libquadmath0 libstdc++-9-dev libstdc++6\n libtsan0 libubsan1\n Suggested packages:\n gcc-9-locales g++-9-multilib gcc-9-doc libstdc++6-9-dbg gcc-9-multilib\n libgcc1-dbg libgomp1-dbg libitm1-dbg libatomic1-dbg libasan5-dbg\n liblsan0-dbg libtsan0-dbg libubsan1-dbg libquadmath0-dbg libstdc++-9-doc\n The following NEW packages will be installed:\n cpp-9 g++-9 gcc-11-base gcc-9 gcc-9-base libasan5 libgcc-9-dev libgcc-s1\n libstdc++-9-dev libubsan1\n The following packages will be upgraded:\n libatomic1 libcc1-0 libgomp1 libitm1 liblsan0 libquadmath0 libstdc++6\n libtsan0\n 8 upgraded, 10 newly installed, 0 to remove and 54 not upgraded.\n Need to get 30.2 MB of archives.\n After this operation, 121 MB of additional disk space will be used.\n Get:1 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 gcc-11-base amd64 11.1.0-1ubuntu1~18.04.1 [19.0 kB]\n Get:2 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libgcc-s1 amd64 11.1.0-1ubuntu1~18.04.1 [41.8 kB]\n Get:3 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libstdc++6 amd64 11.1.0-1ubuntu1~18.04.1 [580 kB]\n Get:4 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 gcc-9-base amd64 9.4.0-1ubuntu1~18.04 [19.3 kB]\n Get:5 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 cpp-9 amd64 9.4.0-1ubuntu1~18.04 [7,489 kB]\n Get:6 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libcc1-0 amd64 11.1.0-1ubuntu1~18.04.1 [40.8 kB]\n Get:7 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libgomp1 amd64 11.1.0-1ubuntu1~18.04.1 [107 kB]\n Get:8 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libitm1 amd64 11.1.0-1ubuntu1~18.04.1 [26.1 kB]\n Get:9 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libatomic1 amd64 11.1.0-1ubuntu1~18.04.1 [9,168 B]\n Get:10 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libasan5 amd64 9.4.0-1ubuntu1~18.04 [393 kB]\n Get:11 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 liblsan0 amd64 11.1.0-1ubuntu1~18.04.1 [150 kB]\n Get:12 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libtsan0 amd64 11.1.0-1ubuntu1~18.04.1 [331 kB]\n Get:13 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libubsan1 amd64 11.1.0-1ubuntu1~18.04.1 [143 kB]\n Get:14 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libquadmath0 amd64 11.1.0-1ubuntu1~18.04.1 [145 kB]\n Get:15 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libgcc-9-dev amd64 9.4.0-1ubuntu1~18.04 [2,356 kB]\n Get:16 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 gcc-9 amd64 9.4.0-1ubuntu1~18.04 [8,257 kB]\n Get:17 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libstdc++-9-dev amd64 9.4.0-1ubuntu1~18.04 [1,719 kB]\n Get:18 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 g++-9 amd64 9.4.0-1ubuntu1~18.04 [8,399 kB]\n Fetched 30.2 MB in 26s (1,143 kB/s)\n Selecting previously unselected package gcc-11-base:amd64.\n (Reading database ... 148486 files and directories currently installed.)\n Preparing to unpack .../gcc-11-base_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking gcc-11-base:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up gcc-11-base:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Selecting previously unselected package libgcc-s1:amd64.\n (Reading database ... 148491 files and directories currently installed.)\n Preparing to unpack .../libgcc-s1_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libgcc-s1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Replacing files in old package libgcc1:amd64 (1:8.4.0-1ubuntu1~18.04) ...\n Setting up libgcc-s1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n (Reading database ... 148493 files and directories currently installed.)\n Preparing to unpack .../libstdc++6_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libstdc++6:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Setting up libstdc++6:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Selecting previously unselected package gcc-9-base:amd64.\n (Reading database ... 148493 files and directories currently installed.)\n Preparing to unpack .../00-gcc-9-base_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking gcc-9-base:amd64 (9.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package cpp-9.\n Preparing to unpack .../01-cpp-9_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking cpp-9 (9.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../02-libcc1-0_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libcc1-0:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../03-libgomp1_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libgomp1:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../04-libitm1_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libitm1:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../05-libatomic1_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libatomic1:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package libasan5:amd64.\n Preparing to unpack .../06-libasan5_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking libasan5:amd64 (9.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../07-liblsan0_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking liblsan0:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../08-libtsan0_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libtsan0:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package libubsan1:amd64.\n Preparing to unpack .../09-libubsan1_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libubsan1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Preparing to unpack .../10-libquadmath0_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libquadmath0:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package libgcc-9-dev:amd64.\n Preparing to unpack .../11-libgcc-9-dev_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking libgcc-9-dev:amd64 (9.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package gcc-9.\n Preparing to unpack .../12-gcc-9_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking gcc-9 (9.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package libstdc++-9-dev:amd64.\n Preparing to unpack .../13-libstdc++-9-dev_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking libstdc++-9-dev:amd64 (9.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package g++-9.\n Preparing to unpack .../14-g++-9_9.4.0-1ubuntu1~18.04_amd64.deb ...\n Unpacking g++-9 (9.4.0-1ubuntu1~18.04) ...\n Setting up libquadmath0:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up libgomp1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up gcc-9-base:amd64 (9.4.0-1ubuntu1~18.04) ...\n Setting up libatomic1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up libcc1-0:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up libtsan0:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up liblsan0:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up cpp-9 (9.4.0-1ubuntu1~18.04) ...\n Setting up libasan5:amd64 (9.4.0-1ubuntu1~18.04) ...\n Setting up libitm1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up libubsan1:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up libgcc-9-dev:amd64 (9.4.0-1ubuntu1~18.04) ...\n Setting up gcc-9 (9.4.0-1ubuntu1~18.04) ...\n Setting up libstdc++-9-dev:amd64 (9.4.0-1ubuntu1~18.04) ...\n Setting up g++-9 (9.4.0-1ubuntu1~18.04) ...\n Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n Processing triggers for libc-bin (2.27-3ubuntu1.2) ...\n /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n \n update-alternatives: using /usr/bin/gcc-9 to provide /usr/bin/gcc (gcc) in auto mode\n Reading package lists... Done\n Building dependency tree \n Reading state information... Done\n Calculating upgrade... Done\n The following packages were automatically installed and are no longer required:\n libnvidia-common-460 linux-headers-4.15.0-153\n linux-headers-4.15.0-153-generic\n Use 'apt autoremove' to remove them.\n The following NEW packages will be installed:\n lib32gcc-s1 linux-headers-4.15.0-154 linux-headers-4.15.0-154-generic\n The following packages have been kept back:\n libcudnn8 libcudnn8-dev libnccl-dev libnccl2\n The following packages will be upgraded:\n binutils binutils-common binutils-x86-64-linux-gnu cuda-compat-11-0\n distro-info-data gnupg2 gzip lib32gcc1 lib32stdc++6 libaudit-common\n libaudit1 libbinutils libc-bin libcublas-dev libcublas10 libcudnn7\n libcudnn7-dev libgcc1 libhogweed4 libldap-2.4-2 libldap-common liblz4-1\n libnettle6 libobjc4 libp11-kit0 libpam-modules libpam-modules-bin\n libpam-runtime libpam-systemd libpam0g libperl5.26 libsasl2-2\n libsasl2-modules-db libseccomp2 libsystemd0 libudev1 libzstd1\n linux-headers-generic linux-libc-dev openssl perl perl-base\n perl-modules-5.26 r-cran-gert r-cran-survival systemd systemd-sysv tar\n ubuntu-keyring udev\n 50 upgraded, 3 newly installed, 0 to remove and 4 not upgraded.\n Need to get 485 MB of archives.\n After this operation, 161 MB of additional disk space will be used.\n Get:1 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 cuda-compat-11-0 450.142.00-1 [6,715 kB]\n Get:2 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 libcublas10 10.2.3.254-1 [43.1 MB]\n Get:3 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libgcc1 amd64 1:11.1.0-1ubuntu1~18.04.1 [41.7 kB]\n Get:4 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 gzip amd64 1.6-5ubuntu1.1 [89.8 kB]\n Get:5 https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 libcublas-dev 10.2.3.254-1 [42.4 MB]\n Get:6 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 lib32gcc1 amd64 1:11.1.0-1ubuntu1~18.04.1 [1,120 B]\n Get:7 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libperl5.26 amd64 5.26.1-6ubuntu0.5 [3,534 kB]\n Get:8 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 lib32gcc-s1 amd64 11.1.0-1ubuntu1~18.04.1 [49.5 kB]\n Get:9 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 libcudnn7-dev 7.6.5.32-1+cuda10.2 [165 MB]\n Get:10 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 perl amd64 5.26.1-6ubuntu0.5 [201 kB]\n Get:11 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 perl-base amd64 5.26.1-6ubuntu0.5 [1,391 kB]\n Get:12 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 lib32stdc++6 amd64 11.1.0-1ubuntu1~18.04.1 [611 kB]\n Get:13 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 perl-modules-5.26 all 5.26.1-6ubuntu0.5 [2,762 kB]\n Get:14 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 tar amd64 1.29b-2ubuntu0.2 [234 kB]\n Get:15 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libc-bin amd64 2.27-3ubuntu1.4 [643 kB]\n Get:16 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libaudit-common all 1:2.8.2-1ubuntu1.1 [4,068 B]\n Get:17 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libaudit1 amd64 1:2.8.2-1ubuntu1.1 [38.7 kB]\n Get:18 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpam0g amd64 1.1.8-3.6ubuntu2.18.04.3 [55.0 kB]\n Get:19 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpam-modules-bin amd64 1.1.8-3.6ubuntu2.18.04.3 [40.3 kB]\n Get:20 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpam-modules amd64 1.1.8-3.6ubuntu2.18.04.3 [252 kB]\n Get:21 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libsystemd0 amd64 237-3ubuntu10.51 [207 kB]\n Get:22 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpam-systemd amd64 237-3ubuntu10.51 [107 kB]\n Get:23 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 systemd amd64 237-3ubuntu10.51 [2,913 kB]\n Get:24 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 udev amd64 237-3ubuntu10.51 [1,102 kB]\n Get:25 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libudev1 amd64 237-3ubuntu10.51 [56.2 kB]\n Get:26 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libpam-runtime all 1.1.8-3.6ubuntu2.18.04.3 [37.1 kB]\n Get:27 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 systemd-sysv amd64 237-3ubuntu10.51 [13.9 kB]\n Get:28 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 liblz4-1 amd64 0.0~r131-2ubuntu3.1 [48.5 kB]\n Get:29 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libzstd1 amd64 1.3.3+dfsg-2ubuntu1.2 [189 kB]\n Get:30 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libnettle6 amd64 3.4.1-0ubuntu0.18.04.1 [111 kB]\n Get:31 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libhogweed4 amd64 3.4.1-0ubuntu0.18.04.1 [140 kB]\n Get:32 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libp11-kit0 amd64 0.23.9-2ubuntu0.1 [187 kB]\n Get:33 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libseccomp2 amd64 2.5.1-1ubuntu1~18.04.1 [43.1 kB]\n Get:34 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 ubuntu-keyring all 2018.09.18.1~18.04.2 [22.3 kB]\n Get:35 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 distro-info-data all 0.37ubuntu0.11 [4,652 B]\n Get:36 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 openssl amd64 1.1.1-1ubuntu2.1~18.04.10 [614 kB]\n Get:37 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 binutils-x86-64-linux-gnu amd64 2.30-21ubuntu1~18.04.5 [1,839 kB]\n Get:38 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 binutils-common amd64 2.30-21ubuntu1~18.04.5 [197 kB]\n Get:39 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 binutils amd64 2.30-21ubuntu1~18.04.5 [3,388 B]\n Get:40 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libbinutils amd64 2.30-21ubuntu1~18.04.5 [489 kB]\n Get:41 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libsasl2-modules-db amd64 2.1.27~101-g0780600+dfsg-3ubuntu2.3 [15.0 kB]\n Get:42 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libsasl2-2 amd64 2.1.27~101-g0780600+dfsg-3ubuntu2.3 [49.2 kB]\n Get:43 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libldap-common all 2.4.45+dfsg-1ubuntu1.10 [15.8 kB]\n Get:44 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 libldap-2.4-2 amd64 2.4.45+dfsg-1ubuntu1.10 [154 kB]\n Get:45 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 linux-headers-4.15.0-154 all 4.15.0-154.161 [10.9 MB]\n Get:46 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic/main amd64 libobjc4 amd64 11.1.0-1ubuntu1~18.04.1 [43.5 kB]\n Get:47 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 linux-headers-4.15.0-154-generic amd64 4.15.0-154.161 [1,256 kB]\n Get:48 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 linux-headers-generic amd64 4.15.0.154.143 [2,440 B]\n Get:49 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 linux-libc-dev amd64 4.15.0-154.161 [988 kB]\n Get:50 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 gnupg2 all 2.2.4-1ubuntu1.4 [5,292 B]\n Get:51 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main amd64 r-cran-gert amd64 1.3.2-1cran1.1804.0 [177 kB]\n Get:52 https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64 libcudnn7 7.6.5.32-1+cuda10.2 [189 MB]\n Get:53 http://ppa.launchpad.net/c2d4u.team/c2d4u4.0+/ubuntu bionic/main amd64 r-cran-survival amd64 3.2-12-1cran1.1804.0 [6,612 kB]\n Fetched 485 MB in 10s (49.7 MB/s)\n Extracting templates from packages: 100%\n Preconfiguring packages ...\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../gzip_1.6-5ubuntu1.1_amd64.deb ...\n Unpacking gzip (1.6-5ubuntu1.1) over (1.6-5ubuntu1) ...\n Setting up gzip (1.6-5ubuntu1.1) ...\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../libperl5.26_5.26.1-6ubuntu0.5_amd64.deb ...\n Unpacking libperl5.26:amd64 (5.26.1-6ubuntu0.5) over (5.26.1-6ubuntu0.3) ...\n Preparing to unpack .../perl_5.26.1-6ubuntu0.5_amd64.deb ...\n Unpacking perl (5.26.1-6ubuntu0.5) over (5.26.1-6ubuntu0.3) ...\n Preparing to unpack .../perl-base_5.26.1-6ubuntu0.5_amd64.deb ...\n Unpacking perl-base (5.26.1-6ubuntu0.5) over (5.26.1-6ubuntu0.3) ...\n Setting up perl-base (5.26.1-6ubuntu0.5) ...\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../perl-modules-5.26_5.26.1-6ubuntu0.5_all.deb ...\n Unpacking perl-modules-5.26 (5.26.1-6ubuntu0.5) over (5.26.1-6ubuntu0.3) ...\n Preparing to unpack .../tar_1.29b-2ubuntu0.2_amd64.deb ...\n Unpacking tar (1.29b-2ubuntu0.2) over (1.29b-2ubuntu0.1) ...\n Setting up tar (1.29b-2ubuntu0.2) ...\n update-alternatives: warning: forcing reinstallation of alternative /usr/sbin/rmt-tar because link group rmt is broken\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../libc-bin_2.27-3ubuntu1.4_amd64.deb ...\n Unpacking libc-bin (2.27-3ubuntu1.4) over (2.27-3ubuntu1.2) ...\n Setting up libc-bin (2.27-3ubuntu1.4) ...\n /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n \n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../libaudit-common_1%3a2.8.2-1ubuntu1.1_all.deb ...\n Unpacking libaudit-common (1:2.8.2-1ubuntu1.1) over (1:2.8.2-1ubuntu1) ...\n Setting up libaudit-common (1:2.8.2-1ubuntu1.1) ...\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../libaudit1_1%3a2.8.2-1ubuntu1.1_amd64.deb ...\n Unpacking libaudit1:amd64 (1:2.8.2-1ubuntu1.1) over (1:2.8.2-1ubuntu1) ...\n Setting up libaudit1:amd64 (1:2.8.2-1ubuntu1.1) ...\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../libpam0g_1.1.8-3.6ubuntu2.18.04.3_amd64.deb ...\n Unpacking libpam0g:amd64 (1.1.8-3.6ubuntu2.18.04.3) over (1.1.8-3.6ubuntu2.18.04.2) ...\n Setting up libpam0g:amd64 (1.1.8-3.6ubuntu2.18.04.3) ...\n (Reading database ... 149564 files and directories currently installed.)\n Preparing to unpack .../libpam-modules-bin_1.1.8-3.6ubuntu2.18.04.3_amd64.deb ...\n Unpacking libpam-modules-bin (1.1.8-3.6ubuntu2.18.04.3) over (1.1.8-3.6ubuntu2.18.04.2) ...\n Setting up libpam-modules-bin (1.1.8-3.6ubuntu2.18.04.3) ...\n (Reading database ... 149566 files and directories currently installed.)\n Preparing to unpack .../libpam-modules_1.1.8-3.6ubuntu2.18.04.3_amd64.deb ...\n Unpacking libpam-modules:amd64 (1.1.8-3.6ubuntu2.18.04.3) over (1.1.8-3.6ubuntu2.18.04.2) ...\n Setting up libpam-modules:amd64 (1.1.8-3.6ubuntu2.18.04.3) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libsystemd0_237-3ubuntu10.51_amd64.deb ...\n Unpacking libsystemd0:amd64 (237-3ubuntu10.51) over (237-3ubuntu10.50) ...\n Setting up libsystemd0:amd64 (237-3ubuntu10.51) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libpam-systemd_237-3ubuntu10.51_amd64.deb ...\n Unpacking libpam-systemd:amd64 (237-3ubuntu10.51) over (237-3ubuntu10.50) ...\n Preparing to unpack .../systemd_237-3ubuntu10.51_amd64.deb ...\n Unpacking systemd (237-3ubuntu10.51) over (237-3ubuntu10.50) ...\n Preparing to unpack .../udev_237-3ubuntu10.51_amd64.deb ...\n Unpacking udev (237-3ubuntu10.51) over (237-3ubuntu10.50) ...\n Preparing to unpack .../libudev1_237-3ubuntu10.51_amd64.deb ...\n Unpacking libudev1:amd64 (237-3ubuntu10.51) over (237-3ubuntu10.50) ...\n Setting up libudev1:amd64 (237-3ubuntu10.51) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libpam-runtime_1.1.8-3.6ubuntu2.18.04.3_all.deb ...\n Unpacking libpam-runtime (1.1.8-3.6ubuntu2.18.04.3) over (1.1.8-3.6ubuntu2.18.04.2) ...\n Setting up libpam-runtime (1.1.8-3.6ubuntu2.18.04.3) ...\n Setting up systemd (237-3ubuntu10.51) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../systemd-sysv_237-3ubuntu10.51_amd64.deb ...\n Unpacking systemd-sysv (237-3ubuntu10.51) over (237-3ubuntu10.50) ...\n Preparing to unpack .../liblz4-1_0.0~r131-2ubuntu3.1_amd64.deb ...\n Unpacking liblz4-1:amd64 (0.0~r131-2ubuntu3.1) over (0.0~r131-2ubuntu3) ...\n Setting up liblz4-1:amd64 (0.0~r131-2ubuntu3.1) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libzstd1_1.3.3+dfsg-2ubuntu1.2_amd64.deb ...\n Unpacking libzstd1:amd64 (1.3.3+dfsg-2ubuntu1.2) over (1.3.3+dfsg-2ubuntu1.1) ...\n Setting up libzstd1:amd64 (1.3.3+dfsg-2ubuntu1.2) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libnettle6_3.4.1-0ubuntu0.18.04.1_amd64.deb ...\n Unpacking libnettle6:amd64 (3.4.1-0ubuntu0.18.04.1) over (3.4-1) ...\n Setting up libnettle6:amd64 (3.4.1-0ubuntu0.18.04.1) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libhogweed4_3.4.1-0ubuntu0.18.04.1_amd64.deb ...\n Unpacking libhogweed4:amd64 (3.4.1-0ubuntu0.18.04.1) over (3.4-1) ...\n Setting up libhogweed4:amd64 (3.4.1-0ubuntu0.18.04.1) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libp11-kit0_0.23.9-2ubuntu0.1_amd64.deb ...\n Unpacking libp11-kit0:amd64 (0.23.9-2ubuntu0.1) over (0.23.9-2) ...\n Setting up libp11-kit0:amd64 (0.23.9-2ubuntu0.1) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libseccomp2_2.5.1-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libseccomp2:amd64 (2.5.1-1ubuntu1~18.04.1) over (2.4.3-1ubuntu3.18.04.3) ...\n Setting up libseccomp2:amd64 (2.5.1-1ubuntu1~18.04.1) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../ubuntu-keyring_2018.09.18.1~18.04.2_all.deb ...\n Unpacking ubuntu-keyring (2018.09.18.1~18.04.2) over (2018.09.18.1~18.04.0) ...\n Setting up ubuntu-keyring (2018.09.18.1~18.04.2) ...\n (Reading database ... 149570 files and directories currently installed.)\n Preparing to unpack .../libgcc1_1%3a11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libgcc1 (1:11.1.0-1ubuntu1~18.04.1) over (1:8.4.0-1ubuntu1~18.04) ...\n Setting up libgcc1 (1:11.1.0-1ubuntu1~18.04.1) ...\n (Reading database ... 149571 files and directories currently installed.)\n Preparing to unpack .../00-distro-info-data_0.37ubuntu0.11_all.deb ...\n Unpacking distro-info-data (0.37ubuntu0.11) over (0.37ubuntu0.10) ...\n Preparing to unpack .../01-openssl_1.1.1-1ubuntu2.1~18.04.10_amd64.deb ...\n Unpacking openssl (1.1.1-1ubuntu2.1~18.04.10) over (1.1.1-1ubuntu2.1~18.04.6) ...\n Preparing to unpack .../02-binutils-x86-64-linux-gnu_2.30-21ubuntu1~18.04.5_amd64.deb ...\n Unpacking binutils-x86-64-linux-gnu (2.30-21ubuntu1~18.04.5) over (2.30-21ubuntu1~18.04.4) ...\n Preparing to unpack .../03-binutils-common_2.30-21ubuntu1~18.04.5_amd64.deb ...\n Unpacking binutils-common:amd64 (2.30-21ubuntu1~18.04.5) over (2.30-21ubuntu1~18.04.4) ...\n Preparing to unpack .../04-binutils_2.30-21ubuntu1~18.04.5_amd64.deb ...\n Unpacking binutils (2.30-21ubuntu1~18.04.5) over (2.30-21ubuntu1~18.04.4) ...\n Preparing to unpack .../05-libbinutils_2.30-21ubuntu1~18.04.5_amd64.deb ...\n Unpacking libbinutils:amd64 (2.30-21ubuntu1~18.04.5) over (2.30-21ubuntu1~18.04.4) ...\n Preparing to unpack .../06-cuda-compat-11-0_450.142.00-1_amd64.deb ...\n Unpacking cuda-compat-11-0 (450.142.00-1) over (450.80.02-1) ...\n Preparing to unpack .../07-lib32gcc1_1%3a11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking lib32gcc1 (1:11.1.0-1ubuntu1~18.04.1) over (1:8.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package lib32gcc-s1.\n Preparing to unpack .../08-lib32gcc-s1_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking lib32gcc-s1 (11.1.0-1ubuntu1~18.04.1) ...\n Preparing to unpack .../09-lib32stdc++6_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking lib32stdc++6 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Preparing to unpack .../10-libcublas10_10.2.3.254-1_amd64.deb ...\n Unpacking libcublas10 (10.2.3.254-1) over (10.2.1.243-1) ...\n Preparing to unpack .../11-libcublas-dev_10.2.3.254-1_amd64.deb ...\n Unpacking libcublas-dev (10.2.3.254-1) over (10.2.1.243-1) ...\n Preparing to unpack .../12-libcudnn7-dev_7.6.5.32-1+cuda10.2_amd64.deb ...\n update-alternatives: removing manually selected alternative - switching libcudnn to auto mode\n update-alternatives: using /usr/include/x86_64-linux-gnu/cudnn_v8.h to provide /usr/include/cudnn.h (libcudnn) in auto mode\n Unpacking libcudnn7-dev (7.6.5.32-1+cuda10.2) over (7.6.5.32-1+cuda10.1) ...\n Preparing to unpack .../13-libcudnn7_7.6.5.32-1+cuda10.2_amd64.deb ...\n Unpacking libcudnn7 (7.6.5.32-1+cuda10.2) over (7.6.5.32-1+cuda10.1) ...\n Preparing to unpack .../14-libsasl2-modules-db_2.1.27~101-g0780600+dfsg-3ubuntu2.3_amd64.deb ...\n Unpacking libsasl2-modules-db:amd64 (2.1.27~101-g0780600+dfsg-3ubuntu2.3) over (2.1.27~101-g0780600+dfsg-3ubuntu2.1) ...\n Preparing to unpack .../15-libsasl2-2_2.1.27~101-g0780600+dfsg-3ubuntu2.3_amd64.deb ...\n Unpacking libsasl2-2:amd64 (2.1.27~101-g0780600+dfsg-3ubuntu2.3) over (2.1.27~101-g0780600+dfsg-3ubuntu2.1) ...\n Preparing to unpack .../16-libldap-common_2.4.45+dfsg-1ubuntu1.10_all.deb ...\n Unpacking libldap-common (2.4.45+dfsg-1ubuntu1.10) over (2.4.45+dfsg-1ubuntu1.6) ...\n Preparing to unpack .../17-libldap-2.4-2_2.4.45+dfsg-1ubuntu1.10_amd64.deb ...\n Unpacking libldap-2.4-2:amd64 (2.4.45+dfsg-1ubuntu1.10) over (2.4.45+dfsg-1ubuntu1.6) ...\n Preparing to unpack .../18-libobjc4_11.1.0-1ubuntu1~18.04.1_amd64.deb ...\n Unpacking libobjc4:amd64 (11.1.0-1ubuntu1~18.04.1) over (8.4.0-1ubuntu1~18.04) ...\n Selecting previously unselected package linux-headers-4.15.0-154.\n Preparing to unpack .../19-linux-headers-4.15.0-154_4.15.0-154.161_all.deb ...\n Unpacking linux-headers-4.15.0-154 (4.15.0-154.161) ...\n Selecting previously unselected package linux-headers-4.15.0-154-generic.\n Preparing to unpack .../20-linux-headers-4.15.0-154-generic_4.15.0-154.161_amd64.deb ...\n Unpacking linux-headers-4.15.0-154-generic (4.15.0-154.161) ...\n Preparing to unpack .../21-linux-headers-generic_4.15.0.154.143_amd64.deb ...\n Unpacking linux-headers-generic (4.15.0.154.143) over (4.15.0.153.142) ...\n Preparing to unpack .../22-linux-libc-dev_4.15.0-154.161_amd64.deb ...\n Unpacking linux-libc-dev:amd64 (4.15.0-154.161) over (4.15.0-118.119) ...\n Preparing to unpack .../23-r-cran-gert_1.3.2-1cran1.1804.0_amd64.deb ...\n Unpacking r-cran-gert (1.3.2-1cran1.1804.0) over (1.3.1-1cran1.1804.0) ...\n Preparing to unpack .../24-r-cran-survival_3.2-12-1cran1.1804.0_amd64.deb ...\n Unpacking r-cran-survival (3.2-12-1cran1.1804.0) over (3.2-11-1cran1.1804.0) ...\n Preparing to unpack .../25-gnupg2_2.2.4-1ubuntu1.4_all.deb ...\n Unpacking gnupg2 (2.2.4-1ubuntu1.4) over (2.2.4-1ubuntu1.3) ...\n Setting up libcudnn7 (7.6.5.32-1+cuda10.2) ...\n Setting up libobjc4:amd64 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up r-cran-gert (1.3.2-1cran1.1804.0) ...\n Setting up libldap-common (2.4.45+dfsg-1ubuntu1.10) ...\n Setting up cuda-compat-11-0 (450.142.00-1) ...\n Setting up systemd-sysv (237-3ubuntu10.51) ...\n Setting up libsasl2-modules-db:amd64 (2.1.27~101-g0780600+dfsg-3ubuntu2.3) ...\n Setting up linux-libc-dev:amd64 (4.15.0-154.161) ...\n Setting up libsasl2-2:amd64 (2.1.27~101-g0780600+dfsg-3ubuntu2.3) ...\n Setting up libcudnn7-dev (7.6.5.32-1+cuda10.2) ...\n update-alternatives: using /usr/include/x86_64-linux-gnu/cudnn_v7.h to provide /usr/include/cudnn.h (libcudnn) in manual mode\n Setting up linux-headers-4.15.0-154 (4.15.0-154.161) ...\n Setting up distro-info-data (0.37ubuntu0.11) ...\n Setting up lib32gcc-s1 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up perl-modules-5.26 (5.26.1-6ubuntu0.5) ...\n Setting up binutils-common:amd64 (2.30-21ubuntu1~18.04.5) ...\n Setting up gnupg2 (2.2.4-1ubuntu1.4) ...\n Setting up libcublas10 (10.2.3.254-1) ...\n Setting up libcublas-dev (10.2.3.254-1) ...\n Setting up libperl5.26:amd64 (5.26.1-6ubuntu0.5) ...\n Setting up udev (237-3ubuntu10.51) ...\n invoke-rc.d: could not determine current runlevel\n invoke-rc.d: policy-rc.d denied execution of restart.\n Setting up libldap-2.4-2:amd64 (2.4.45+dfsg-1ubuntu1.10) ...\n Setting up linux-headers-4.15.0-154-generic (4.15.0-154.161) ...\n /etc/kernel/header_postinst.d/dkms:\n * dkms: running auto installation service for kernel 4.15.0-154-generic\n \n Kernel preparation unnecessary for this kernel. Skipping...\n applying patch disable_fstack-clash-protection_fcf-protection.patch...patching file Kbuild\n Hunk #1 succeeded at 82 (offset 11 lines).\n \n \n Building module:\n cleaning build area...(bad exit status: 2)\n unset ARCH; [ ! -h /usr/bin/cc ] && export CC=/usr/bin/gcc; env NV_VERBOSE=1 'make' -j2 NV_EXCLUDE_BUILD_MODULES='' KERNEL_UNAME=4.15.0-154-generic IGNORE_XEN_PRESENCE=1 IGNORE_CC_MISMATCH=1 SYSSRC=/lib/modules/4.15.0-154-generic/build LD=/usr/bin/ld.bfd modules................................................\n cleaning build area...(bad exit status: 2)\n \n DKMS: build completed.\n \n nvidia.ko:\n Running module version sanity check.\n - Original module\n - No original module exists within this kernel\n - Installation\n - Installing to /lib/modules/4.15.0-154-generic/updates/dkms/\n \n nvidia-modeset.ko:\n Running module version sanity check.\n - Original module\n - No original module exists within this kernel\n - Installation\n - Installing to /lib/modules/4.15.0-154-generic/updates/dkms/\n \n nvidia-drm.ko:\n Running module version sanity check.\n - Original module\n - No original module exists within this kernel\n - Installation\n - Installing to /lib/modules/4.15.0-154-generic/updates/dkms/\n \n nvidia-peermem.ko:\n Running module version sanity check.\n - Original module\n - No original module exists within this kernel\n - Installation\n - Installing to /lib/modules/4.15.0-154-generic/updates/dkms/\n \n nvidia-uvm.ko:\n Running module version sanity check.\n - Original module\n - No original module exists within this kernel\n - Installation\n - Installing to /lib/modules/4.15.0-154-generic/updates/dkms/\n \n depmod...\n \n DKMS: install completed.\n ...done.\n Setting up openssl (1.1.1-1ubuntu2.1~18.04.10) ...\n Setting up lib32stdc++6 (11.1.0-1ubuntu1~18.04.1) ...\n Setting up r-cran-survival (3.2-12-1cran1.1804.0) ...\n Setting up lib32gcc1 (1:11.1.0-1ubuntu1~18.04.1) ...\n Setting up linux-headers-generic (4.15.0.154.143) ...\n Setting up libpam-systemd:amd64 (237-3ubuntu10.51) ...\n Setting up libbinutils:amd64 (2.30-21ubuntu1~18.04.5) ...\n Setting up perl (5.26.1-6ubuntu0.5) ...\n Setting up binutils-x86-64-linux-gnu (2.30-21ubuntu1~18.04.5) ...\n Setting up binutils (2.30-21ubuntu1~18.04.5) ...\n Processing triggers for mime-support (3.60ubuntu1) ...\n Processing triggers for libc-bin (2.27-3ubuntu1.4) ...\n /sbin/ldconfig.real: /usr/local/lib/python3.7/dist-packages/ideep4py/lib/libmkldnn.so.0 is not a symbolic link\n \n Processing triggers for man-db (2.8.3-2ubuntu0.1) ...\n Processing triggers for dbus (1.12.2-1ubuntu1.2) ...\n gcc (Ubuntu 9.4.0-1ubuntu1~18.04) 9.4.0\n Copyright (C) 2019 Free Software Foundation, Inc.\n This is free software; see the source for copying conditions. There is NO\n warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n \n g++ (Ubuntu 9.4.0-1ubuntu1~18.04) 9.4.0\n Copyright (C) 2019 Free Software Foundation, Inc.\n This is free software; see the source for copying conditions. There is NO\n warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n \n nvcc: NVIDIA (R) Cuda compiler driver\n Copyright (c) 2005-2020 NVIDIA Corporation\n Built on Wed_Jul_22_19:09:09_PDT_2020\n Cuda compilation tools, release 11.0, V11.0.221\n Build cuda_11.0_bu.TC445_37.28845127_0\n\n\n\n```python\nmuons = load(name='muons',\n build_directory='./build',\n sources=[f'{noa_location}/docs/pms/muons.cc'],\n extra_include_paths=[f'{noa_location}/include'],\n extra_cflags=['-Wall -Wextra -Wpedantic -O3 -std=c++17'],\n verbose=False)\n```\n\n\n```python\nmuons_cuda = load(name='muons_cuda',\n build_directory='./build', \n sources=[f'{noa_location}/docs/pms/muons.cu'],\n extra_include_paths=[f'{noa_location}/include'],\n extra_cflags=['-Wall -Wextra -Wpedantic -O3 -std=c++17'],\n extra_cuda_cflags=['-std=c++17 --extended-lambda'],\n verbose=False) if torch.cuda.is_available() else None\n```\n\n## Differential Cross-Section calculations\n\nDifferential cross-sections (DCS) are implemented in `` for `CPU` and `` for `CUDA` within the namespace `noa::pms::dcs`.\n\nHere, we demonstrate the calculations for muons passing through the standard rock. In `` you will find:\n```cpp\nconstexpr ParticleMass MUON_MASS = 0.10565839; // GeV/c^2\n\nconstexpr AtomicElement STANDARD_ROCK =\n AtomicElement{\n 22., // Atomic mass in g/mol\n 0.1364E-6, // Mean Excitation in GeV\n 11 // Atomic number\n };\n```\n\nLet's get a range of kinetic and recoil energies:\n\n\n```python\nkinetic_energies = torch.linspace(1e-3, 1e6, 10000).double()\nrecoil_energies = 0.0505 * kinetic_energies\n```\n\n\n```python\nkinetic_energies_gpu = kinetic_energies.cuda()\nrecoil_energies_gpu = recoil_energies.cuda()\n```\n\n\n```python\nkinetic_energies_gpu[:5]\n```\n\n\n\n\n tensor([1.0000e-03, 1.0001e+02, 2.0002e+02, 3.0003e+02, 4.0004e+02],\n device='cuda:0', dtype=torch.float64)\n\n\n\nFrom now on, we shall get ourselves into the namespace:\n```cpp\nusing namespace noa::pms;\n```\nOn `CPU` the DCS computation kernel can be mapped on a tensor via the utility `dcs::vmap`. The user is expected to provide a `result` tensor with the same options as `kinetic_energies` which will get populated with the calculation values:\n```cpp\nconst auto result = torch::zeros_like(kinetic_energies);\n```\n\n### Bremsstrahlung\n\nBremsstrahlung dominates other muon interaction processes in the region of catastrophic collisions (𝑣 ≥ 0.1 ), that is\nat “moderate” muon energies above the kinematic limit for knock–on electron production. At high energies (𝐸 ≥ 1\nTeV) this process contributes about 40% of the average muon energy loss.\n\n##### Input:\n * K - The projectile initial kinetic energy, in GeV\n * q - The kinetic energy lost to the photon, in GeV\n * A - The mass number of the target atom, in g/mol\n * Z - The charge number of the target atom.\n * mu - The projectile rest mass, in GeV\n \n\n##### Output:\n DCS (differential crros-section) in m^2/kg.\n \n#### Definitions and Applicability\n\nTheory from: https://pdg.lbl.gov/2014/AtomicNuclearProperties/adndt.pdf.\n\nThe formula for the differential cross section applies when:\n\n* 𝐸 ≫ 𝜇, hence the ultrarelativistic approximation is used\n* 𝐸 ≤ $10^{20}$ eV; above this energy, LPM suppression can be expected\n* 𝑣 ≥ $10^{−6}$ ; below $10^{−6}$ Ter-Mikaelyan suppression takes place. However, in the latter region the cross section\nof muon bremsstrahlung is several orders of magnitude less than that of other processes.\nThe Coulomb correction (for high 𝑍) is not included. However, existing calculations [AB97] show that for muon\nbremsstrahlung this correction is small.\n\n##### Formulae\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}\\nu} = \\left.\\frac{\\text{d}\\sigma}{\\text{d}\\nu}\\right|_\\text{brems, elec} + \\left.\\frac{\\text{d}\\sigma}{\\text{d}\\nu}\\right|_\\text{brems, nucl}\n\\end{equation}\n\nThe differential cross section for muon bremsstrahlung from a (screened) nucleus:\n\n\\begin{equation}\n\\left.\\frac{\\text{d}\\sigma}{\\text{d}\\nu}\\right|_\\text{brems, nucl} = \\alpha(2Z\\frac{m_e}{M_\\mu})^{2}(\\frac{4}{3}(\\frac{1}{\\nu} - 1) + \\nu)\\Phi_n(\\delta)\n\\end{equation}\n\nTo account for bremsstrahlung losses on atomic electrons, approximation for the contribution from electrons, taking into account electronic binding and recoil, is \n\n\\begin{equation}\n\\left.\\frac{\\text{d}\\sigma}{\\text{d}\\nu}\\right|_\\text{brems, elec} = \\alpha Z(2\\frac{m_e}{M_\\mu})^{2}(\\frac{4}{3}(\\frac{1}{\\nu} - 1) + \\nu)\\Phi_\\text{in}(\\delta)\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}\\nu} = \\alpha Z(2\\frac{m_e}{M_\\mu})^{2}(\\frac{4}{3}(\\frac{1}{\\nu} - 1) + \\nu)(\\Phi_\\text{in}(\\delta) + Z\\Phi_n(\\delta) )\n\\end{equation}\n \nHere $\\nu = \\frac{q}{E}$ is the fraction of the muon's energy transferred to the photon, and \n\n\\begin{equation}\n\\Phi(\\delta) = \\ln(\\frac{BZ^{\\frac{-1}{3}}(M_\\mu + \\delta(D_n\\sqrt{e} - 2))}{(m_e + \\delta \\sqrt{e}BZ^{\\frac{-1}{3}})D_n},\n\\end{equation}\n\nwhere $D_n = 1.54A^{0.27}$ , $B = 182.7$ ($B = 202.4$ for hygrogen), $e = 2.7181...$ and\n\n\\begin{equation}\n\\delta = \\frac{M_\\mu^{2}\\nu}{2E(1 - \\nu)}\n\\end{equation}\n\n\\begin{equation}\n\\Phi_\\text{in}(\\delta) = \\ln(\\frac{M_\\mu BZ^{-2/3} \\sqrt{e}}{(m_e + \\delta BZ^{-2/3} \\sqrt{e})(\\frac{M_\\mu \\delta}{m_e^{2}} + \\sqrt{e})}),\n\\end{equation}\n\nwhere $B = 1429$ for all elements but hydrogen, where $B = 446$\n\nFor our calculations we use differential cross section, as \n\\begin{equation}\n\\frac{\\text{d} \\sigma}{\\text{d} q} = \\frac{\\text{d}\\sigma}{\\text{d}\\nu E}\n\\end{equation}\nThis formula takes the form:\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}q} = \\frac{\\alpha Z}{E}(2\\frac{m_e}{M_\\mu})^{2}(\\frac{4}{3}(\\frac{1}{\\nu} - 1) + \\nu)(\\Phi_\\text{in}(\\delta) + Z\\Phi_n(\\delta) )\n\\end{equation}\nBut, this DCS in $\\frac{m^2}{Gev}$. We need to multiply by Avogadro's number, energy and divide by the mass number of the target atom to get DCS in $\\frac{m^2}{kg}$.\n\nThe final formula:\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}q} = \\frac{\\alpha Z}{E}(2\\frac{m_e}{M_\\mu})^{2}(\\frac{4}{3}(\\frac{1}{\\nu} - 1) + \\nu)(\\Phi_\\text{in}(\\delta) + Z\\Phi_n(\\delta) ) \\frac{N_a E}{A}\n\\end{equation}\n\nAnd take into account, that A in g/mol\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}q} = \\frac{\\alpha Z}{E}(2\\frac{m_e}{M_\\mu})^{2}(\\frac{4}{3}(\\frac{1}{\\nu} - 1) + \\nu)(\\Phi_\\text{in}(\\delta) + Z\\Phi_n(\\delta) ) \\frac{1000 N_a E}{A}\n\\end{equation}\n\nFor `CPU` we have:\n```cpp\ndcs::vmap(dcs::pumas::bremsstrahlung)(\n result, kinetic_energies, recoil_energies, STANDARD_ROCK, MUON_MASS);\n```\nFor `CUDA` we create the lambda function directly ourselves:\n```cpp\ndcs::pumas::cuda::vmap_bremsstrahlung(\n result, kinetic_energies, recoil_energies, STANDARD_ROCK, MUON_MASS);\n```\n\n\n```python\nbrems = muons.bremsstrahlung(kinetic_energies, recoil_energies)\nbrems[:5]\n```\n\n\n\n\n tensor([3.5293e-04, 3.9395e-06, 4.0777e-06, 4.1341e-06, 4.1650e-06],\n dtype=torch.float64)\n\n\n\n\n```python\nbrems_gpu = muons_cuda.bremsstrahlung(kinetic_energies_gpu, recoil_energies_gpu);\nbrems_gpu[:5]\n```\n\n\n\n\n tensor([3.5293e-04, 3.9395e-06, 4.0777e-06, 4.1341e-06, 4.1650e-06],\n device='cuda:0', dtype=torch.float64)\n\n\n\n\n```python\n(brems - brems_gpu.cpu()).abs().sum()\n```\n\n\n\n\n tensor(3.2179e-18, dtype=torch.float64)\n\n\n\n\n```python\n%timeit muons_cuda.bremsstrahlung(kinetic_energies_gpu, recoil_energies_gpu);\n```\n\n 157 µs ± 3.06 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\n\n\n```python\n%timeit muons.bremsstrahlung(kinetic_energies, recoil_energies);\n```\n\n 326 µs ± 3.58 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\n\n### Pair Production\n\nDirect electron pair production is one of the most important muon interaction processes. At TeV muon energies,\nthe pair production cross section exceeds those of other muon interaction processes over a range of energy transfers\nbetween 100 MeV and 0.1𝐸𝜇. The average energy loss for pair production increases linearly with muon energy, and\nin the TeV region this process contributes more than half the total energy loss rate.\n\nTo adequately describe the number of pairs produced, the average energy loss and the stochastic energy loss distribution,\nthe differential cross section behavior over an energy transfer range of 5 MeV ≤ 𝜖 ≤ 0.1 ·𝐸𝜇 must be accurately\nreproduced. This is is because the main contribution to the total cross section is given by transferred energies 5 MeV\n≤ 𝜖 ≤ 0.01 ·𝐸𝜇, and because the contribution to the average muon energy loss is determined mostly in the region\n0.001 · 𝐸𝜇 ≤ 𝜖 ≤ 0.1 ·𝐸𝜇 .\n\n##### Input:\n * Z - The charge number of the target atom.\n * A - The mass number of the target atom.\n * mass - The projectile rest mass, in GeV\n * K - The projectile initial kinetic energy.\n * q - The kinetic energy lost to the photon ($E - E^{\\text{'}}$).\n \n##### Output:\n DCS in m^2/kg.\n \n#### Definitions and Applicability\n\nTheory from https://geant4-userdoc.web.cern.ch/UsersGuides/PhysicsReferenceManual/fo/PhysicsReferenceManual.pdf (Page 151)\n\nCoefficients for the Gaussian quadrature from:\nhttps://pomax.github.io/bezierinfo/legendre-gauss.html.\n\nThe formula for the differential cross section applies when:\n* $E_\\mu \\gg \\mu $ $ ( E \\geq 2 - 5 GeV)$ and $E_\\mu \\leq 10^{15} - 10^{17} eV $. If muon energies exceed this limit, the LPM (Landau Pomeranchuk Migdal) effect may become important, depending on the material.\n*The muon energy transfer $q$ lies between $q_\\text{min} = 4m_e$ and $q_\\text{max} = E_\\mu - \\frac{3\\sqrt{e}}{4} M_\\mu Z^{1/3}$, although the formal lower limit is $q \\gg 2m_e$, and the formal upper limit requires $E_\\mu ^\\text{'} \\gg \\mu$.\n*$Z \\leq 40 - 50$. For higher Z, the Coulomb correction is important but has not been sufficiently studied theoretically.\n\n##### Formulae\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}q}(Z, A, E, q) = \\frac{4}{3\\pi} \\frac{Z(Z + \\xi(Z))}{A} N_A {(\\alpha r_e)}^{2} (\\frac{1 - \\nu}{q}) \\int_{p}[\\Phi_e + (m_e/M_\\mu)^{2}\\Phi_\\mu]dp,\n\\end{equation}\n\nwhere $\\Phi_{e,\\mu} = B_{e,\\mu} {L_{e,\\mu}}^{'}$ and $\\Phi_{e,\\mu} = 0 \\text{ whenever } \\Phi_{e,\\mu}<0$.\n\n$B_e$ and $B_\\mu$ do not depend on Z, A, and are given by\n\n\\begin{equation}\nB_e = [(2 + \\rho^{2})(1 + \\beta) + \\xi(3 + \\rho^{2})]\\ln(1 + \\frac{1}{\\xi}) + \\frac{1 - \\rho^{2} - \\beta}{1 + \\xi} - (3 + \\rho^{2})\n\\approx \\frac{1}{2\\xi}[(3 - \\rho^{2}) + 2\\beta(z + \\rho^{2})] \\text{ for } \\xi \\geq 10 ^{3}\n\\end{equation}\n\n\\begin{equation}\nB_\\mu = [(1 + \\rho^{2})(1 + \\frac{3\\beta}{2}) - \\frac{1}{\\xi}(1 + 2\\beta)(1 - \\rho^{2})]\\ln(1 + \\xi) + \\frac{\\xi(1 - \\rho{2} - \\beta)}{1 + \\xi} + (1 + 2\\beta)(1 - \\rho^{2})\n\\approx \\frac{\\xi}{2}[(5 - \\rho^{2}) + \\beta(3 + \\rho^{2})] \\text{ for } \\xi \\leq 10^{-3}\n\\end{equation}\n\nAlso,\n\n\n\\begin{equation}\n\\xi = \\frac{\\mu^{2}\\nu^{2}}{4m^{2}} \\frac{(1 - \\rho^{2})}{1 - \\nu}; \\text{ }\n\\beta = \\frac{\\nu^{2}}{2(1 - \\nu)}\n\\end{equation}\n\n\\begin{equation}\nL_e^\\text{'} = \\ln(\\frac{A^{*}Z^{-1/3} \\sqrt{(1 + \\xi)(1 + Y_e)}}{1 + \\frac{2m\\sqrt{e}A*Z^{-1/3}(1 + \\xi)(1 + Y_\\mu)}{E\\nu(1 - \\rho^{2})}}) - \\frac{1}{2}ln([1 + (\\frac{3mZ^{1/3}}{2\\mu})^{2}(1 + \\xi)(1 + Y_e)])\n\\end{equation}\n\n\\begin{equation}\nL_\\mu ^\\text{'} = \\ln(\\frac{(\\frac{M_\\mu}{m_e})A^{*}Z^{-1/3} \\sqrt{(1 + \\frac{1}{\\xi})(1 + Y_e)}}{1 + \\frac{2m\\sqrt{e}A*Z^{-1/3}(1 + \\xi)(1 + Y_\\mu)}{E\\nu(1 - \\rho^{2})}}) - ln(\\frac{3}{2} Z^{1/3}\\sqrt{(1 + \\frac{1}{\\xi})(1 + Y_\\mu)})\n\\end{equation}\n\nFor faster computing, the expressions for $L_{e, \\mu} ^\\text{'}$ are further algebraically transformed. The function $L_{e, \\mu} ^\\text{'}$ include the nuclear size correction in comparison with parameterization.\n\n\\begin{equation}\nY_e = \\frac{5 - \\rho^2 + 4\\beta(1 + \\rho^2)}{2(1 + 3\\beta)\\ln(3 + 1/\\xi)) - \\rho^2 - 2\\beta(2 - \\rho^2)}\n\\end{equation}\n\n\\begin{equation}\nY_\\mu = \\frac{4 + \\rho^2 + 3\\beta(1 + \\rho^2)}{(1 + \\rho^2)(\\frac{3}{2} + 2\\beta)\\ln(3 + \\xi) + 1 - \\frac{3}{2}\\rho^2}\n\\end{equation}\n\n\\begin{equation}\n\\rho_{max} = 1 - \\frac{6M_\\mu^2}{E^2(1 - \\nu)})\\sqrt{1 - \\frac{4m_e}{E\\nu}} \n\\end{equation}\n\n```cpp\ndcs::vmap(dcs::pumas::pair_production)(\n result, kinetic_energies, recoil_energies, STANDARD_ROCK, MUON_MASS);\n```\n\n\n```python\nppair = muons.pair_production(kinetic_energies, recoil_energies)\nppair[:5]\n```\n\n\n\n\n tensor([0.0000e+00, 6.5366e-06, 7.3699e-06, 7.7919e-06, 8.0572e-06],\n dtype=torch.float64)\n\n\n\n### Photonuclear\n\nInput:\n * Z - The charge number of the target atom.\n * A - The mass number of the target atom.\n * ml - The projectile rest mass, in GeV\n * K - The projectile initial kinetic energy.\n * q - The kinetic energy lost to the photon. \n\nOutput:\n DCS in m^2/kg.\n \n#### Definitions and Applicability\n\nTheory from: https://arxiv.org/pdf/hep-ph/9712415.pdf, https://arxiv.org/pdf/hep-ph/0012350.pdf\n \nThe inelastic interaction of muons with nuclei is important at high muon energies (𝐸 ≥ 10 GeV), and at relatively high\nenergy transfers 𝜈 (𝜈/𝐸 ≥ 10−2). It is especially important for light materials and for the study of detector response\nto high energy muons, muon propagation and muon-induced hadronic background. The average energy loss for this\nprocess increases almost linearly with energy, and at TeV muon energies constitutes about 10% of the energy loss rate.\n\nThe main contribution to the cross section 𝜎(𝐸, 𝜈) and energy loss comes from the low 𝑄2–region ( 𝑄2 ≪ 1 GeV2).\nIn this domain, many simplifications can be made in the theoretical consideration of the process in order to obtain\nconvenient and simple formulae for the cross section. Most widely used are the expressions given by Borog and\nPetrukhin [BP75], and Bezrukov and Bugaev [BB81]. Results from these authors agree within 10% for the differential\ncross section and within about 5% for the average energy loss, provided the same photonuclear cross section, 𝜎𝛾𝑁, is\nused in the calculations.\n\n##### Formulae\n\nThe differential cross section can be written in the form\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{4\\pi\\alpha^2}{Q^4}\\frac{F_2(x, Q^2)}{x}(1-y-\\frac{Mxy}{2E} + (1 - \\frac{2m_l^2}{Q^2})\\frac{y^2(1 + \\frac{4M^2x^2}{Q^2})}{2(1 + R(x, Q^2))})\n\\end{equation}\n\nWhere $F_2$ - a nucleon structure function\n\n\\begin{equation}\nF_2(x, Q^2) = \\frac{Q^2}{Q^2 + m_0^2} (F_2^P(x, Q^2) + F_2^R(x, Q^2))\n\\end{equation}\n\n\\begin{equation}\nF_2 ^{R}(x, Q^{2}) = c_R(t)x_R^{a_R(t)}(1 - x)^{b_R(t)} \n= c_R(t)e^{a_R(t)\\ln x_R+ b_R(t)\\ln(1 - x)}\n\\end{equation}\n\n\\begin{equation}\nF_2 ^{P}(x, Q^{2}) = c_P(t)x_P^{a_P(t)}(1 - x)^{b_P(t)} \n= c_P(t)e^{\\ln(x_P^{a_P(t)}(1 - x)^{b_P(t)})}\n= c_P(t)e^{\\ln x_P^{a_P(t)}+ \\ln(1 - x)^{b_P(t)}}\n= c_P(t)e^{a_P(t)\\ln x_P+ b_P(t)\\ln(1 - x)}\n\\end{equation}\n\nTake $x$ as $x = \\frac{Q^2}{2Mq}$\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{4\\pi\\alpha^2 F_2}{Q^4} \\frac{2Mq}{Q^2}(1 - y - \\frac{My}{2E}\\frac{Q^2}{2Mq} + (1 - \\frac{2m_l^2}{Q^2})\\frac{y^2(1 + (\\frac{2MQ^2}{2MqQ})^2)}{2(1 + R)})\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{8\\pi\\alpha^2F_2Mq}{Q^6}(1 - y - \\frac{Q^2y}{4Eq} + (1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + (y\\frac{Q}{q})^2}{2(1 + R)})\n\\end{equation}\n\nTake into account, that $y = \\frac{q}{E}$ \n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{8\\pi\\alpha^2F_2Mq}{Q^6}(1 - y - \\frac{Q^2}{4E^2} + (1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + \\frac{Q^2}{E^2}}{2(1 + R)})\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{8\\pi\\alpha^2F_2Mq}{Q^6}(1 - y + (1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + \\frac{Q^2}{E^2}}{2(1 + R)}) - \\frac{8\\pi\\alpha^2F_2Mq}{Q^6}\\frac{Q^2}{4E^2}\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{8\\pi\\alpha^2F_2Mq}{Q^6}(1 - y + (1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + \\frac{Q^2}{E^2}}{2(1 + R)}) - \\frac{8\\pi\\alpha^2F_2Mq}{4Q^4E^2}\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}x} = \\frac{8\\pi\\alpha^2F_2Mq}{Q^2}((\\frac{1 - y + \\frac{1}{2}(1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + \\frac{Q^2}{E^2}}{1 + R}}{Q^4}) - \\frac{1}{4Q^2E^2})\n\\end{equation}\n\nLet's see on $x = \\frac{Q^2}{2Mq}$\n\n\\begin{equation}\n\\frac{\\text{d}x}{\\text{d}q} = \\frac{-Q^2}{2Mq^2}\n\\end{equation}\n\nAnd\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}q}\\frac{2Mq^2}{-Q^2} = \\frac{8\\pi\\alpha^2F_2Mq}{Q^2}((\\frac{1 - y + \\frac{1}{2}(1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + \\frac{Q^2}{E^2}}{1 + R}}{Q^4}) - \\frac{1}{4Q^2E^2})\n\\end{equation}\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}q} = \\frac{-4\\pi\\alpha^2F_2}{q}((\\frac{1 - y + \\frac{1}{2}(1 - \\frac{2m_l^2}{Q^2}) \\frac{y^2 + \\frac{Q^2}{E^2}}{1 + R}}{Q^4}) - \\frac{1}{4Q^2E^2})\n\\end{equation}\n\nSo it's not enough correct equation. We should add some approximation factors. And finally we have:\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}q} = \\frac{\\text{cf} F_2}{q} (\\frac{1-y+\\frac{1}{2}(1 - \\frac{2m_l^2}{Q^2}) \\frac {y^2 + \\frac{Q^2}{E^2}}{1 + R}}{Q^4} - \\frac{1}{4E^2Q^2})\n\\end{equation}\n\nThen integrate this equation using Gaussian Quadrature from $Q_\\text{min}^2 = \\frac{m_l^2y^2}{1 - y} $ to $Q_\\text{max}^2 = 2MEy - ((M + m_\\pi)^2 - M^2) $\n\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}q} = \\int{\\frac{\\text{d}\\sigma(x, Q^2)}{\\text{d}Q^2\\text{d}q}}\\text{d}Q^2\n\\end{equation}\n\n```cpp\ndcs::vmap(dcs::pumas::photonuclear)(\n result, kinetic_energies, recoil_energies, STANDARD_ROCK, MUON_MASS);\n```\n\n\n```python\nphotonuc = muons.photonuclear(kinetic_energies, recoil_energies)\nphotonuc[:5]\n```\n\n\n\n\n tensor([0.0000e+00, 2.2912e-06, 2.1304e-06, 2.0719e-06, 2.0427e-06],\n dtype=torch.float64)\n\n\n\n### Ionisation\n\nInput:\n * A - The charge number of the target atom.\n * I - The mean excitation of the target atom. \n * Z - The mass number of the target atom.\n * mu - The projectile rest mass, in GeV\n * K - The projectile initial kinetic energy.\n * q - The kinetic energy lost to the photon.\n \nOutput:\n DCS in m^2/kg.\n \n### Definitions and Applicability\n\nTheory from: Salvat et al., NIMB316 (2013) 144-159, Sokalski et al., Phys.Rev.D64 (2001) 074015 (MUM)\n\nThe differential cross section for ionisation is computed following Salvat et al., NIMB316 (2013) 144-159, considering only close interactions for DELs. In addition a radiative correction is applied according toSokalski et al., Phys.Rev.D64 (2001) 074015 (MUM).\n\n\\begin{equation}\n\\frac{\\text{d}\\sigma}{\\text{d}q} = \\frac{CEZ}{A(\\frac{1}{2P_2} + \\frac{P_2W_\\text{max}}{E^2W_\\text{max} - qP_2})}(1 + \\Delta_{e\\gamma}),\n\\end{equation}\n\nwhere $P_2 = E^2 - M_\\mu^2$, $W_{max} = \\frac{2m_e P_2}{M_\\mu^2 + m_e(m_e + 2E)}$ and $C = 1.535336*10^{-5}$ \n\n$\\Delta_{e\\gamma}$ - Radiative correction\n\n\\begin{equation}\n\\Delta_{e\\gamma} = \\frac{\\alpha}{2\\pi}\\ln(1 + \\frac{2\\nu E}{m_e})(\\ln(\\frac{4E^2(1 - \\nu)}{M_\\mu^2}) - \\ln(1 + \\frac{2\\nu E}{m_e}))\n\\end{equation}\n\nIf we take into account, that $\\nu = \\frac{q}{E}$\n\n\\begin{equation}\n\\Delta_{e\\gamma} = \\frac{\\alpha}{2\\pi}\\ln(1 + \\frac{2q}{m_e})(\\ln(\\frac{4E(E - q)}{M_\\mu^2}) - \\ln(1 + \\frac{2q}{m_e}))\n\\end{equation}\n\n```cpp\ndcs::vmap(dcs::pumas::ionisation)(\n result, kinetic_energies, recoil_energies, STANDARD_ROCK, MUON_MASS);\n```\n\n\n```python\nionis = muons.ionisation(kinetic_energies, recoil_energies)\nionis[:5]\n```\n\n\n\n\n tensor([0.0000e+00, 3.0168e-05, 1.5300e-05, 1.0284e-05, 7.7575e-06],\n dtype=torch.float64)\n\n\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsample = 1000 #amount of points\n\nrecoil_energies = np.zeros(sample)\n\nE = np.linspace(0.00001, 10000, 10 ) #array with different energy levels\n\nfor j in range(10):\n\n kinetic_energies_np = np.full(sample, E[j]) #numpy array with one energy level\n kinetic_energies_torch = torch.Tensor(kinetic_energies_np).double() \n\n for i in range(sample):\n recoil_energies[i] = E[j]*(0.05 + i*(1 - 0.05)/sample)\n\n recoil_energies_torch = torch.Tensor(recoil_energies).double() \n\n brems = muons.bremsstrahlung(kinetic_energies_torch, recoil_energies_torch)\n ppair = muons.pair_production(kinetic_energies_torch, recoil_energies_torch)\n photonuc = muons.photonuclear(kinetic_energies_torch, recoil_energies_torch)\n ionis = muons.ionisation(kinetic_energies_torch, recoil_energies_torch)\n\n print(\"Energy level: \", E[j])\n\n fig, ax = plt.subplots()\n ax.plot(recoil_energies, brems.numpy(), label = 'bremsstrahlung')\n ax.plot(recoil_energies, ppair.numpy(), label = 'pair production')\n ax.plot(recoil_energies, photonuc, label = 'photonuclear') \n ax.plot(recoil_energies, ionis.numpy(), label = 'ionisation') \n\n ax.set_xlabel('The kinetic energy lost to the photon, GeV', fontsize = 20)\n ax.set_ylabel('DCS, m^2/kg', fontsize = 20)\n ax.set_title(\"Energy loss\")\n\n fig.set_figwidth(20)\n fig.set_figheight(10)\n\n ax.legend()\n\n```\n", "meta": {"hexsha": "7067012ce15d31e3d45be25a3c7066084b567206", "size": 598020, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/pms/muography.ipynb", "max_stars_repo_name": "DanilaSR/noa", "max_stars_repo_head_hexsha": "f880ad8245fbedcc7f564e6ab7937d28f1e14dae", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/pms/muography.ipynb", "max_issues_repo_name": "DanilaSR/noa", "max_issues_repo_head_hexsha": "f880ad8245fbedcc7f564e6ab7937d28f1e14dae", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/pms/muography.ipynb", "max_forks_repo_name": "DanilaSR/noa", "max_forks_repo_head_hexsha": "f880ad8245fbedcc7f564e6ab7937d28f1e14dae", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 363.0965391621, "max_line_length": 53306, "alphanum_fraction": 0.906041604, "converted": true, "num_tokens": 21936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.32146745036587054}} {"text": "# Create a decay dataset suitable for radioactivedecay from PyNE\nThis notebook creates a set of decay dataset files suitable for radioactivedecay `v0.4.5+` from the decay data in PyNE `v0.7.6`. The PyNE data is based on the [191004 ENDSF](https://github.com/pyne/pyne/pull/1216) release.\n\nFirst import the necessary modules.\n\n\n```python\nimport math, pickle\n\nfrom pyne import nucname, data\nfrom pyne.material import Material\nimport pyne\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import sparse\nfrom sympy import Integer, S, log, Matrix\nfrom sympy.matrices import SparseMatrix\n\nprint(\"Using PyNE version:\", pyne.__version__)\n```\n\n Using PyNE version: 0.7.6\n\n\n### Create a DataFrame containing the PyNE decay data\nCreate a list of all the ground state (non-metastable) radionuclides in PyNE. Note we exclude the metastable states as the PyNE treatment for decay chains passing through metastable states is [incorrect](https://github.com/pyne/pyne/issues/739) as of `v0.7.6`. We also exclude radionuclides with undefined half-lives.\n\n\n```python\npyne_nonmetastable_ids = []\nfor z in range(1,120):\n for a in range(1,300):\n try:\n id = z*10000000+a*10000\n hl = data.half_life(id)\n except:\n continue\n if hl == float(\"inf\"): continue # ignore stable nuclides\n elif math.isnan(hl): continue # ignore nuclides where the half-life is undefined half-lives\n pyne_nonmetastable_ids.append(id)\nprint(\"Total number of radionuclides:\", len(pyne_nonmetastable_ids))\n```\n\n Total number of radionuclides: 2920\n\n\nDefine functions to fill a Pandas DataFrame with the decay data from PyNE.\n\n\n```python\ndef add_hyphen(name):\n \"\"\"Add hypen to radionuclide name string e.g. H3 to H-3.\"\"\"\n\n for i in range(1, len(name)):\n if not name[i].isdigit():\n continue\n name = name[:i] + \"-\" + name[i:]\n break\n return name\n\ndef create_rows(ids):\n \"\"\"Create a list of dictionaries which will become rows of the DataFrame of decay data.\"\"\"\n\n rows = []\n for id in ids:\n name = add_hyphen(nucname.name(id))\n Z, A = nucname.znum(id), nucname.anum(id)\n hl = data.half_life(id)\n children = list(data.decay_children(id))\n bf = []\n modes = []\n atomic_mass = data.atomic_mass(id)\n for c in children:\n bf.append(data.branch_ratio(id, c))\n cZ, cA = nucname.znum(c), nucname.anum(c)\n if Z == cZ and A == cA: modes.append(\"IT\")\n elif Z-2 == cZ and A-4 == cA: modes.append(\"α\")\n elif Z+1 == cZ and A == cA: modes.append(\"β-\")\n elif Z-1 == cZ and A == cA: modes.append(\"β+ or EC\")\n else: modes.append(\"SF or other\")\n rows.append({\"Radionuclide\": name, \"id\": id, \"Z\": Z, \"A\": A, \"Half-life_s\": hl,\n \"Num_decay_modes\": len(children), \"Progeny\": children, \"Branching_fractions\": bf,\n \"Modes\": modes, \"Atomic_mass\": atomic_mass})\n return rows\n```\n\nAdd all the PyNE decay data to a DataFrame.\n\n\n```python\ncol_names = [\"Radionuclide\", \"id\", \"Z\", \"A\", \"Half-life_s\", \"Num_decay_modes\", \n \"Progeny\", \"Branching_fractions\", \"Modes\", \"Atomic_mass\"]\npyne_full = pd.DataFrame(create_rows(pyne_nonmetastable_ids), columns=col_names)\npyne_full.set_index(\"Radionuclide\", inplace=True)\npyne_full.to_csv(\"pyne_full.csv\", index=True)\npyne_full.head(n=10)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
idZAHalf-life_sNum_decay_modesProgenyBranching_fractionsModesAtomic_mass
Radionuclide
H-310030000133.887896e+081[20030000][1.0][β-]3.016049
H-610060000162.016584e-231[10050000][1.0][SF or other]6.044955
He-520050000258.167164e-240[][][]5.012057
He-620060000268.067000e-011[30060000][1.0][β-]6.018886
He-720070000271.890547e-180[][][]7.027991
He-820080000281.191000e-012[30070000, 30080000][0.16, 0.84][SF or other, β-]8.033934
He-10201000002103.781095e-181[20090000][1.0][SF or other]10.052815
Li-530050000351.550249e-230[][][]5.012538
Li-830080000388.399000e-011[40080000][1.0][β-]8.022486
Li-930090000391.783000e-012[40080000, 40090000][0.5080000000000001, 0.4919999999999999][SF or other, β-]9.026790
\n
\n\n\n\n### Order the DataFrame so all progeny are located below their parent\nThe radionuclides in the DataFrame need to be ordered so that progeny (decay children) are always located lower than their parent. This is so the subsequent matrices that we create are lower triangular.\n\nTo achieve this we first count how many times each radioactive decay mode occurs in the dataset.\n\n\n```python\nmodes = pd.Series(np.concatenate(pyne_full.Modes))\nprint(\"β+ or electron capture:\", modes.value_counts()[\"β+ or EC\"])\nprint(\"β-:\", modes.value_counts()[\"β-\"])\nprint(\"α:\", modes.value_counts()[\"α\"])\nprint(\"Spontaneous Fission or other:\", modes.value_counts()[\"SF or other\"])\nprint(\"Total number of decay modes:\", pyne_full.Num_decay_modes.sum())\n```\n\n β+ or electron capture: 1143\n β-: 1133\n α: 580\n Spontaneous Fission or other: 1257\n Total number of decay modes: 4113\n\n\nWe order by decreasing mass number (A), followed by decreasing atomic number (Z), as there are more β+ and EC decays than β- decays.\n\n\n```python\npyne_full.sort_values(by=[\"A\", \"Z\"], inplace=True, ascending=[False, False])\npyne_full.head(n=10)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
idZAHalf-life_sNum_decay_modesProgenyBranching_fractionsModesAtomic_mass
Radionuclide
Fl-28511428500001142850.15001[1122810000][1.0][α]285.183579
Cn-285112285000011228534.00001[1102810000][1.0][α]285.177321
Fl-28411428400001142840.00250[][][]284.181344
Cn-28411228400001122840.10100[][][]284.174499
Cn-28311228300001122834.00000[][][]283.173362
Cn-28211228200001122820.00050[][][]282.170668
Rg-28211128200001112820.50001[1092780000][1.0][α]282.169405
Cn-28111228100001122810.13001[1102770000][1.0][α]281.169641
Rg-281111281000011128126.00000[][][]281.166718
Ds-28111028100001102819.60000[][][]281.164715
\n
\n\n\n\nNow it is necessary to correct the positions of the remaining radionuclides that are not ordered correctly. We do this by looping over all the radionuclides in the DataFrame, and checking if their progeny are located below. If not, the positions of the parent and progeny rows in the DataFrame are switched. This process takes a few passes until all the parents and progeny are correctly ordered.\n\n\n```python\nnuclide_list = list(pyne_full.index)\nid_list = list(pyne_full.id)\nswapping = 1\nwhile swapping >= 1:\n swaps = 0\n for parent in nuclide_list:\n for c, mode, bf in zip(pyne_full.at[parent, \"Progeny\"],\n pyne_full.at[parent, \"Modes\"], \n pyne_full.at[parent, \"Branching_fractions\"]):\n if data.decay_const(c) == 0.0 or c not in id_list:\n continue\n j = nuclide_list.index(parent)\n k = id_list.index(c)\n if j > k:\n nuclide_list[j], nuclide_list[k] = nuclide_list[k], nuclide_list[j]\n id_list[j], id_list[k] = id_list[k], id_list[j]\n pyne_full = pyne_full.reindex(index=nuclide_list)\n swaps +=1\n print(\"Iteration\", swapping, \"number of swaps:\", swaps)\n swapping += 1\n if swaps == 0: swapping = 0\npyne_full.head(n=10)\n```\n\n Iteration 1 number of swaps: 901\n Iteration 2 number of swaps: 632\n Iteration 3 number of swaps: 425\n Iteration 4 number of swaps: 262\n Iteration 5 number of swaps: 135\n Iteration 6 number of swaps: 53\n Iteration 7 number of swaps: 16\n Iteration 8 number of swaps: 1\n Iteration 9 number of swaps: 0\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
idZAHalf-life_sNum_decay_modesProgenyBranching_fractionsModesAtomic_mass
Radionuclide
Fl-28511428500001142850.15001[1122810000][1.0][α]285.183579
Cn-285112285000011228534.00001[1102810000][1.0][α]285.177321
Fl-28411428400001142840.00250[][][]284.181344
Cn-28411228400001122840.10100[][][]284.174499
Cn-28311228300001122834.00000[][][]283.173362
Cn-28211228200001122820.00050[][][]282.170668
Rg-28211128200001112820.50001[1092780000][1.0][α]282.169405
Cn-28111228100001122810.13001[1102770000][1.0][α]281.169641
Rg-281111281000011128126.00000[][][]281.166718
Ds-28111028100001102819.60000[][][]281.164715
\n
\n\n\n\n### Now make the dataset files for radioactivedecay\nThe process of making datasets for radioactivedecay is as follows. We first make the sparse lower triangular matrix *Λ*, which captures the decay relationships and branching fractions between parents and their immediate (first) progeny. We then make the sparse matrix _C_, which is used in decay calculations, and from this make its inverse *C-1*.\n\nFirst we define some functions used for making *Λ*, _C_ and *C-1*.\n\n\n```python\ndef make_lambda_mat(df):\n \"\"\"Make the lambda matrix and a list of the decay constants.\"\"\"\n\n rows = np.array([], dtype=np.int64)\n cols = np.array([], dtype=np.int64)\n values = np.array([], dtype=np.float64)\n lambdas = []\n ln2 = np.log(2)\n\n nuclide_list = list(df.index)\n id_list = list(df.id)\n\n for parent in nuclide_list:\n j = nuclide_list.index(parent)\n rows = np.append(rows, [j])\n cols = np.append(cols, [j])\n lambd = ln2/df.at[parent, \"Half-life_s\"]\n values = np.append(values, -lambd)\n lambdas = np.append(lambdas, lambd)\n for progeny, bf in zip(df.at[parent, \"Progeny\"], df.at[parent, \"Branching_fractions\"]):\n if (progeny not in id_list): continue\n i = id_list.index(progeny)\n rows = np.append(rows, [i])\n cols = np.append(cols, [j])\n values = np.append(values, [lambd*bf])\n\n return sparse.csc_matrix((values, (rows, cols))), lambdas\n\ndef prepare_C_inv_C(df):\n \"\"\"Prepare data structures needed to make C and inv_C.\"\"\"\n\n nuclide_list = list(df.index)\n num_nuclides = len(nuclide_list)\n\n rows_dict = {}\n for i in range(num_nuclides-1, -1, -1):\n a,_ = lambda_mat[:,i].nonzero()\n b = a\n for j in a: \n if j > i: \n b = np.unique(np.concatenate((b,rows_dict[j])))\n rows_dict[i] = b\n\n rows_C = np.array([], dtype=np.int64)\n cols_C = np.array([], dtype=np.int64)\n for i in range(0, num_nuclides):\n rows_C = np.concatenate((rows_C,rows_dict[i]))\n cols_C = np.concatenate((cols_C,np.array([i]*len(rows_dict[i]))))\n\n C = sparse.csc_matrix((np.array([0.0]*rows_C.size, dtype=np.float64), (rows_C, cols_C)))\n inv_C = sparse.csc_matrix((np.array([0.0]*rows_C.size, dtype=np.float64), (rows_C, cols_C)))\n \n return rows_dict, rows_C, cols_C, C, inv_C\n\ndef make_C(rows_dict, rows_C, cols_C, C, lambda_mat, df):\n \"\"\"Calculate C. Report cases of radionuclides with identical or similar half-lives in the same decay chain.\"\"\"\n\n nuclide_list = list(df.index)\n for index in range(0, rows_C.size):\n i = rows_C[index]\n j = cols_C[index]\n if i == j: C[i,i] = 1.0\n else:\n sigma = 0.0\n for k in rows_dict[j]:\n if k == i: break\n sigma += lambda_mat[i,k]*C[k,j]\n if lambda_mat[j,j]==lambda_mat[i,i]: \n print(\"equal decay constants:\", nuclide_list[i], nuclide_list[j])\n C[i,j] = sigma/(lambda_mat[j,j]-lambda_mat[i,i])\n if abs((lambda_mat[j,j]-lambda_mat[i,i])/lambda_mat[j,j]) < 1E-4: \n print(\"rel_diff of decay constants < 1E-4:\", nuclide_list[i], nuclide_list[j])\n return C\n\ndef make_inv_C(rows_dict, rows_C, cols_C, C, inv_C):\n \"\"\"Calculate inv_C.\"\"\"\n\n for index in range(0, rows_C.size):\n i = rows_C[index]\n j = cols_C[index]\n if i == j: inv_C[i,i] = 1.0\n else:\n sigma = 0.0\n for k in rows_dict[j]:\n if k == i: break\n sigma -= C[i,k]*inv_C[k,j]\n inv_C[i,j] = sigma \n return inv_C\n```\n\nThe process of making _Λ_, _C_ and *C-1* is complicated as PyNE includes some decay chains where two radionuclides have identical half-lives. PyNE has [special routines](https://pyne.io/theorymanual/decay.html) to cope with this, but radioactivedecay currently does not. Fortunately these cases are limited to some fairly obscure radionuclides which are unlikely to be relevant to most users.\n\nThe following is a first pass through at making *Λ* and *C*. It highlights the cases where radionuclides in the same chain have identical half-lives, and also cases where radionuclides in the same chain have similar half-lives (relative difference < 1E-4).\n\n\n```python\nlambda_mat, lambdas = make_lambda_mat(pyne_full)\nrows_dict, rows_C, cols_C, C, inv_C = prepare_C_inv_C(pyne_full)\nC = make_C(rows_dict, rows_C, cols_C, C, lambda_mat, pyne_full)\n```\n\n equal decay constants: Os-179 Pt-183\n rel_diff of decay constants < 1E-4: Os-179 Pt-183\n\n\n :70: RuntimeWarning: divide by zero encountered in double_scalars\n C[i,j] = sigma/(lambda_mat[j,j]-lambda_mat[i,i])\n :67: RuntimeWarning: invalid value encountered in double_scalars\n sigma += lambda_mat[i,k]*C[k,j]\n\n\n equal decay constants: Re-168 Ir-172\n rel_diff of decay constants < 1E-4: Re-168 Ir-172\n equal decay constants: Tm-149 Lu-153\n rel_diff of decay constants < 1E-4: Tm-149 Lu-153\n\n\nSo there are radionuclides with identical half-lives in the chains containing 183Pt, 172Ir and 153Lu. These cases withstanding, there are no other chains containing radionuclides with decay constants with a relative difference of less than 1E-4.\n\nIt turns out that there is a [bug](https://github.com/pyne/pyne/issues/1342) in PyNE `v0.7.6` causing it to incorrectly calculate decayed activities for the chains containing 183Pt, 172Ir and 153Lu. The bug affects all radionuclides in the chains upwards from these three radionuclides. Because of this bug and the fact that radioactivedecay does not support chains with radionuclides with equal half-lives, we remove the affected radionuclides from the decay dataset. Note even by doing this, decay calculation results are unaffected for chains starting with radionuclides below 183Pt, 172Ir and 153Lu.\n\nThis function finds the radionuclides to remove.\n\n\n```python\ndef find_affected_radionuclides(nuclide_list, lambda_mat, nuclide):\n \"\"\"Find radionuclides higher in decay chain than nuclide.\"\"\"\n\n s1 = {nuclide_list.index(nuclide)}\n index = 0\n while index < len(nuclide_list):\n s2 = set(lambda_mat.getcol(index).indices)\n if len(s1.intersection(s2)) > 0:\n s2 = set([s for s in list(s2) if s <= index])\n if s2.issubset(s1):\n index += 1\n continue\n s1 = s2.union(s1)\n index = 0\n continue\n index +=1\n return [nuclide_list[nuclide] for nuclide in s1]\n\nnuclide_list = list(pyne_full.index)\naffected = find_affected_radionuclides(nuclide_list, lambda_mat, \"Pt-183\")\nprint(\"Radionuclides affected for Pt-183:\", affected)\nremove = affected\n\naffected = find_affected_radionuclides(nuclide_list, lambda_mat, \"Ir-172\")\nprint(\"Radionuclides affected for Ir-172:\", affected)\nremove.extend(affected)\n\naffected = find_affected_radionuclides(nuclide_list, lambda_mat, \"Lu-153\")\nprint(\"Radionuclides affected for Lu-153:\", affected)\nremove.extend(affected)\n```\n\n Radionuclides affected for Pt-183: ['Po-191', 'Pt-183', 'Bi-191', 'Pb-187', 'Tl-187', 'Rn-195', 'At-195', 'Hg-183', 'Au-183']\n Radionuclides affected for Ir-172: ['Pb-180', 'Hg-176', 'Tl-177', 'Pt-172', 'Ir-172']\n Radionuclides affected for Lu-153: ['Lu-153', 'Ta-157']\n\n\nIn total there are 16 radionuclides to be removed from the decay dataset.\n\n\n```python\npyne_truncated = pyne_full.copy()\npyne_truncated = pyne_truncated.drop(labels=remove)\npyne_truncated.to_csv(\"pyne_truncated.csv\", index=True)\n```\n\nNow this is done, we can make the matrices _C_ and *C-1* used by radioactivedecay.\n\n\n```python\nlambda_mat, lambdas = make_lambda_mat(pyne_truncated)\nrows_dict, rows_C, cols_C, C, inv_C = prepare_C_inv_C(pyne_truncated)\nC = make_C(rows_dict, rows_C, cols_C, C, lambda_mat, pyne_truncated)\ninv_C = make_inv_C(rows_dict, rows_C, cols_C, C, inv_C)\n```\n\n### Calculate SymPy versions of the matrices for arbitrary-precision calculations\n\nWe now calculate SymPy versions of _C_ and *C-1* for arbitrary-precision calculations. First define some functions for processing the data into SymPy objects:\n\n\n\n```python\nyear_sympy = S(36525)/10000\n\ndef to_rational(number):\n \"\"\"\n Converts half-life string to SymPy object.\n \"\"\"\n\n if number == '0.0':\n return S(0)\n\n if 'e' in number or 'E' in number:\n if 'e' in number:\n end = number.split('e')[1]\n number = number.split('e')[0]\n else:\n end = number.split('E')[1]\n number = number.split('E')[0]\n parts = number.split('.')\n if len(parts) == 1: parts.append('')\n if end[0] == '+':\n multiply = 1\n factor = S(10**int(end.lstrip('+')))\n else:\n multiply = 0\n factor = S(10**int(end.lstrip('-')))\n denom = S(10**len(parts[1]))\n parts[0] = parts[0].lstrip('0')\n if len(parts[0]) == 0: parts[1] = parts[1].lstrip('0')\n if multiply == 1:\n return S(parts[0]+parts[1])*factor/denom\n else: return S(parts[0]+parts[1])/(denom*factor)\n parts = number.split('.')\n if len(parts) == 1: parts.append('')\n denom = S(10**len(parts[1]))\n parts[0] = parts[0].lstrip('0')\n if len(parts[0]) == 0: parts[1] = parts[1].lstrip('0')\n return S(parts[0]+parts[1])/denom\n```\n\nNow make a SymPy version of the *Λ* matrix:\n\n\n```python\nnum_nuclides = len(pyne_truncated)\nlambda_mat_sympy = SparseMatrix.zeros(num_nuclides, num_nuclides)\nlambdas_sympy = Matrix.zeros(num_nuclides, 1)\nnuclide_list = list(pyne_truncated.index)\nid_list = list(pyne_truncated.id)\nmasses_sympy = Matrix.zeros(num_nuclides, 1)\n\nfor parent in nuclide_list:\n j = nuclide_list.index(parent)\n hl_sympy = to_rational(str(pyne_truncated.at[parent, \"Half-life_s\"]))\n lambd = log(2)/hl_sympy\n lambda_mat_sympy[j, j] = -lambd\n lambdas_sympy[j] = lambd\n for progeny, bf in zip(pyne_truncated.at[parent, \"Progeny\"], pyne_truncated.at[parent, \"Branching_fractions\"]):\n if (progeny not in id_list): continue\n i = id_list.index(progeny)\n lambda_mat_sympy[i, j] = lambd*to_rational(str(bf))\n masses_sympy[j] = to_rational(str(pyne_truncated.at[parent, \"Atomic_mass\"]))\n```\n\nNow make a SymPy version of the _C_ and *C-1* matrix:\n\n\n```python\nc_sympy = SparseMatrix.zeros(num_nuclides, num_nuclides)\nc_inv_sympy = SparseMatrix.zeros(num_nuclides, num_nuclides)\n\nfor index in range(0, rows_C.size):\n i = rows_C[index]\n j = cols_C[index]\n if i == j: c_sympy[i, i] = Integer(1)\n else:\n sigma = Integer(0)\n for k in rows_dict[j]:\n if k == i: break\n sigma += lambda_mat_sympy[i, k]*c_sympy[k, j]\n c_sympy[i, j] = sigma/(lambda_mat_sympy[j, j]-lambda_mat_sympy[i, i])\n\nfor index in range(0, rows_C.size):\n i = rows_C[index]\n j = cols_C[index]\n if i == j: c_inv_sympy[i, i] = Integer(1)\n else:\n sigma = Integer(0)\n for k in rows_dict[j]:\n if k == i: break\n sigma -= c_sympy[i, k]*c_inv_sympy[k, j]\n c_inv_sympy[i, j] = sigma\n```\n\n### Save the outputs\n\nWrite output files containing _C_ and *C-1* in SciPy and SymPy sparse format, and other files needed to create a dataset suitable for radioactive decay `v0.4.0+`.\n\n\n\n```python\nhldata = np.array([(np.float64(hl), 's', str(hl) + ' s') for hl in pyne_truncated[\"Half-life_s\"]], dtype=object)\n\nprog_bfs_modes = np.array([{}]*len(pyne_truncated.index))\ni = 0\nfor parent in list(pyne_truncated.index):\n progeny = [add_hyphen(nucname.name(id)) for id in pyne_truncated.at[parent, \"Progeny\"]]\n bfs = dict(zip(progeny, pyne_truncated.at[parent, \"Branching_fractions\"]))\n modes = dict(zip(progeny, pyne_truncated.at[parent, \"Modes\"]))\n bfs = {key: value for key, value in sorted(bfs.items(), key=lambda x: x[1], reverse=True)}\n prog_bfs_modes[i] = {progeny: [bf, modes[progeny]] for progeny, bf in bfs.items()}\n i += 1\n\nnp.savez_compressed(\"./decay_data.npz\", radionuclides=np.array(nuclide_list),\n masses=np.array(list(pyne_truncated[\"Atomic_mass\"])),\n hldata=hldata, prog_bfs_modes=prog_bfs_modes,\n year_conv=365.25)\n\n# Write out SciPy sparse matrices (convert to CSR format)\nsparse.save_npz(\"./c_scipy.npz\", C.tocsr())\nsparse.save_npz(\"./c_inv_scipy.npz\", inv_C.tocsr())\n\nimport pkg_resources, sympy\nif pkg_resources.parse_version(sympy.__version__) >= pkg_resources.parse_version('1.9'):\n pickle_type = '1.9'\nelse:\n pickle_type = '1.8'\n\n# Write out SymPy objects to pickle files\nwith open(f\"c_sympy_{pickle_type}.pickle\", \"wb\") as outfile:\n outfile.write(pickle.dumps(c_sympy))\nwith open(f\"c_inv_sympy_{pickle_type}.pickle\", \"wb\") as outfile:\n outfile.write(pickle.dumps(c_inv_sympy))\nwith open(f\"atomic_masses_sympy_{pickle_type}.pickle\", \"wb\") as outfile:\n outfile.write(pickle.dumps(masses_sympy))\nwith open(f\"decay_consts_sympy_{pickle_type}.pickle\", \"wb\") as outfile:\n outfile.write(pickle.dumps(lambdas_sympy))\nwith open(f\"year_conversion_sympy_{pickle_type}.pickle\", \"wb\") as outfile:\n outfile.write(pickle.dumps(year_sympy))\n```\n", "meta": {"hexsha": "0a0b313f760827703ebc7dfd0c21dec25ab08180", "size": 49726, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pyne/pyne_dataset.ipynb", "max_stars_repo_name": "radioactivedecay/datasets", "max_stars_repo_head_hexsha": "ab4d124c2498e957fe6ab0c162961e11f669877a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pyne/pyne_dataset.ipynb", "max_issues_repo_name": "radioactivedecay/datasets", "max_issues_repo_head_hexsha": "ab4d124c2498e957fe6ab0c162961e11f669877a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pyne/pyne_dataset.ipynb", "max_forks_repo_name": "radioactivedecay/datasets", "max_forks_repo_head_hexsha": "ab4d124c2498e957fe6ab0c162961e11f669877a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-09T21:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T21:10:08.000Z", "avg_line_length": 37.4724943482, "max_line_length": 678, "alphanum_fraction": 0.4285685557, "converted": true, "num_tokens": 9443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.3213686919218509}} {"text": "```python\n#@markdown Configuración Inicial\nfrom IPython.utils import io\n\nfrom google.colab.data_table import DataTable\nfrom IPython.display import Javascript\nfrom IPython.display import display, Markdown, Latex\nfrom IPython.display import Audio, Image\nfrom IPython.display import IFrame, HTML\nwith io.capture_output() as capt:\n !pip install gradio\n\nimport gradio as gr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\n\ndef dLatex(self):\n return display(Latex(self))\n\ndef dMarkdown(self):\n return display(Markdown(self))\n\n# Avoids scroll-in-the-scroll in the entire Notebook\n# https://stackoverflow.com/a/66891328\ndef resize_colab_cell():\n display(Javascript(\n 'google.colab.output.setIframeHeight(0, true, {maxHeight: 5000})'\n ))\nget_ipython().events.register('pre_run_cell', resize_colab_cell)\n\ndef dLatex(self):\n return display(Latex(self))\n\ndef dMarkdown(self):\n return display(Markdown(self))\n```\n\n# Deriva Instrumental\n\nDeriva *(drift)*: cambios con el tiempo en la lectura de los gravímetros en una estación\n\n**Causas:**\n* Constante elástica del resorte (resortes y fibras de torsión no son perfectamente elásticos)\n* Temperatura\n* Mareas terrestres\n\nAl repetir una medición en el mismo lugar y bajo las mismas circunstancias, no se obtiene el mismo valor (variaciones de aprox. $0.001\\,\\mathrm{mGal}$)\n\n**¿De qué depende la deriva?**\n* Tipo de instrumento (varía de un instrumento a otro)\n* Características del resorte\n* Edad y uso del gravímetro\n* Fluctuaciones de temperatura externa\n* Tipo de transporte\n* Cambios de presión\n* Cambios de voltaje en la batería\n* Valores de deriva suelen ser menores a $1\\,\\mathrm{mGal}$\n\n\n**Deriva según el gravímetro:**\n\n* Gravímetros LC&R:\n * Instrumentos nuevos en promedio menor a $1\\,\\mathrm{mGal/mes}$\n * en un equipo con algunos años de uso, deriva menor a $0.5\\,\\mathrm{mGal/mes}$ (Manual LC&R)\n* Gravímetros Scintrex: Modelo CG5, deriva residual menor a $20\\,\\mu\\mathrm{Gal/dia}$\n * El instrumento realiza correcciones automáticas\n* Gravímetros Burries deriva menor a $0.3\\,\\mathrm{mGal/mes}$ (Jentzsch et al., 2017)\n\n**¿Cómo se corrige la deriva?**\n* Realizar mediciones en la estación base con diferencia\nde una o dos horas\n* Graficar las lecturas en función del tiempo\n* Por ello, primera y última medición del día se realizan\nen la estación base\n\n\n\n\\begin{align}\nd\n&=\n\\frac{L_{f}-L_{i}}{t_{f}-t_{i}}\n\\\\\n{L^{c}}_{j}\n&=\nL_{j}-d\\left(t_{j}-t_{A i}\\right)\n\\end{align}\n\n\n```python\n#@markdown Tabla\npd.options.display.float_format = '{:.2f}'.format\ndf0 = pd.DataFrame(columns=[\"ESTACIÓN\", \"Hora\", \"Lectura\"],\n data=[[ 1, \"08:00\", 520],\n [ 2, \"08:30\", 490],\n [ 3, \"09:05\", 450],\n [ 4, \"09:40\", 420],\n [ 1, \"10:10\", 522],\n [ 5, \"10:45\", 470],\n [ 6, \"11:20\", 510],\n [ 7, \"11:55\", 580],\n [ 4, \"12:40\", 424],\n [ 8, \"13:40\", 570],\n [ 9, \"14:15\", 650],\n [10, \"14:50\", 510],\n [ 7, \"15:15\", 575]]\n )\n\n@np.vectorize\ndef hour2min(hour):\n h, m = hour.split(':')\n return 60*int(h)+int(m)\n\ndf = df0.copy()\ndf['Minutos'] = hour2min(df0['Hora'])\ndf['Minutos'] = df['Minutos']-min(df['Minutos'])\ndf = df[['ESTACIÓN', 'Minutos', 'Lectura']]\n\ndisplay(df0.set_index(\"ESTACIÓN\").T)\n```\n\n\n \n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ESTACIÓN12341567489107
Hora08:0008:3009:0509:4010:1010:4511:2011:5512:4013:4014:1514:5015:15
Lectura520490450420522470510580424570650510575
\n
\n\n\n\n```python\nk = 0.728 #@param {type:\"slider\", min:0.5, max:1, step:0.001}\ng_0 = 951253 #@param {type:\"slider\", min:9e5, max:10e5, step:1}\n```\n\n\n \n\n\n\n```python\nk = 0.882\ng_0 = 979166.3\n```\n\n\n \n\n\n\n```python\ndef find_loop(df, base, drop_index=None):\n dfd = df.loc[df['ESTACIÓN'] == base]\n min, max = tuple(dfd.index)[:2]\n if drop_index==None:\n return df.loc[min:max]\n else:\n return df.loc[min:max].drop(drop_index)\n\ndef rev_loop(dfv, g):\n ind = dfv.index\n delta_l, delta_m = tuple(dfv[['Lectura','Minutos']].\\\n iloc[[0,-1]].diff().iloc[-1])\n d = delta_l/delta_m\n dfv['Lectura_rev'] = [dfv['Lectura'][i] - \n d * (dfv['Minutos'][i] -\n dfv['Minutos'][min(ind)])\n for i in ind]\n dfv['delta_g'] = k * dfv['Lectura_rev'].diff().fillna(0)\n dfv['g'] = g + dfv['delta_g'].cumsum()\n return d, dfv\n\n\ndf_dup = df.loc[df['ESTACIÓN'].duplicated()]\n\nbases = df_dup['ESTACIÓN'].to_list()\ndup_index = [None] + df_dup.index.to_list()[:-1]\n\nprint(' bases:', bases)\nprint('dup_index:', dup_index)\n\ndfs = [find_loop(df, base, dup) for base, dup in zip(bases, dup_index)]\nfor dfi in dfs:\n display(dfi)\n\nfig, ax = plt.subplots()\nfor l, dfi in enumerate(dfs):\n dfi.plot(\n x='Minutos',\n y='ESTACIÓN',\n style='o-',\n alpha=.75,\n label=f'Loop {l:d}',\n zorder=len(dfs)-l,\n ax=ax)\nax.set_yticks(range(1+max(df['ESTACIÓN'])))\nax.grid(axis='y')\nplt.show()\n```\n\n\n```python\ndf_0 = dfs[0].copy()\nd_1, df_1 = rev_loop(df_0, g_0)\ndMarkdown(f'$d_0={d_1:g}$')\ndisplay(df_0)\n```\n\n\n \n\n\n\n$d_0=0.0153846$\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ESTACIÓNMinutosLecturaLectura_revdelta_gg
010520520.000.00979166.30
1230490489.54-26.87979139.43
2365450449.00-35.75979103.68
34100420418.46-26.93979076.74
41130522520.0089.56979166.30
\n
\n\n\n\n```python\nlrev_1, g_1 = df_0[['Lectura_rev', 'g']].iloc[-2]\nprint(lrev_1, g_1, sep='\\n')\n\ndf_1 = dfs[1].copy()\ndf_1.loc[min(df_1.index), 'Lectura'] = lrev_1\n\nd_1, df_1 = rev_loop(df_1, g_1)\ndMarkdown(f'$d_1={d_1:g}$')\ndisplay(df_1)\n```\n\n\n \n\n\n 418.46153846153845\n 979076.7430769231\n\n\n\n$d_1=0.0307692$\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ESTACIÓNMinutosLecturaLectura_revdelta_gg
34100418.46418.460.00979076.74
55165470.00468.0043.69979120.44
66200510.00506.9234.33979154.77
77235580.00575.8560.79979215.56
84280424.00418.46-138.81979076.74
\n
\n\n\n\n```python\nlrev_2, g_2 = df_1[['Lectura_rev', 'g']].iloc[-2]\nprint(lrev_2, g_2, sep='\\n')\n\ndf_2 = dfs[2].copy()\ndf_2.loc[min(df_2.index), 'Lectura'] = lrev_2\n\nd_2, df_2 = rev_loop(df_2, g_2)\ndMarkdown(f'$d_2={d_2:g}$')\ndisplay(df_2)\n```\n\n\n \n\n\n 575.8461538461538\n 979215.5563076923\n\n\n\n$d_2=-0.00423077$\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ESTACIÓNMinutosLecturaLectura_revdelta_gg
77235575.85575.850.00979215.56
98340570.00570.44-4.76979210.79
109375650.00650.5970.69979281.48
1110410510.00510.74-123.35979158.13
127435575.00575.8557.42979215.56
\n
\n\n\n\n```python\ndf_rev = pd.concat([\n df_0.iloc[:-1],\n df_1.iloc[1:-1],\n df_2.iloc[1:-1]\n ], ignore_index=True\n )\n\ndf_rev['bad'] = (k * df_rev['Lectura_rev'].diff().fillna(0) != \n df_rev['delta_g'])\ndisplay(df_rev)\nprint('Total bad:', df_rev['bad'].sum())\n```\n\n\n \n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ESTACIÓNMinutosLecturaLectura_revdelta_ggbad
010520.00520.000.00979166.30False
1230490.00489.54-26.87979139.43False
2365450.00449.00-35.75979103.68False
34100420.00418.46-26.93979076.74False
45165470.00468.0043.69979120.44False
56200510.00506.9234.33979154.77False
67235580.00575.8560.79979215.56False
78340570.00570.44-4.76979210.79False
89375650.00650.5970.69979281.48False
910410510.00510.74-123.35979158.13False
\n
\n\n\n Total bad: 0\n\n\n\n```python\ndf_drop = df.drop_duplicates(subset='ESTACIÓN',\n ignore_index=True)\ndf_rev['rev_diff'] = (df_drop['Lectura']-df_rev['Lectura_rev'])\n\ndisplay(pd.concat([\n df_drop[['ESTACIÓN','Lectura']],\n df_rev[['ESTACIÓN','Lectura_rev']]\n ], axis=1\n )\n)\n\nfig, ax = plt.subplots()\ndf_rev.plot(\n x='Minutos',\n y='rev_diff',\n ax=ax)\nplt.show()\n\nfig, ax = plt.subplots()\ndf_rev.plot(\n x='Minutos',\n y='g',\n ax=ax)\nplt.show()\n```\n", "meta": {"hexsha": "d1a0f1243e272a03ebad47f92fb62b79e1cd0b02", "size": 82503, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Gravimetry/Deriva_Instrumental.ipynb", "max_stars_repo_name": "edwardptera/Gravimetro", "max_stars_repo_head_hexsha": "cb39d813d07a6684de2cc29cfa97087950c0c11e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gravimetry/Deriva_Instrumental.ipynb", "max_issues_repo_name": "edwardptera/Gravimetro", "max_issues_repo_head_hexsha": "cb39d813d07a6684de2cc29cfa97087950c0c11e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gravimetry/Deriva_Instrumental.ipynb", "max_forks_repo_name": "edwardptera/Gravimetro", "max_forks_repo_head_hexsha": "cb39d813d07a6684de2cc29cfa97087950c0c11e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 82503.0, "max_line_length": 82503, "alphanum_fraction": 0.775753609, "converted": true, "num_tokens": 5254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.32100374815570765}} {"text": "# `rlplay`-ing around with the Double-Dee QN\n\n\n```python\nimport torch\nimport numpy\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport gym\n```\n\nSee example.ipynb for the overview of `rlplay`\n\n
\n\n## Tabular CartPole with Q-learning\n\n### The environment\n\nA version of the Taxi Environment that disassembles the observation into pieces\n\n\n```python\nfrom gym.spaces import Dict, Discrete\n\n\nclass StructuredTaxiEnv(gym.ObservationWrapper):\n def __init__(self, env):\n super().__init__(env)\n self.observation_space = Dict(dict(\n row=Discrete(5),\n col=Discrete(5),\n location=Discrete(5),\n destination=Discrete(4)\n ))\n\n @staticmethod\n def observation(n):\n # observation = r x c x p x d \\in 5 x 5 x 5 x 4\n # n, d = divmod(observation, 4)\n # n, p = divmod(n, 5)\n # r, c = divmod(n, 5)\n d = n % 4\n n = n // 4\n p = n % 5\n n = n // 5\n c = n % 5\n r = n // 5\n return dict(row=r, col=c, location=p, destination=d)\n```\n\nA wrapper that makes Taxi's `.render` compatible with `core_evaluate`\n\n\n```python\nclass RenderPatch(gym.Wrapper):\n def render(self, mode='human'):\n result = self.env.render(mode)\n if result is None:\n return True\n\n return result\n```\n\nThe environment factory\n\n\n```python\nfrom gym.envs.toy_text import TaxiEnv\n\n\ndef base_factory(struct=False, seed=None):\n env = gym.make(\"Taxi-v3\")\n if struct:\n env = StructuredTaxiEnv(env)\n return RenderPatch(env)\n```\n\n
\n\n### the Actor\n\nA procedure and a layer, which converts the input integer data into its\nlittle-endian binary representation as float $\\{0, 1\\}^m$ vectors.\n\n\n```python\ndef onehotbits(input, n_bits=63, dtype=torch.float):\n \"\"\"Encode integers to fixed-width binary floating point vectors\"\"\"\n assert not input.dtype.is_floating_point\n assert 0 < n_bits < 64 # torch.int64 is signed, so 64-1 bits max\n\n # n_bits = {torch.int64: 63, torch.int32: 31, torch.int16: 15, torch.int8 : 7}\n\n # get mask of set bits\n pow2 = torch.tensor([1 << j for j in range(n_bits)]).to(input.device)\n x = input.unsqueeze(-1).bitwise_and(pow2).to(bool)\n\n # upcast bool to float to get one-hot\n return x.to(dtype)\n\n\nclass OneHotBits(torch.nn.Module):\n def __init__(self, n_bits=63, dtype=torch.float):\n assert 1 <= n_bits < 64\n super().__init__()\n self.n_bits, self.dtype = n_bits, dtype\n\n def forward(self, input):\n return onehotbits(input, n_bits=self.n_bits, dtype=self.dtype)\n```\n\nA special module dictionary, which applies itself to the input dict of tensors\n\n\n```python\nfrom typing import Optional, Mapping\nfrom torch.nn import Module, ModuleDict as BaseModuleDict\n\n\nclass ModuleDict(BaseModuleDict):\n \"\"\"The ModuleDict, that applies itself to the input dicts.\"\"\"\n def __init__(\n self,\n modules: Optional[Mapping[str, Module]] = None,\n dim: Optional[int]=-1\n ) -> None:\n super().__init__(modules)\n self.dim = dim\n\n def forward(self, input):\n # enforce concatenation in the order of the declaration in __init__\n return torch.cat([\n m(input[k]) for k, m in self.items()\n ], dim=self.dim)\n```\n\nA simple tabular q-learner actor\n\n\n```python\nfrom rlplay.engine import BaseActorModule\n\n\nclass TaxiActor(BaseActorModule):\n def __init__(self, duelling=False, struct=False, epsilon=0.1):\n super().__init__()\n self.duelling = duelling\n\n # the table is actually an embedding of the state index\n n_dim = 6 + (1 if duelling else 0)\n if not struct:\n self.table = torch.nn.Embedding(500, n_dim)\n\n else:\n self.table = torch.nn.Sequential(\n ModuleDict(dict(\n row=torch.nn.Embedding(5, 4),\n col=torch.nn.Embedding(5, 4),\n location=torch.nn.Embedding(5, 4),\n destination=torch.nn.Embedding(4, 4),\n )),\n torch.nn.Linear(16, n_dim)\n )\n\n # for updating the exploration epsilon in the clones\n self.register_buffer('epsilon', torch.tensor(epsilon))\n\n def forward(self, obs, act, rew, fin, *, hx=None, stepno=None, virtual=False):\n qv, hx = self.table(obs), ()\n if self.duelling:\n # dueling net [Wang et al. (2016)](https://arxiv.org/abs/1511.06581)\n val, adv= torch.split_with_sizes(qv, [1, 6], dim=-1)\n qv = adv + (val - adv.mean(dim=-1, keepdim=True))\n\n val, actions = val.squeeze(-1), qv.max(dim=-1).indices\n\n else:\n val, actions = qv.max(dim=-1)\n\n if self.training:\n *head, n_actions = qv.shape\n actions = actions.where(\n torch.rand(head).gt(self.epsilon),\n torch.randint(n_actions, size=head))\n\n return actions, hx, dict(q=qv, value=val)\n```\n\n
\n\n### D-DQN loss\n\nService functions for the algorithms\n\n\n```python\nfrom plyr import apply, suply, xgetitem\n\n\ndef timeshift(state, *, shift=1):\n \"\"\"Get current and shifted slices of nested objects.\"\"\"\n # use `xgetitem` to let None through\n # XXX `curr[t]` = (x_t, a_{t-1}, r_t, d_t), t=0..T-H\n curr = suply(xgetitem, state, index=slice(None, -shift))\n\n # XXX `next[t]` = (x_{t+H}, a_{t+H-1}, r_{t+H}, d_{t+H}), t=0..T-H\n next = suply(xgetitem, state, index=slice(shift, None))\n\n return curr, next\n```\n\nDouble DQN loss for contiguous trajectory fragments. \n\n* `.state[t+1].rew` -- $r_{t+1}$\n* `.state[t+1].fin` -- $d_{t+1}$\n* `.state[t+1].act` -- $a_t$ which caused $\n (s_t, z_t, a_t) \\longrightarrow (s_{t+1}, z_{t+1}, r_{t+1}, d_{t+1})\n$\n* `_, _, fragment.actor[t] = actor(.state[t])` -- $\n q(z_t, h_t, \\cdot; \\theta_{\\text{old}})\n$ -- used for rollout collection\n* `_, _, info_module[t] = module(.state[t])` -- $\n q(z_t, h_t, \\cdot; \\theta)\n$ -- the current q-function, producing $(h_t)_{t=0}^{T+1}$\n* `_, _, info_target[t] = target(.state[t])` -- $\n q(z_t, h_t, \\cdot; \\theta_-)\n$ -- the q-target with $(h^-_t)_{t=0}^{T+1}$\n\nThe current q-network minimizes the $\\mathrm{TD}(0)$-error is\n\n$$\n\\delta_t(\\theta)\n = \\bigl(\n r_{t+1}\n + \\gamma 1_{\\{\\neg d_{t+1}\\}} v^*(z_{t+1})\n \\bigr) - q(z_t, h_t, a_t; \\theta)\n \\,, $$\n\nwhere the approximate state value estimate $\n v^*(z_{t+1})\n$ is one of\n* `Q-learning`: $\n \\max_a q(z_{t+1}, h_{t+1}, a; \\theta)\n$\n* `DQN`: $\n \\max_a q(z_{t+1}, h_{t+1}, a; \\theta_-)\n$\n* `double DQN`: $\n q(z_{t+1}, h_{t+1}, \\hat{a}_{t+1}; \\theta_-)\n$ for $\n \\hat{a}_{t+1} = \\arg \\max_a Qq(z_{t+1}, h_{t+1}, a; \\theta)\n$\n\nOne of the works related to DQN learning of recurrent agents is [Kapturowski et al. (2018)](https://openreview.net/forum?id=r1lyTjAqYX), who propose to use a burn-in period in\nthe contiguous trajectory fragment in order to compensate for the representation drift,\ndue to different RNN parameters $\\theta_-$ and $\\theta$.\n\nThere is no clear-cut evidence suggesting that the hidden recurrent sequences $h_t$\nand $h^-_t$ yield significantly different results.\n\n\n```python\nimport torch.nn.functional as F\n\n\n# @torch.enable_grad()\ndef ddq_learn(fragment, module, *, gamma=0.95, target=None, double=False):\n r\"\"\"Compute the Double-DQN loss over a _contiguous_ fragment of a trajectory.\n\n Details\n -------\n In Q-learning the action value function minimizes the TD-error\n\n $$\n r_{t+1}\n + \\gamma 1_{\\neg d_{t+1}} v^*(z_{t+1})\n - q(z_t, a_t; \\theta)\n \\,, $$\n\n w.r.t. Q-network parameters $\\theta$ where $z_t$ is the actionable state,\n $r_{t+1}$ is the reward for $s_t \\to s_{t+1}$ transition. The value of\n $z_t$ include the current observation $x_t$ and the recurrent state $h_t$,\n the last action $a_{t-1}$, the last reward $r_t$, and termination flag\n $d_t$.\n\n In the classic Q-learning there is no target network and the next state\n optimal state value function is bootstrapped using the current Q-network\n (`module`):\n\n $$\n v^*(z_{t+1})\n \\approx \\max_a q(z_{t+1}, a; \\theta)\n \\,. $$\n\n The DQN method, proposed by\n\n [Minh et al. (2013)](https://arxiv.org/abs/1312.5602),\n\n uses a secondary Q-network (`target`) to estimate the value of the next\n state:\n\n $$\n v^*(z_{t+1})\n \\approx \\max_a q(z_{t+1}, a; \\theta^-)\n \\,, $$\n\n where $\\theta^-$ are the frozen parameters of the target Q-network. The\n Double DQN algorithm of\n\n [van Hasselt et al. (2015)](https://arxiv.org/abs/1509.06461)\n\n unravels the $\\max$ operator as\n $\n \\max_k u_k \\equiv u_{\\arg \\max_k u_k}\n $\n and replaces the outer $u$ with the Q-values of the target Q-network, while\n computing the inner $u$ (inside the $\\arg\\max$) with the current Q-network.\n Specifically, the Double DQN value estimate is\n\n $$\n v^*(z_{t+1})\n \\approx q(z_{t+1}, \\hat{a}_{t+1}; \\theta^-)\n \\,,\n \\hat{a}_{t+1}\n = \\arg \\max_a q(z_{t+1}, a; \\theta)\n \\,, $$\n\n for $\n \\hat{a}_{t+1}\n = \\arg \\max_a q(s_{t+1}, a; \\theta)\n $ being the action taken by the current Q-network $\\theta$ at $z_{t+1}$.\n\n Recurrent DQN\n -------------\n The key problem with the recurrent state $h_t$ in $z_t$ is its representation\n drift: the endogenous states used for collecting trajectory data during the\n rollout are produced by an actor with stale parameters $\\theta_{\\text{old}}$,\n and thus might have high discrepancy with the recurrent state produced by\n the current Q-network $\\theta$ or the target $\\theta-_$. To mitigate this\n \n [Kapturowski et al. (2018)](https://openreview.net/forum?id=r1lyTjAqYX)\n \n proposed to spend a slice `burn-in` of the recorded trajectory on\n aligning the recurrent representation. Specifically, starting with $h_0$\n (contained in `fragment.hx`) they propose to launch two sequences $h_t$\n and $h^-_t$ from the same $h^-_0 = h_0$ using $q(\\cdot; \\theta)$ and\n $q(\\cdot; \\theta^-)$, respectively.\n \"\"\"\n\n trajectory, hx = fragment.state, fragment.hx\n obs, act, rew, fin = trajectory.obs, trajectory.act, trajectory.rew, trajectory.fin\n\n # get $Q(z_t, h_t, \\cdot; \\theta)$ for all t=0..T\n _, _, info_module = module(\n obs, act, rew, fin, hx=hx, stepno=trajectory.stepno)\n\n # get the next state `state[t+1]` $z_{t+1}$ to access $a_t$\n state_next = suply(xgetitem, trajectory, index=slice(1, None))\n\n # $\\hat{A}_t$, the module's response to current and next state,\n # contains the q-values. `curr` is $q(z_t, h_{t+1}, \\cdot; \\theta)$\n # and `next` is $q(z_{t+1}, h_{t+1}, \\cdot; \\theta)$ is `next`.\n info_module_curr, info_module_next = timeshift(info_module)\n\n # get $q(z_t, h_t, a_t; \\theta)$ for all t=0..T-1\n q_replay = info_module_curr['q'].gather(-1, state_next.act.unsqueeze(-1))\n\n # get $\\hat{v}_{t+1}(z_{t+1}) = ...$\n with torch.no_grad():\n if target is None:\n # get $... = \\max_a Q(z_{t+1}, h_{t+1}, a; \\theta)$\n q_value = info_module_next['q'].max(dim=-1, keepdim=True).values\n\n else:\n _, _, info_target = target(\n obs, act, rew, fin, hx=hx, stepno=trajectory.stepno)\n\n info_target_next = suply(xgetitem, info_target, index=slice(1, None))\n if not double:\n # get $... = \\max_a Q(z_{t+1}, h^-_{t+1}, a; \\theta^-)$\n q_value = info_target_next['q'].max(dim=-1, keepdim=True).values\n\n else:\n # get $\\hat{a}_{t+1} = \\arg \\max_a Q(z_{t+1}, h_{t+1}, a; \\theta)$\n hat_act = info_module_next['q'].max(dim=-1).indices.unsqueeze(-1)\n\n # get $... = Q(z_{t+1}, h^-_{t+1}, \\hat{a}_{t+1}; \\theta^-)$\n q_value = info_target_next['q'].gather(-1, hat_act)\n\n # get $r_{t+1} + \\gamma 1_{d_{t+1}} \\hat{v}_{t+1}(z_{t+1})$ using inplace ops\n q_value.masked_fill_(state_next.fin.unsqueeze(-1), 0.)\n q_value.mul_(gamma).add_(state_next.rew.unsqueeze(-1))\n\n # td-error ell-2 loss\n return F.mse_loss(q_replay, q_value, reduction='sum'), {}\n```\n\n
\n\nThe following is my incomplete take on [Bellemare et al. (2017)](http://proceedings.mlr.press/v70/bellemare17a.html)\n\nThen the distributional Bellman operator on a policy $\\pi_\\theta$ at $(s, a)$ is\ndefined as a random variable on $\\mathbb{R}$ with the following law\n\n$$\n(T Q_\\theta)(s, a)\n \\overset{D}{=}\n r + \\gamma Q_\\theta(s', a')\n \\,, \\text{ for }\n (r, s') \\sim p(r, s'\\mid s, a)\n \\,, \\text{ and }\n a' \\sim \\pi_\\theta(a \\mid s')\n \\,.\n$$\n\nFormally, this means the following (omitting the dependency of on $(s, a)$):\n\n\\begin{align}\n \\mathbb{P}\\bigl(\n T Q_\\theta \\in U\n \\bigr)\n &= \\mathbb{P}\\bigl(\n R + \\gamma Q_\\theta(S', A') \\in U\n \\bigr)\n \\\\\n &= \\mathbb{E}_{r, s'\\sim p(r, s'\\mid s, a)}\n \\mathbb{E}_{a'\\sim \\pi_\\theta(a \\mid s')}\n \\mathbb{P}\\bigl(\n R + \\gamma Q_\\theta(S', A') \\in U\n \\,\\big \\vert\\, S'=s, R=r, A'=a'\n \\bigr)\n \\\\\n &= \\mathbb{E}_{r, s'\\sim p(r, s'\\mid s, a)}\n \\mathbb{E}_{a'\\sim \\pi_\\theta(a \\mid s')}\n \\mathbb{P}\\bigl(\n Q_\\theta(s', a') \\in \\frac{U - r} \\gamma\n \\bigr)\n \\,,\n\\end{align}\n\nor, in other words, $T$ acts on the conditional distribution $\n Q_\\theta(\\cdot \\mid s, a)\n$ thus: for any bounded Borel measurable $f$\n\n\\begin{align}\n \\int (T Q_\\theta)(dv \\mid s, a) f(v)\n &= \\int\n p(ds', dr\\mid s, a) % clump p and R into one cond-distrib\n \\pi_\\theta(da' \\mid s')\n Q_\\theta(dv\\mid s', a')\n f(r + \\gamma v)\n \\\\\n &= % Fubini\n \\mathbb{E}_{r, s'\\sim p(r, s'\\mid s, a)}\n \\mathbb{E}_{a'\\sim \\pi_\\theta(a \\mid s')}\n \\mathbb{E}_{v\\sim Q_\\theta(v\\mid s', a')}\n f(r + \\gamma v)\n \\,.\n\\end{align}\n\nThus suggests several approximations, depending on the tractability of the inner expectations.\n\nIdeally we would like to find such distribution, that\n$$\n(T Q_\\theta)(s, a)\n \\overset{D}{=}\n Q_\\theta(s, a)\n \\,, $$\nfor all or most $s$ and $a$.\n\nIf $f$ is $L$-Lipschitz, then\n\\begin{align}\n\\biggl\\lvert\n \\int \\bigl(\n (T H)(dv \\mid s, a) - (T G)(dv \\mid s, a)\n \\bigr) f(v)\n \\biggr\\rvert\n &\\leq \\int\n p(ds', dr\\mid s, a)\n \\pi_\\theta(da' \\mid s')\n H(dh\\mid s', a')\n G(dg \\mid s', a')\n \\bigl\\lvert\n f(r + \\gamma h) - f(r + \\gamma g)\n \\bigr\\rvert\n \\\\\n &\\leq L \\gamma \\int\n p(ds', dr\\mid s, a)\n \\pi_\\theta(da' \\mid s')\n H(dh \\mid s', a')\n G(dg \\mid s', a')\n \\bigl\\lvert h - g \\bigr\\rvert\n \\\\\n &\\leq L \\gamma \\int\n p(ds', dr\\mid s, a)\n \\pi_\\theta(da' \\mid s')\n \\int\n H(dh \\mid s', a')\n G(dg \\mid s', a')\n \\bigl\\lvert h - g \\bigr\\rvert\n \\\\\n &\\leq L \\gamma \\sup_{s, a}\n \\int\n H(dh \\mid s, a)\n G(dg \\mid s, a)\n \\bigl\\lvert h - g \\bigr\\rvert\n \\,,\n\\end{align}\n\nso there is hope for contraction or even convergence, however, it is better to\nconsult [Bellemare et al. (2017)](http://proceedings.mlr.press/v70/bellemare17a.html)\nfirst.\n\n\n\nBelow is the loss for a version of the distributional DQN, specific to Gaussian approximations\nand maxent regularization.\n\nWe minimize (in expectation over transition $s, a \\to s'$) the Kullback-Leibler\ndivergence between distributions $\n (T Q_\\theta)(dv \\mid s, a)\n$ and $\n Q_\\theta(dv \\mid s, a)\n$, while at the same time encouraging $\n Q_\\theta(dv \\mid s, a)\n$ to exhibit high entropy. The actions $a' \\sim \\pi_\\theta(a\\mid s')$\nare sampled greedily as $\n \\arg \\max_a \\int Q_\\theta(dv \\mid s', a) v\n$ (assuming finite action space).\n\n\n```python\ndef gdqn(fragment, module, *, gamma, C=1e-3):\n trajectory, hx = fragment.state, fragment.hx\n obs, act, rew, fin = trajectory.obs, trajectory.act, trajectory.rew, trajectory.fin\n\n # get $Q(z_t, h_t, \\cdot; \\theta)$ for all t=0..T\n act, _, info_module = module(\n obs, act, rew, fin, hx=hx, stepno=trajectory.stepno)\n\n # get the next state `state[t+1]` $z_{t+1}$ to access $a_t$\n state_next, act = suply(xgetitem, (trajectory, act.unsqueeze(-1)), index=slice(1, None))\n\n # $\\hat{A}_t$, the module's response to current and next state,\n # contains the q-values. `curr` is $q(z_t, h_{t+1}, \\cdot; \\theta)$\n # and `next` is $q(z_{t+1}, h_{t+1}, \\cdot; \\theta)$ is `next`.\n info_module_curr, info_module_next = timeshift(info_module)\n\n # get T Z_\\theta(\\cdot \\mid z_t, a_t)\n # \\overset{=}{D} N(\\cdot \\mid r_{t+1} + \\gamma 1_{d_{t+1}} \\hat{v}_{t+1}(z_{t+1}), ...)\n # use action a' \\sim \\arg \\max_a z_\\theta(a \\mid z_{t+1}, a_{t+1})\n factor = torch.where(state_next.fin, 1e-4, gamma) # XXX some leakage from the next traj.\n with torch.no_grad():\n # get $r_{t+1} + \\gamma 1_{d_{t+1}} \\hat{v}_{t+1}(z_{t+1})$\n zed = info_module_next['loc'].gather(-1, act).squeeze(-1)\n loc = state_next.rew + factor * zed\n # XXX should the termination does not affect the scale?\n scl = factor * info_module_next['scl'].gather(-1, act).squeeze(-1)\n q = Normal(loc, scl)\n\n # get Z_\\theta(\\cdot \\mid s_t, a_t)\n act = state_next.act.unsqueeze(-1)\n p = Normal(\n info_module_curr['loc'].gather(-1, act).squeeze(-1),\n info_module_curr['scl'].gather(-1, act).squeeze(-1),\n )\n \n # distance from T z_\\theta to z_\\theta on s-a-r-s' samples\n dst = kl_divergence(q, p).mean() # q is fixed target.\n # XXX fwd kl means covering, not mode-seeking.\n\n # use kl from N(0, 1) prior, but can we also use entropy?\n # pi = Normal(*torch.tensor([0., 1.])).expand(loc.shape)\n # kl_reg = kl_divergence(p, pi).mean()\n reg = -p.entropy().mean()\n\n return dst + C * reg, {\n 'dst': float(dst),\n 'reg': float(reg),\n }\n```\n\nLet's define an actor for the distributional Q-learning with the Gaussian approximation:\n\n$$\nQ_\\theta(\n v \\mid z, a\n ) = \\mathcal{N}\\bigl(\n v \\,\\big\\vert \\,\n \\mu(z, a),\n \\sigma^2(z, a)\n \\bigr)\n \\,. $$\n\nThe greedy action sampling must take into account the distribution of $\n j^* = \\arg\\max_i z_i\n$ for a collection of independent $\n z_i \\sim \\mathcal{N}(Z_i \\mid \\mu_i, \\sigma^2_i)\n$, not just the means. Specifically, we must make sure that $j^*=j$ with probability\n\n$$\n\\mathbb{P}(Z_j \\geq \\max_{i\\neq j} Z_i)\n = \\mathbb{E}\n \\mathbb{P}(Z_j \\geq \\max_{i\\neq j} Z_i \\big \\vert Z_j)\n = \\mathbb{E}_{\\xi \\sim \\mathcal{N}(0, 1)}\n \\prod_{i\\neq j} \\Phi\\biggl(\n \\frac{\\mu_j - \\mu_i}{\\sigma_i}\n + \\frac{\\sigma_j}{\\sigma_i} \\xi\n \\biggr)\n \\,, $$\n \nwherein we used independence and the fact that the max of independent Gaussian rvs satisfies\n\n$$\n\\mathbb{P}(\\max_i Z_i \\leq c)\n = \\prod_i \\mathbb{P}(Z_i \\leq c)\n = \\prod_i \\Phi\\biggl(\n \\frac{c - \\mu_i}{\\sigma_i}\n \\biggr)\n \\,, $$\n\nfor $\\Phi$ -- the univariate standard Gaussian CDF.\n\nBut this is hard to compute... So we use the largest mean heuristic.\nMaybe we can use extreme value asymptotics here?\n\n\n```python\nfrom rlplay.engine import BaseActorModule\nfrom torch.distributions import Independent, Normal, kl_divergence\n\n\nclass GaussTaxiActor(BaseActorModule):\n def __init__(self, *, struct=False, epsilon=0.1):\n super().__init__()\n self.struct = struct\n\n if not struct:\n self.table = torch.nn.Embedding(500, 2 * 6)\n\n else:\n self.table = torch.nn.Sequential(\n ModuleDict(dict(\n row=torch.nn.Embedding(5, 3),\n col=torch.nn.Embedding(5, 3),\n location=torch.nn.Embedding(5, 3),\n destination=torch.nn.Embedding(4, 3),\n )),\n torch.nn.Linear(12, 32),\n torch.nn.ReLU(),\n torch.nn.Linear(32, 2 * 6),\n )\n\n # for updating the exploration epsilon in the clones\n self.register_buffer('epsilon', torch.tensor(epsilon))\n\n def forward(self, obs, act, rew, fin, *, hx=None, stepno=None, virtual=False):\n out, hx = self.table(obs), ()\n\n loc, out = torch.chunk(out, 2, dim=-1)\n scl = torch.clamp(F.softplus(out), min=1e-3)\n\n # val, act = Normal(loc, scl).sample().max(dim=-1)\n val, act = loc.max(dim=-1) # unfounded heuristic :(\n\n return act, hx, dict(loc=loc, scl=scl, q=loc, value=val)\n```\n\n
\n\n### Run!\n\nprepare the optimizer for the learner\n\n\n```python\ngamma = 0.99\nuse_dist = True\nuse_target = False\nuse_double = False\nuse_duelling = False\n\n# `target` does not work for some reason at all with taxi, maybe the freeze schedule is off?\n# or contiguous fragments work to the detriment of learning\n\n# `duelling` also fails for both target and double, and sorta for ordinary q\n```\n\nInitialize the learner and the environment factories\n\n\n```python\nfrom functools import partial\n\n\nstructured = False\n\nfactory_eval = partial(base_factory, struct=structured)\nfactory = partial(base_factory, struct=structured)\n\nif use_dist:\n learner = GaussTaxiActor(struct=structured)\nelse:\n learner = TaxiActor(duelling=use_duelling, epsilon=1., struct=structured)\n\nlearner.train()\ndevice_ = torch.device('cpu') # torch.device('cuda:0')\nlearner.to(device=device_)\n\noptim = torch.optim.Adam(learner.parameters(), lr=1e-2)\n```\n\nInitialize the sampler\n\n\n```python\nT, B = 25, 8\n```\nfrom rlplay.engine.rollout import same\n\nbatchit = same.rollout(\n [factory() for _ in range(B)],\n learner,\n n_steps=T,\n sticky=False,\n device=device_,\n)from rlplay.engine.rollout import single\n\nbatchit = single.rollout(\n factory,\n learner,\n n_steps=T,\n n_envs=B,\n sticky=False,\n clone=True,\n close=False,\n device=device_,\n start_method='fork', # fork in notebook for macos, spawn in linux\n)\n\n```python\nfrom rlplay.engine.rollout import multi\n\nbatchit = multi.rollout(\n factory,\n learner,\n n_steps=T,\n n_actors=8,\n n_per_actor=B,\n n_buffers=16,\n n_per_batch=2,\n sticky=False,\n pinned=False,\n clone=True,\n close=False,\n device=device_,\n start_method='fork', # fork in notebook for macos, spawn in linux\n)\n```\n\nA generator of evaluation rewards\n\n\n```python\nfrom rlplay.engine.rollout.evaluate import evaluate\n\ntest_it = evaluate(factory_eval, learner, n_envs=4, n_steps=500,\n clone=False, device=device_, start_method='fork')\n```\n\nImplement your favourite training method\n\n\n```python\nimport tqdm\nimport copy\nfrom math import log, exp\nfrom torch.nn.utils import clip_grad_norm_\n\ntorch.set_num_threads(1)\n\n# the training loop\nlosses, rewards = [], []\ndecay = -log(2) / 50 # exploration epsilon halflife\nfor epoch in tqdm.tqdm(range(400)):\n # freeze the target for q\n target = copy.deepcopy(learner) if use_target else None\n\n for j, batch in zip(range(100), batchit):\n if use_dist:\n loss, info = gdqn(batch, learner, gamma=gamma)\n\n else:\n loss, info = ddq_learn(batch, learner, target=target,\n gamma=gamma, double=use_double)\n\n\n optim.zero_grad()\n loss.backward()\n grad = clip_grad_norm_(learner.parameters(), max_norm=1e3)\n optim.step()\n\n losses.append(dict(\n loss=float(loss), grad=float(grad), **info\n ))\n\n learner.epsilon.mul_(exp(decay)).clip_(0.1, 1.0)\n\n # fetch the evaluation results lagged by one inner loop!\n rewards.append(next(test_it))\n```\n\n\n```python\n# close the generators\nbatchit.close()\ntest_it.close()\n```\nimport pdb; pdb.pm()\n
\n\n\n```python\ndef collate(records):\n \"\"\"collate identically keyed dicts\"\"\"\n out, n_records = {}, 0\n for record in records:\n for k, v in record.items():\n out.setdefault(k, []).append(v)\n \n return out\n\n\ndata = {k: numpy.array(v) for k, v in collate(losses).items()}\n```\n\n\n```python\nplt.semilogy(data['loss'])\n```\n\n\n```python\nplt.semilogy(data['grad'])\n```\n\n\n```python\nif 'dst' in data:\n plt.semilogy(data['dst'])\n```\n\n\n```python\nif 'reg' in data:\n plt.semilogy(data['reg'])\n```\n\n\n```python\nrewards = numpy.stack(rewards, axis=0)\n```\n\n\n```python\nrewards\n```\n\n\n```python\nm, s = numpy.median(rewards, axis=-1), rewards.std(axis=-1)\n```\n\n\n```python\nfi, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=300)\n\nax.plot(numpy.mean(rewards, axis=-1))\nax.plot(numpy.median(rewards, axis=-1))\nax.plot(numpy.min(rewards, axis=-1))\nax.plot(numpy.std(rewards, axis=-1))\n# ax.plot(m+s * 1.96)\n# ax.plot(m-s * 1.96)\n\nplt.show()\n```\n\n
\n\nThe ultimate evaluation run\n\n\n```python\nfrom rlplay.engine import core\n\nwith factory_eval() as env:\n learner.eval()\n eval_rewards, info = core.evaluate([\n env\n ], learner, render=True, n_steps=1e2, device=device_)\n\nprint(sum(eval_rewards))\n```\nimport pdb; pdb.pm()\n
\n\nLet's analyze the performance\n\n\n```python\n(info['q'] - numpy.expand_dims(info['value'], -1)).shape\n```\n\n\n```python\nplt.plot((info['q'] - numpy.expand_dims(info['value'], -1))[:, 0])\n```\n\n\n```python\nfrom rlplay.algo.returns import npy_returns, npy_deltas\n\ntd_target = eval_rewards + gamma * info['value'][1:]\ntd_error = td_target - info['value'][:-1]\n# td_error = npy_deltas(\n# eval_rewards, numpy.zeros_like(eval_rewards, dtype=bool), info['value'][:-1],\n# gamma=gamma, bootstrap=info['value'][-1])\n\nfig, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=300)\nax.semilogy(abs(td_error) / abs(td_target))\nax.set_title('relative td(1)-error');\n```\n\n\n```python\nfrom rlplay.algo.returns import npy_returns, npy_deltas\n\n# plt.plot(\n# npy_returns(eval_rewards, numpy.zeros_like(eval_rewards, dtype=bool),\n# gamma=gamma, bootstrap=info['value'][-1]))\nfig, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=300)\nax.plot(info['value']);\n```\n\n\n```python\nwith torch.no_grad():\n obs = torch.arange(500).unsqueeze(1)\n if structured:\n obs = StructuredTaxiEnv.observation(obs)\n\n _, _, info = learner(obs, act=None, rew=None, fin=None) \n if 'loc' in info:\n # shuffle dims to `a d p r c`\n loc = info['loc'].reshape(5, 5, 5, 4, -1).permute(4, 3, 2, 0, 1)\n scl = info['scl'].reshape(5, 5, 5, 4, -1).permute(4, 3, 2, 0, 1)\n p = Normal(loc, scl)\n ent = p.entropy()\n\n else:\n loc = info['q'].reshape(5, 5, 5, 4, -1).permute(4, 3, 2, 0, 1)\n```\n\n\n```python\nd = 'R'\ndst = {'R': 0, 'G': 1, 'Y': 2, 'B': 3}\n\n# +---------+\n# |R: | : :G|\n# | : | : : |\n# | : : : : |\n# | | : | : |\n# |Y| : |B: |\n# +---------+\n\nx = loc[:, dst[d]].permute(1, 2, 0, 3) # .reshape(5 * 5, 6 * 5)\nplt.imshow(torch.cat([\n x, x[:, :, :4].max(2, keepdim=True).values,\n], dim=2).reshape(5 * 5, 7 * 5))\n\n# cols: action snewpd, rows: location RGYBT\nplt.xlabel('action + pool')\nplt.xticks(list(range(2, 35, 5)), [*'snewpd', 'max'])\nplt.ylabel('location')\nplt.yticks(list(range(2, 25, 5)), list('RGYBT'))\nplt.title(f'destination: {d}');\n```\n\n
\n\n\n```python\nassert False\n```\n", "meta": {"hexsha": "fd2622d4ef387cfc1294a11d172f9e919a062cd6", "size": 44131, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "stage/example-dqn.ipynb", "max_stars_repo_name": "ivannz/rlplay", "max_stars_repo_head_hexsha": "eeca796e6501d6077c4fbfde4cdb41567768a492", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2021-04-11T13:38:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T09:37:05.000Z", "max_issues_repo_path": "stage/example-dqn.ipynb", "max_issues_repo_name": "ivannz/rlplay", "max_issues_repo_head_hexsha": "eeca796e6501d6077c4fbfde4cdb41567768a492", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-12-23T09:22:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T11:39:22.000Z", "max_forks_repo_path": "stage/example-dqn.ipynb", "max_forks_repo_name": "ivannz/rlplay", "max_forks_repo_head_hexsha": "eeca796e6501d6077c4fbfde4cdb41567768a492", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7378706199, "max_line_length": 184, "alphanum_fraction": 0.4759012939, "converted": true, "num_tokens": 8443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.32095242067285534}} {"text": "\n# Coupled Cluster theory and infinite nuclear matter\n\n **Morten Hjorth-Jensen**, [National Superconducting Cyclotron Laboratory](http://www.nscl.msu.edu/) and [Department of Physics and Astronomy](https://www.pa.msu.edu/), [Michigan State University](http://www.msu.edu/), East Lansing, MI 48824, USA and Department of Physics, University of Oslo, N-0316 Oslo, Norway\n\nDate: **28th Indian-Summer School on Ab Initio Methods in Nuclear Physics**\n\n# Introduction\nCoester and Kummel first developed the ideas that led to coupled-cluster\ntheory in the late 1950s. The basic idea is that the correlated wave function\nof a many-body system $\\mid\\Psi\\rangle$\ncan be formulated as an exponential of correlation\noperators $T$ acting on a reference state $\\mid\\Phi\\rangle$\n\n$$\n\\mid\\Psi\\rangle = \\exp\\left(-\\hat{T}\\right)\\mid\\Phi\\rangle\\ .\n$$\n\nWe will discuss how to define the operators later in this work. This simple\nansatz carries enormous power. It leads to a non-perturbative many-body\ntheory that includes summation of ladder diagrams , ring\ndiagrams, and an infinite-order\ngeneralization of many-body perturbation theory.\n\n# Introduction\nDevelopments and applications\nof coupled-cluster theory took different routes in chemistry\nand nuclear physics. In quantum chemistry,\ncoupled-cluster developments\nand applications have proven to be extremely useful, see for example the review by [Barrett and Musial](http://journals.aps.org/rmp/abstract/10.1103/RevModPhys.79.291) as well as the recent \ntextbook by [Shavitt and Barrett](http://www.cambridge.org/fr/academic/subjects/chemistry/physical-chemistry/many-body-methods-chemistry-and-physics-mbpt-and-coupled-cluster-theory?format=HB). Many previous applications to nuclear physics struggled with the repulsive character of the nuclear forces and limited basis sets used in the computations. Most of these problems have been overcome during the last decade and coupled-cluster\ntheory is one of the computational methods of preference for doing nuclear physics, with applications ranging from light nuclei to medium-heavy nuclei,\nsee for example the recent review by [Hagen, Papenbrock, Hjorth-Jensen and Dean](http://iopscience.iop.org/0034-4885/77/9/096302). \n\n\n## A non-practical way of solving the eigenvalue problem\n\nBefore we proceed with the derivation of the Coupled cluster equations, let us repeat some of the arguments we presented during our FCI lectures. \nIn our FCI discussions, we rewrote the solution of the Schroedinger equation as a set of coupled equationsin the unknown coefficients $C$. Let us repeat some of these arguments.\nTo obtain the eigenstates and eigenvalues in terms of non-linear equations is not a very practical approach. However, it serves the scope of linking FCI theory with approximative solutions to the many-body problem\nlike Coupled cluster (CC) theory \n\n\n## A non-practical way of solving the eigenvalue problem\nIf we assume that we have a two-body operator at most, the Slater-Condon rule \ngives then an equation for the \ncorrelation energy in terms of $C_i^a$ and $C_{ij}^{ab}$ only. We get then\n\n$$\n\\langle \\Phi_0 | \\hat{H} -E| \\Phi_0\\rangle + \\sum_{ai}\\langle \\Phi_0 | \\hat{H} -E|\\Phi_{i}^{a} \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle \\Phi_0 | \\hat{H} -E|\\Phi_{ij}^{ab} \\rangle C_{ij}^{ab}=0,\n$$\n\nor\n\n$$\nE-E_0 =\\Delta E=\\sum_{ai}\\langle \\Phi_0 | \\hat{H}|\\Phi_{i}^{a} \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle \\Phi_0 | \\hat{H}|\\Phi_{ij}^{ab} \\rangle C_{ij}^{ab},\n$$\n\nwhere the energy $E_0$ is the reference energy and $\\Delta E$ defines the so-called correlation energy.\nThe single-particle basis functions could be the results of a Hartree-Fock calculation or just the eigenstates of the non-interacting part of the Hamiltonian. \n\n\n## A non-practical way of solving the eigenvalue problem\nIn our notes on Hartree-Fock calculations, \nwe have already computed the matrix $\\langle \\Phi_0 | \\hat{H}|\\Phi_{i}^{a}\\rangle $ and $\\langle \\Phi_0 | \\hat{H}|\\Phi_{ij}^{ab}\\rangle$. If we are using a Hartree-Fock basis, then the matrix elements\n$\\langle \\Phi_0 | \\hat{H}|\\Phi_{i}^{a}\\rangle=0$ and we are left with a *correlation energy* given by\n\n$$\nE-E_0 =\\Delta E^{HF}=\\sum_{abij}\\langle \\Phi_0 | \\hat{H}|\\Phi_{ij}^{ab} \\rangle C_{ij}^{ab}.\n$$\n\n\n## A non-practical way of solving the eigenvalue problem\nInserting the various matrix elements we can rewrite the previous equation as\n\n$$\n\\Delta E=\\sum_{ai}\\langle i| \\hat{f}|a \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle ij | \\hat{v}| ab \\rangle C_{ij}^{ab}.\n$$\n\nThis equation determines the correlation energy but not the coefficients $C$. \nWe need more equations. Our next step is to set up\n\n$$\n\\langle \\Phi_i^a | \\hat{H} -E| \\Phi_0\\rangle + \\sum_{bj}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{j}^{b} \\rangle C_{j}^{b}+\n\\sum_{bcjk}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{jk}^{bc} \\rangle C_{jk}^{bc}+\n\\sum_{bcdjkl}\\langle \\Phi_i^a | \\hat{H} -E|\\Phi_{jkl}^{bcd} \\rangle C_{jkl}^{bcd}=0,\n$$\n\nas this equation will allow us to find an expression for the coefficents $C_i^a$ since we can rewrite this equation as\n\n$$\n\\langle i | \\hat{f}| a\\rangle +\\langle \\Phi_i^a | \\hat{H}|\\Phi_{i}^{a} \\rangle C_{i}^{a}+ \\sum_{bj\\ne ai}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{j}^{b} \\rangle C_{j}^{b}+\n\\sum_{bcjk}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{jk}^{bc} \\rangle C_{jk}^{bc}+\n\\sum_{bcdjkl}\\langle \\Phi_i^a | \\hat{H}|\\Phi_{jkl}^{bcd} \\rangle C_{jkl}^{bcd}=EC_i^a.\n$$\n\n\n## A non-practical way of solving the eigenvalue problem\nWe see that on the right-hand side we have the energy $E$. This leads to a non-linear equation in the unknown coefficients. \nThese equations are normally solved iteratively ( that is we can start with a guess for the coefficients $C_i^a$). A common choice is to use perturbation theory for the first guess, setting thereby\n\n$$\nC_{i}^{a}=\\frac{\\langle i | \\hat{f}| a\\rangle}{\\epsilon_i-\\epsilon_a}.\n$$\n\nThe observant reader will however see that we need an equation for $C_{jk}^{bc}$ and $C_{jkl}^{bcd}$ as well.\nTo find equations for these coefficients we need then to continue our multiplications from the left with the various\n$\\Phi_{H}^P$ terms. \n\n\n## A non-practical way of solving the eigenvalue problem\nFor $C_{jk}^{bc}$ we need then\n\n8\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n$$\n\\sum_{cdkl}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{kl}^{cd} \\rangle C_{kl}^{cd}+\\sum_{cdeklm}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{klm}^{cde} \\rangle C_{klm}^{cde}+\\sum_{cdefklmn}\\langle \\Phi_{ij}^{ab} | \\hat{H} -E|\\Phi_{klmn}^{cdef} \\rangle C_{klmn}^{cdef}=0,\n$$\n\nand we can isolate the coefficients $C_{kl}^{cd}$ in a similar way as we did for the coefficients $C_{i}^{a}$. \nA standard choice for the first iteration is to set\n\n$$\nC_{ij}^{ab} =\\frac{\\langle ij \\vert \\hat{v} \\vert ab \\rangle}{\\epsilon_i+\\epsilon_j-\\epsilon_a-\\epsilon_b}.\n$$\n\n\n## A non-practical way of solving the eigenvalue problem\nAt the end we can rewrite our solution of the Schroedinger equation in terms of $n$ coupled equations for the coefficients $C_H^P$.\nThis is a very cumbersome way of solving the equation. However, by using this iterative scheme we can illustrate how we can compute the\nvarious terms in the wave operator or correlation operator $\\hat{C}$. We will later identify the calculation of the various terms $C_H^P$\nas parts of different many-body approximations to full CI. In particular, we can relate this non-linear scheme with Coupled Cluster theory and\nmany-body perturbation theory.\n\n## Summarizing FCI and bringing in approximative methods\nIf we can diagonalize large matrices, FCI is the method of choice since:\n* It gives all eigenvalues, ground state and excited states\n\n* The eigenvectors are obtained directly from the coefficients $C_H^P$ which result from the diagonalization\n\n* We can compute easily expectation values of other operators, as well as transition probabilities\n\n* Correlations are easy to understand in terms of contributions to a given operator beyond the Hartree-Fock contribution. This is the standard approach in many-body theory. \n\n## Summarizing FCI and bringing in approximative methods\nThe correlation energy is defined as, with a two-body Hamiltonian,\n\n$$\n\\Delta E=\\sum_{ai}\\langle i| \\hat{f}|a \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle ij | \\hat{v}| ab \\rangle C_{ij}^{ab}.\n$$\n\nThe coefficients $C$ result from the solution of the eigenvalue problem. \nThe energy of say the ground state is then\n\n$$\nE=E_{ref}+\\Delta E,\n$$\n\nwhere the so-called reference energy is the energy we obtain from a Hartree-Fock calculation, that is\n\n$$\nE_{ref}=\\langle \\Phi_0 \\vert \\hat{H} \\vert \\Phi_0 \\rangle.\n$$\n\n## Summarizing FCI and bringing in approximative methods\nHowever, as we have seen, even for a small case like the four first major shells and a nucleus like oxygen-16, the dimensionality becomes quickly intractable. If we wish to include single-particle states that reflect weakly bound systems, we need a much larger single-particle basis. We need thus approximative methods that sum specific correlations to infinite order. \n\nPopular methods are\n* [Many-body perturbation theory (in essence a Taylor expansion)](http://www.sciencedirect.com/science/journal/03701573/261/3-4)\n\n* [Coupled cluster theory (coupled non-linear equations)](http://iopscience.iop.org/0034-4885/77/9/096302)\n\n* [Green's function approaches (matrix inversion)](http://www.worldscientific.com/worldscibooks/10.1142/6821)\n\n* [Similarity group transformation methods (coupled ordinary differential equations)](http://journals.aps.org/prc/abstract/10.1103/PhysRevC.85.061304)\n\nAll these methods start normally with a Hartree-Fock basis as the calculational basis. \n\n## A quick tour of Coupled Cluster theory\n\nThe ansatz for the wavefunction (ground state) is given by\n\n$$\n\\vert \\Psi\\rangle = \\vert \\Psi_{CC}\\rangle = e^{\\hat{T}} \\vert \\Phi_0\\rangle = \n \\left( \\sum_{n=1}^{A} \\frac{1}{n!} \\hat{T}^n \\right) \\vert \\Phi_0\\rangle,\n$$\n\nwhere $A$ represents the maximum number of particle-hole excitations and $\\hat{T}$ is the cluster operator defined as\n\n$$\n\\begin{align*}\n \\hat{T} &= \\hat{T}_1 + \\hat{T}_2 + \\ldots + \\hat{T}_A \\\\\n \\hat{T}_n &= \\left(\\frac{1}{n!}\\right)^2 \n \\sum_{\\substack{\n i_1,i_2,\\ldots i_n \\\\\n a_1,a_2,\\ldots a_n}}\n t_{i_1i_2\\ldots i_n}^{a_1a_2\\ldots a_n} a_{a_1}^\\dagger a_{a_2}^\\dagger \\ldots a_{a_n}^\\dagger a_{i_n} \\ldots a_{i_2} a_{i_1}.\n \\end{align*}\n$$\n\n## A quick tour of Coupled Cluster theory\nThe energy is given by\n\n$$\nE_{\\mathrm{CC}} = \\langle\\Phi_0\\vert \\overline{H}\\vert \\Phi_0\\rangle,\n$$\n\nwhere $\\overline{H}$ is a similarity transformed Hamiltonian\n\n$$\n\\begin{align*}\n \\overline{H}&= e^{-\\hat{T}} \\hat{H}_N e^{\\hat{T}} \\\\\n \\hat{H}_N &= \\hat{H} - \\langle\\Phi_0\\vert \\hat{H} \\vert \\Phi_0\\rangle.\n \\end{align*}\n$$\n\n## A quick tour of Coupled Cluster theory\nThe coupled cluster energy is a function of the unknown cluster amplitudes $t_{i_1i_2\\ldots i_n}^{a_1a_2\\ldots a_n}$,\ngiven by the solutions to the amplitude equations\n\n$$\n0 = \\langle\\Phi_{i_1 \\ldots i_n}^{a_1 \\ldots a_n}\\vert \\overline{H}\\vert \\Phi_0\\rangle.\n$$\n\nThe similarity transformed Hamiltonian $\\overline{H}$ is expanded using the Baker-Campbell-Hausdorff expression,\n\n$$\n\\begin{align*}\n \\overline{H}&= \\hat{H}_N + \\left[ \\hat{H}_N, \\hat{T} \\right] + \n \\frac{1}{2} \\left[\\left[ \\hat{H}_N, \\hat{T} \\right], \\hat{T}\\right] + \\ldots \\\\\n & \\quad \\frac{1}{n!} \\left[ \\ldots \\left[ \\hat{H}_N, \\hat{T} \\right], \\ldots \\hat{T} \\right] +\\dots\n \\end{align*}\n$$\n\nand simplified using the connected cluster theorem\n\n$$\n\\overline{H}= \\hat{H}_N + \\left( \\hat{H}_N \\hat{T}\\right)_c + \\frac{1}{2} \\left( \\hat{H}_N \\hat{T}^2\\right)_c\n + \\dots + \\frac{1}{n!} \\left( \\hat{H}_N \\hat{T}^n\\right)_c +\\dots\n$$\n\n## A quick tour of Coupled Cluster theory\nA much used approximation is to truncate the cluster operator $\\hat{T}$ at the $n=2$ level. This defines the so-called singes and doubles approximation to the Coupled Cluster wavefunction, normally shortened to CCSD..\n\nThe coupled cluster wavefunction is now given by\n\n$$\n\\vert \\Psi_{CC}\\rangle = e^{\\hat{T}_1 + \\hat{T}_2} \\vert \\Phi_0\\rangle\n$$\n\nwhere\n\n$$\n\\begin{align*}\n \\hat{T}_1 &= \n \\sum_{ia}\n t_{i}^{a} a_{a}^\\dagger a_i \\\\\n \\hat{T}_2 &= \\frac{1}{4} \n \\sum_{ijab}\n t_{ij}^{ab} a_{a}^\\dagger a_{b}^\\dagger a_{j} a_{i}.\n \\end{align*}\n$$\n\n## A quick tour of Coupled Cluster theory\nThe amplutudes $t$ play a role similar to the coefficients $C$ in the shell-model calculations. They are obtained by solving a set of non-linear equations\nsimilar to those discussed above in connection withe FCI discussion.\n\nIf we truncate our equations at the CCSD level, it corresponds to performing a transformation of the Hamiltonian matrix of the following type for a six particle problem (with a two-body Hamiltonian):\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$0p-0h$ $1p-1h$ $2p-2h$ $3p-3h$ $4p-4h$ $5p-5h$ $6p-6h$
$0p-0h$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ 0 0 0 0
$1p-1h$ 0 $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ 0 0 0
$2p-2h$ 0 $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ 0 0
$3p-3h$ 0 $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ 0
$4p-4h$ 0 0 $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$
$5p-5h$ 0 0 0 $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$
$6p-6h$ 0 0 0 0 $\\tilde{x}$ $\\tilde{x}$ $\\tilde{x}$
\n\n## A quick tour of Coupled Cluster theory\nIn our FCI discussion the correlation energy is defined as, with a two-body Hamiltonian,\n\n$$\n\\Delta E=\\sum_{ai}\\langle i| \\hat{f}|a \\rangle C_{i}^{a}+\n\\sum_{abij}\\langle ij | \\hat{v}| ab \\rangle C_{ij}^{ab}.\n$$\n\nIn Coupled cluster theory it becomes (irrespective of level of truncation of $T$)\n\n$$\n\\Delta E=\\sum_{ai}\\langle i| \\hat{f}|a \\rangle t_{i}^{a}+\n\\sum_{abij}\\langle ij | \\hat{v}| ab \\rangle t_{ij}^{ab}.\n$$\n\n## A quick tour of Coupled Cluster theory\nCoupled cluster theory has several interesting computational features and is the method of choice in quantum chemistry. The method was originally proposed by Coester and Kummel, two nuclear physicists (way back in the fifties). It came back in full strength in nuclear physics during the last decade. \n\nThere are several interesting features:\n* With a truncation like CCSD or CCSDT, we can include to infinite order correlations like $2p-2h$.\n\n* We can include a large basis of single-particle states, not possible in standard FCI calculations\n\nHowever, Coupled Cluster theory is\n* non-variational\n\n* if we want to find properties of excited states, additional calculations via for example equation of motion methods are needed\n\n* if correlations are strong, a single-reference ansatz may not be the best starting point\n\n* we cannot quantify properly the error we make when truncations are made in the cluster operator\n\n## The CCD approximation\n\nWe will now approximate the cluster operator $\\hat{T}$ to include only $2p-2h$ correlations. This leads to the so-called CCD approximation, that is\n\n$$\n\\hat{T}\\approx \\hat{T}_2=\\frac{1}{4}\\sum_{abij}t_{ij}^{ab}a^{\\dagger}_aa^{\\dagger}_ba_ja_i,\n$$\n\nmeaning that we have\n\n$$\n\\vert \\Psi_0 \\rangle \\approx \\vert \\Psi_{CCD} \\rangle = \\exp{\\left(\\hat{T}_2\\right)}\\vert \\Phi_0\\rangle.\n$$\n\n## The CCD approximation\nInserting these equations in the expression for the computation of the energy we have,\nwith a Hamiltonian defined with respect to a general vacuum (see the exercises in the second quantization part)\n\n$$\n\\hat{H}=\\hat{H}_N+E_{\\mathrm{ref}},\n$$\n\nwith\n\n$$\n\\hat{H}_N=\\sum_{pq}\\langle p \\vert \\hat{f} \\vert q \\rangle a^{\\dagger}_pa_q + \\frac{1}{4}\\sum_{pqrs}\\langle pq \\vert \\hat{v} \\vert rs \\rangle a^{\\dagger}_pa^{\\dagger}_qa_sa_r,\n$$\n\nwe obtain that the energy can be written as\n\n$$\n\\langle \\Phi_0 \\vert \\exp{-\\left(\\hat{T}_2\\right)}\\hat{H}_N\\exp{\\left(\\hat{T}_2\\right)}\\vert \\Phi_0\\rangle =\n\\langle \\Phi_0 \\vert \\hat{H}_N(1+\\hat{T}_2)\\vert \\Phi_0\\rangle = E_{CCD}.\n$$\n\n## The CCD approximation\nThis quantity becomes\n\n$$\nE_{CCD}=E_{\\mathrm{ref}}+\\frac{1}{4}\\sum_{abij}\\langle ij \\vert \\hat{v} \\vert ab \\rangle t_{ij}^{ab},\n$$\n\nwhere the latter is the correlation energy from this level of approximation of CC theory. \nSimilarly, the expression for the amplitudes reads\n\n$$\n\\langle \\Phi_{ij}^{ab} \\vert \\exp{-\\left(\\hat{T}_2\\right)}\\hat{H}_N\\exp{\\left(\\hat{T}_2\\right)}\\vert \\Phi_0\\rangle = 0.\n$$\n\n## The CCD approximation\nThese equations can be reduced to (after several applications of Wick's theorem) to, for all $i > j$ and all $a > b$,\n\n$$\n0 = \\langle ab \\vert \\hat{v} \\vert ij \\rangle + \\left(\\epsilon_a+\\epsilon_b-\\epsilon_i-\\epsilon_j\\right)t_{ij}^{ab} \\nonumber\n$$\n\n$$\n+\\frac{1}{2}\\sum_{cd} \\langle ab \\vert \\hat{v} \\vert cd \\rangle t_{ij}^{cd}+\\frac{1}{2}\\sum_{kl} \\langle kl \\vert \\hat{v} \\vert ij \\rangle t_{kl}^{ab}+\\hat{P}(ij\\vert ab)\\sum_{kc} \\langle kb \\vert \\hat{v} \\vert cj \\rangle t_{ik}^{ac} \\nonumber\n$$\n\n$$\n+\\frac{1}{4}\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert cd \\rangle t_{ij}^{cd}t_{kl}^{ab}+\\hat{P}(ij)\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert cd \\rangle t_{ik}^{ac}t_{jl}^{bd} \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} \n-\\frac{1}{2}\\hat{P}(ij)\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert cd \\rangle t_{ik}^{dc}t_{lj}^{ab}-\\frac{1}{2}\\hat{P}(ab)\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert cd \\rangle t_{lk}^{ac}t_{ij}^{db},\n\\label{eq:ccd} \\tag{1}\n\\end{equation}\n$$\n\nwhere we have defined\n\n$$\n\\hat{P}\\left(ab\\right)= 1-\\hat{P}_{ab},\n$$\n\nwhere $\\hat{P}_{ab}$ interchanges two particles occupying the quantum numbers $a$ and $b$. \n\n## The CCD approximation\nThe operator $\\hat{P}(ij\\vert ab)$ is defined as\n\n$$\n\\hat{P}(ij\\vert ab) = (1-\\hat{P}_{ij})(1-\\hat{P}_{ab}).\n$$\n\nRecall also that the unknown amplitudes $t_{ij}^{ab}$\nrepresent anti-symmetrized matrix elements, meaning that they obey the same symmetry relations as the two-body interaction, that is\n\n$$\nt_{ij}^{ab}=-t_{ji}^{ab}=-t_{ij}^{ba}=t_{ji}^{ba}.\n$$\n\nThe two-body matrix elements are also anti-symmetrized, meaning that\n\n$$\n\\langle ab \\vert \\hat{v} \\vert ij \\rangle = -\\langle ab \\vert \\hat{v} \\vert ji \\rangle= -\\langle ba \\vert \\hat{v} \\vert ij \\rangle=\\langle ba \\vert \\hat{v} \\vert ji \\rangle.\n$$\n\nThe non-linear equations for the unknown amplitudes $t_{ij}^{ab}$ are solved iteratively. We discuss the implementation of these equations below.\n\n## Approximations to the full CCD equations\n\nIt is useful to make approximations to the equations for the amplitudes. The standard method for solving these equations is to set up an iterative scheme where method's like Newton's method or similar root searching methods are used to find the amplitudes. \nItreative solvers need a guess for the amplitudes. A good starting point is to use the correlated wave operator from perturbation theory to\nfirst order in the interaction.\nThis means that we define the zeroth approximation to the amplitudes as\n\n$$\nt^{(0)}=\\frac{\\langle ab \\vert \\hat{v} \\vert ij \\rangle}{\\left(\\epsilon_i+\\epsilon_j-\\epsilon_a-\\epsilon_b\\right)},\n$$\n\nleading to our first approximation for the correlation energy at the CCD level to be equal to second-order perturbation theory without $1p-1h$ excitations, namely\n\n$$\n\\Delta E_{\\mathrm{CCD}}^{(0)}=\\frac{1}{4}\\sum_{abij} \\frac{\\langle ij \\vert \\hat{v} \\vert ab \\rangle \\langle ab \\vert \\hat{v} \\vert ij \\rangle}{\\left(\\epsilon_i+\\epsilon_j-\\epsilon_a-\\epsilon_b\\right)}.\n$$\n\n## Approximations to the full CCD equations\nWith this starting point, we are now ready to solve Eq. ([eq:ccd](#eq:ccd)) iteratively. Before we attack the full equations, it is however instructive to study a truncated version of the equations. We will first study the following approximation where we take away all terms except the linear terms that involve the single-particle energies and the the two-particle intermediate excitations, that is\n\n\n
\n\n$$\n\\begin{equation}\n0 = \\langle ab \\vert \\hat{v} \\vert ij \\rangle + \\left(\\epsilon_a+\\epsilon_b-\\epsilon_i-\\epsilon_j\\right)t_{ij}^{ab}+\\frac{1}{2}\\sum_{cd} \\langle ab \\vert \\hat{v} \\vert cd \\rangle t_{ij}^{cd}.\n\\label{eq:ccd1} \\tag{2}\n\\end{equation}\n$$\n\n## Approximations to the full CCD equations\nSetting the single-particle energies for the hole states equal to an energy variable $\\omega = \\epsilon_i+\\epsilon_j$, Eq. ([eq:ccd1](#eq:ccd1)) reduces to the\nwell-known equations for the so-called $G$-matrix, widely used in [infinite matter and finite nuclei studies](http://www.sciencedirect.com/science/journal/03701573/261/3-4). The equation can then be reordered and solved by matrix inversion. To see this let us define the following quantity\n\n$$\n\\tau_{ij}^{ab}= \\left(\\omega-\\epsilon_a-\\epsilon_b\\right)t_{ij}^{ab},\n$$\n\nand inserting\n\n$$\n1=\\frac{\\left(\\omega-\\epsilon_c-\\epsilon_d\\right)}{\\left(\\omega-\\epsilon_c-\\epsilon_d\\right)},\n$$\n\nin the intermediate sums over $cd$ in Eq. ([eq:ccd1](#eq:ccd1)), we can rewrite the latter equation as\n\n$$\n\\tau_{ij}^{ab}(\\omega)= \\langle ab \\vert \\hat{v} \\vert ij \\rangle + \\frac{1}{2}\\sum_{cd} \\langle ab \\vert \\hat{v} \\vert cd \\rangle \\frac{1}{\\omega-\\epsilon_c-\\epsilon_d}\\tau_{ij}^{cd}(\\omega),\n$$\n\nwhere we have indicated an explicit energy dependence. This equation, transforming a two-particle configuration into a single index, can be transformed into a matrix inversion problem. Solving the equations for a fixed energy $\\omega$ allows us to compare directly with results from Green's function theory when only two-particle intermediate states are included. \n\n## Approximations to the full CCD equations\nTo solve Eq. ([eq:ccd1](#eq:ccd1)), we would thus start with a guess for the unknown amplitudes, typically using the wave operator defined by first order in perturbation theory, leading to a zeroth approximation to the energy given by second-order perturbation theory for the correlation energy.\nA simple approach to the solution of Eq. ([eq:ccd1](#eq:ccd1)), is to thus to\n1. Start with a guess for the amplitudes and compute the zeroth approximation to the correlation energy\n\n2. Use the ansatz for the amplitudes to solve Eq. ([eq:ccd1](#eq:ccd1)) via for example your root-finding method of choice (Newton's method or modifications thereof can be used) and continue these iterations till the correlation energy does not change more than a prefixed quantity $\\lambda$; $\\Delta E_{\\mathrm{CCD}}^{(i)}-\\Delta E_{\\mathrm{CCD}}^{(i-1)} \\le \\lambda$.\n\n3. It is common during the iterations to scale the amplitudes with a parameter $\\alpha$, with $\\alpha \\in (0,1]$ as $t^{(i)}=\\alpha t^{(i)}+(1-\\alpha)t^{(i-1)}$.\n\n## Approximations to the full CCD equations\nThe next approximation is to include the two-hole term in Eq. ([eq:ccd](#eq:ccd)), a term which allow us to make a link with Green's function theory with two-particle and two-hole correlations. This means that we solve\n\n\n
\n\n$$\n\\begin{equation}\n0 = \\langle ab \\vert \\hat{v} \\vert ij \\rangle + \\left(\\epsilon_a+\\epsilon_b-\\epsilon_i-\\epsilon_j\\right)t_{ij}^{ab}+\\frac{1}{2}\\sum_{cd} \\langle ab \\vert \\hat{v} \\vert cd \\rangle t_{ij}^{cd}+\\frac{1}{2}\\sum_{kl} \\langle kl \\vert \\hat{v} \\vert ij \\rangle t_{kl}^{ab}.\n\\label{eq:ccd2} \\tag{3}\n\\end{equation}\n$$\n\nThis equation is solved the same way as we would do for Eq. ([eq:ccd1](#eq:ccd1)). The final step is then to include all terms in Eq. ([eq:ccd](#eq:ccd)). \n\n\n## Introduction to studies of infinite matter\n\n\nStudies of infinite nuclear matter play an important role in nuclear physics. The aim of this part of the lectures is to provide the necessary ingredients for perfoming studies of neutron star matter (or matter in $\\beta$-equilibrium) and symmetric nuclear matter. \n\nHere we will study infinite neutron matter \n* at the Hartree-Fock with realistic nuclear forces and\n\n* using many-body methods like coupled-cluster theory or many-body perturbation theory\n\n## Infinite nuclear matter and neutron star matter\n\nStudies of dense baryonic matter are of central importance to our basic understanding \nof the stability of nuclear matter, spanning from matter at high densities and temperatures\nto matter as found within dense astronomical objects like neutron stars. \n\nNeutron star matter\nat densities of 0.1 fm$^{-3}$ and greater, is often assumed to \nbe made of mainly neutrons, protons, electrons and \nmuons in beta equilibrium. However, other baryons like various hyperons may exist, as well as possible mesonic condensates and transitions to quark degrees of freedom at higher densities. \nHere we focus on specific definitions of various phases and focus \non distinct phases of matter such as pure baryonic\nmatter and/or quark matter.\nThe composition of matter is then \ndetermined by the requirements of chemical and electrical equilibrium.\nFurthermore, we will also consider matter at temperatures much lower\nthan the typical Fermi energies.\n\n## Properties of infinite nuclear matter\n\nThe equilibrium conditions are governed by the weak processes \n(normally referred to as the processes\nfor $\\beta$-equilibrium)\n\n\n
\n\n$$\n\\begin{equation} \n b_1 \\rightarrow b_2 + l +\\bar{\\nu}_l \\hspace{1cm} b_2 +l \\rightarrow b_1 \n+\\nu_l,\n\\label{eq:betadecay} \\tag{4}\n\\end{equation}\n$$\n\nwhere $b_1$ and $b_2$ refer to for example the baryons being a neutron and a proton, \nrespectively, \n$l$ is either an electron or a muon and $\\bar{\\nu}_l $\nand $\\nu_l$ their respective anti-neutrinos and neutrinos. Muons typically \nappear at\na density close to nuclear matter saturation density, the latter being\n\n$$\nn_0 \\approx 0.16 \\pm 0.02 \\hspace{1cm} \\mathrm{fm}^{-3},\n$$\n\nwith a corresponding binding energy $E_0$ \nfor symmetric nuclear matter (SNM) at saturation density of\n\n$$\nE_0 = B/A=-15.6\\pm 0.2 \\hspace{1cm} \\mathrm{MeV}.\n$$\n\n## The infinite neutron gas as a homogenous system\n\nThis is a homogeneous system and the one-particle wave functions are given by plane wave functions normalized to a volume $\\Omega$ \nfor a box with length $L$ (the limit $L\\rightarrow \\infty$ is to be taken after we have computed various expectation values)\n\n$$\n\\psi_{\\mathbf{k}\\sigma}(\\mathbf{r})= \\frac{1}{\\sqrt{\\Omega}}\\exp{(i\\mathbf{kr})}\\xi_{\\sigma}\n$$\n\nwhere $\\mathbf{k}$ is the wave number and $\\xi_{\\sigma}$ is a spin function for either spin up or down\n\n$$\n\\xi_{\\sigma=+1/2}=\\left(\\begin{array}{c} 1 \\\\ 0 \\end{array}\\right) \\hspace{0.5cm}\n\\xi_{\\sigma=-1/2}=\\left(\\begin{array}{c} 0 \\\\ 1 \\end{array}\\right).\n$$\n\n## Periodic boundary conditions and single-particle states\n\nWhen using periodic boundary conditions, the \ndiscrete-momentum single-particle basis functions\n\n$$\n\\phi_{\\mathbf{k}}(\\mathbf{r}) =\ne^{i\\mathbf{k}\\cdot \\mathbf{r}}/L^{d/2}\n$$\n\nare associated with \nthe single-particle energy\n\n\n
\n\n$$\n\\begin{equation}\n \\varepsilon_{n_{x}, n_{y}} = \\frac{\\hbar^{2}}{2m} \\left( \\frac{2\\pi }{L}\\right)^{2}\\left( n_{x}^{2} + n_{y}^{2}\\right)\n\\label{_auto1} \\tag{5}\n\\end{equation}\n$$\n\nfor two-dimensional sytems and\n\n\n
\n\n$$\n\\begin{equation}\n \\varepsilon_{n_{x}, n_{y}, n_{z}} = \\frac{\\hbar^{2}}{2m}\n \\left( \\frac{2\\pi }{L}\\right)^{2}\n \\left( n_{x}^{2} + n_{y}^{2} + n_{z}^{2}\\right)\n\\label{_auto2} \\tag{6}\n\\end{equation}\n$$\n\nfor three-dimensional systems.\n\n## More on periodic boundary conditions and single-particle states\n\nThe table on the next slide illustrates how single-particle energies\n fill energy shells in a two-dimensional neutron box.\n Here $n_{x}$ and $n_{y}$ are the momentum quantum numbers,\n $n_{x}^{2} + n_{y}^{2}$ determines the single-particle \n energy level, $N_{\\uparrow \\downarrow }$ represents the \n cumulated number of spin-orbitals in an unpolarized spin\n phase, and $N_{\\uparrow \\uparrow }$ stands for the\n cumulated number of spin-orbitals in a spin-polarized\n system.\n\n\n\n## Magic numbers for the two-dimensional neutron (or electron) gas\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$n_{x}^{2}+n_{y}^{2}$ $n_{x}$ $n_{y}$ $N_{\\uparrow \\downarrow }$ $N_{\\uparrow \\uparrow }$
0 0 0 2 1
1 -1 0
1 0
0 -1
0 1 10 5
2 -1 -1
-1 1
1 -1
1 1 18 9
4 -2 0
2 0
0 -2
0 2 26 13
5 -2 -1
2 -1
-2 1
2 1
-1 -2
-1 2
1 -2
1 2 42 21
\n\n\n\n## Three-dimensional neutron gas\nUsing the same approach as made with the two-dimensional electron gas with the single-particle kinetic energy defined as\n\n$$\n\\frac{\\hbar^2}{2m}\\left(k_{n_x}^2+k_{n_y}^2k_{n_z}^2\\right),\n$$\n\nand\n\n$$\nk_{n_i}=\\frac{2\\pi n_i}{L} \\hspace{0.1cm} n_i = 0, \\pm 1, \\pm 2, \\dots,\n$$\n\nwe can set up a similar table and obtain (assuming identical particles one and including spin up and spin down solutions) for energies less than or equal to $n_{x}^{2}+n_{y}^{2}+n_{z}^{2}\\le 3$\n\n\n## Single-particle states for the three-dimensional neutron gas\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
$n_{x}^{2}+n_{y}^{2}+n_{z}^{2}$ $n_{x}$ $n_{y}$ $n_{z}$ $N_{\\uparrow \\downarrow }$
0 0 0 0 2
1 -1 0 0
1 1 0 0
1 0 -1 0
1 0 1 0
1 0 0 -1
1 0 0 1 14
2 -1 -1 0
2 -1 1 0
2 1 -1 0
2 1 1 0
2 -1 0 -1
2 -1 0 1
2 1 0 -1
2 1 0 1
2 0 -1 -1
2 0 -1 1
2 0 1 -1
2 0 1 1 38
3 -1 -1 -1
3 -1 -1 1
3 -1 1 -1
3 -1 1 1
3 1 -1 -1
3 1 -1 1
3 1 1 -1
3 1 1 1 54
\nContinuing in this way we get for $n_{x}^{2}+n_{y}^{2}+n_{z}^{2}=4$ a total of 12 additional states, resulting in $?$ as a new magic number. We can continue like this by adding more shells.\n\nWhen performing calculations based on many-body perturbation theory, Coupled cluster theory or other many-body methods, we need then to add states above the Fermi level in order to sum over single-particle states which are not occupied. \n\n\n\n\n## Input parameters\nEvery number of particles for filled shells defines also the number of particles to be used in a given calculation. We use the number of particles to define the density of the system\n\n$$\n\\rho = g \\frac{k_F^3}{6\\pi^2},\n$$\n\nwhere you need to define $k_F$ and the degeneracy $g$, which is two for one type of spin-$1/2$ particles and four for symmetric nuclear matter.\n\nWith the density we can define the length $L$ of the box used with periodic boundary contributions, that is use the relation\n\n$$\nV= L^3= \\frac{A}{\\rho}.\n$$\n\nFinally we can use $L$ to define the spacing to set up the spacing between varipus $k$-values, that is\n\n$$\n\\Delta k = \\frac{2\\pi}{L}.\n$$\n\nHere, $A$ can be the number of nucleons. \n\n## Potential model employed in code development\n\nThe interaction we will use for these calculations is a semirealistic\nnucleon-nucleon potential known as the Minnesota potential\n\n$$\nV_{\\alpha}\\left(r\\right)=V_{\\alpha}\\exp{(-\\alpha r^{2})}.\n$$\n\nThe spin and isospin\ndependence of the Minnesota potential is given by\n\n\n
\n\n$$\n\\begin{equation}\nV\\left( r\\right)=\\frac{1}{2}\\left( V_{R}+\\frac{1}{2}\\left(1+P_{12}^{\\sigma}\\right) V_{T}+\\frac{1}{2}\\left(1-P_{12}^{\\sigma}\\right) V_{S}\\right)\\left(1-P_{12}^{\\sigma}P_{12}^{\\tau}\\right),\n\\label{_auto3} \\tag{7}\n\\end{equation}\n$$\n\nwhere\n\n$$\nP_{12}^{\\sigma}=\\frac{1}{2}\\left(1+\\sigma_{1}\\cdot\\sigma_{2}\\right),\n$$\n\nand\n\n$$\nP_{12}^{\\tau}=\\frac{1}{2}\\left( 1+\\tau_{1}\\cdot\\tau_{2}\\right)\n$$\n\nare\nthe spin and isospin exchange operators, respectively. \n\n## Fourier transform\nA Fourier\ntransform to momentum space of the radial part\n\n$$\nV_{\\alpha}\\left(r\\right)\n$$\n\nis rather simple since\nthe radial depends only on the magnitude of the relative distance and\nthereby the relative momentum\n\n$$\n\\mathbf{q}=\\frac{1}{2}\\left(\\mathbf{k}_{p}-\\mathbf{k}_{q}-\\mathbf{k}_{r}+\\mathbf{k}_{s}\\right)\n$$\n\nOmitting spin and isospin dependencies, the momentum space version of the\ninteraction reads\n\n\n
\n\n$$\n\\begin{equation}\n\\langle \\mathbf{k}_p \\mathbf{k}_q \\vert V_{\\alpha}\\vert\\mathbf{k}_r\\mathbf{k}_s\\rangle=\n\\frac{V_{\\alpha}}{L^{3}}\\left(\\frac{\\pi}{\\alpha}\\right)^{3/2}\\exp{(\\frac{-q^{2}}{4\\alpha})}\\delta_{\\mathbf{k}_{p}+\\mathbf{k}_{q},\\mathbf{k}_{r}+\\mathbf{k}_{s}}\n\\label{_auto4} \\tag{8}\n\\end{equation}\n$$\n\n## Developing a program for infinite matter\n\n* Structure a code in terms of functions.\n\n* Modularize your codes.\n\n* Be able to read input data flexibly.\n\n* Write unit tests (test functions) and let your code undergo heavy testing.\n\n* Refactor code in terms of classes (instead of functions only).\n\n* Conduct and automate large-scale numerical experiments.\n\n* New code is added in a modular fashion to a library (modules).\n\n* Programs are run through convenient user interfaces.\n\n* Use scripts in order to automatize tedious manual work.\n\n* Make sure your scientific investigations are reproducible and document properly your results.\n\n* Use version control software like for example **git**\n\n## Codes and reading material\n\n* The codes are all available from the coming Lectures Notes in Physics volume [An advanced course in computational nuclear physics: Bridging the scales from quarks to neutron stars, M. Hjorth-Jensen, M. P. Lombardo, U. van Kolck, Editors](https://github.com/ManyBodyPhysics/LectureNotesPhysics/tree/master/doc/src/Chapter8-programs)\n\n* For more reading on CCD see chapter 8 of the coming Lectures Notes in Physics volume [An advanced course in computational nuclear physics: Bridging the scales from quarks to neutron stars, M. Hjorth-Jensen, M. P. Lombardo, U. van Kolck, Editors](https://github.com/ManyBodyPhysics/LectureNotesPhysics/tree/master/doc/src/lnp.pdf)\n\n## The CCD equation\nThe CCD equations can be written as\n\n$$\n\\left(\\epsilon_i+\\epsilon_j-\\epsilon_a-\\epsilon_b\\right)t_{ij}^{ab}\n = \\langle ab \\vert \\hat{v} \\vert ij \\rangle \\nonumber\n$$\n\n$$\n+\\frac{1}{2}\\sum_{cd} \\langle ab \\vert \\hat{v} \\vert cd \\rangle\n t_{ij}^{cd}+\\frac{1}{2}\\sum_{kl} \\langle kl \\vert \\hat{v} \\vert ij\n \\rangle t_{kl}^{ab}+\\hat{P}(ij\\vert ab)\\sum_{kc} \\langle kb \\vert\n \\hat{v} \\vert cj \\rangle t_{ik}^{ac} \\nonumber\n$$\n\n$$\n+\\frac{1}{4}\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert cd \\rangle\n t_{ij}^{cd}t_{kl}^{ab}+\\hat{P}(ij)\\sum_{klcd} \\langle kl \\vert\n \\hat{v} \\vert cd \\rangle t_{ik}^{ac}t_{jl}^{bd} \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} -\\frac{1}{2}\\hat{P}(ij)\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert\n cd \\rangle t_{ik}^{dc}t_{lj}^{ab}-\\frac{1}{2}\\hat{P}(ab)\\sum_{klcd}\n \\langle kl \\vert \\hat{v} \\vert cd \\rangle t_{lk}^{ac}t_{ij}^{db},\n\\label{_auto5} \\tag{9}\n\\end{equation}\n$$\n\nfor all $i < j$ and all $a < b$, using the standard notation that\n $a,b,...$ are particle states and $i,j,...$ are hole states. With\n the CCD correlation energy given by\n\n\n
\n\n$$\n\\begin{equation}\n \\Delta E_{CCD} = \\frac{1}{4} \\sum_{ijab}\n \\langle ij \\vert\\hat{v}\\vert ab\\rangle t^{ab}_{ij}.\n\\label{eq:ccdcorr} \\tag{10}\n \\end{equation}\n$$\n\n\n## Solving the CCD equations\n One way to solve these equations, is to write equation\n ([eq:ccd2](#eq:ccd2)) as a series of iterative nonlinear algebraic equations\n\n$$\nt_{ij}^{ab}{}^{(n+1)} = \\frac{1}{\\epsilon^{ab}_{ij}} \\bigg(\\langle\n ab \\vert \\hat{v} \\vert ij \\rangle \\nonumber\n$$\n\n$$\n+\\frac{1}{2}\\sum_{cd} \\langle ab \\vert \\hat{v} \\vert cd \\rangle\n t_{ij}^{cd}{}^{(n)}+\\frac{1}{2}\\sum_{kl} \\langle kl \\vert \\hat{v}\n \\vert ij \\rangle t_{kl}^{ab}{}^{(n)}+\\hat{P}(ij\\vert ab)\\sum_{kc}\n \\langle kb \\vert \\hat{v} \\vert cj \\rangle t_{ik}^{ac}{}^{(n)} \n \\nonumber\n$$\n\n$$\n+\\frac{1}{4}\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert\n cd \\rangle\n t_{ij}^{cd}{}^{(n)}t_{kl}^{ab}{}^{(n)}+\\hat{P}(ij)\\sum_{klcd}\n \\langle kl \\vert \\hat{v} \\vert cd \\rangle\n t_{ik}^{ac}{}^{(n)}t_{jl}^{bd}{}^{(n)} \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} -\\frac{1}{2}\\hat{P}(ij)\\sum_{klcd} \\langle kl \\vert \\hat{v} \\vert\n cd \\rangle\n t_{ik}^{dc}{}^{(n)}t_{lj}^{ab}{}^{(n)}-\\frac{1}{2}\\hat{P}(ab)\\sum_{klcd}\n \\langle kl \\vert \\hat{v} \\vert cd \\rangle\n t_{lk}^{ac}{}^{(n)}t_{ij}^{db}{}^{(n)} \\bigg),\n\\label{eq:ccd3} \\tag{11}\n \\end{equation}\n$$\n\nfor all $i < j$ and all $a < b$, where $\\epsilon^{ab}_{ij} =\\left(\\epsilon_i+\\epsilon_j-\\epsilon_a-\\epsilon_b\\right)$, and\n $t_{ij}^{ab}{}^{(n)}$ is the $t$ amplitude for the nth iteration of\n the series. This way, given some starting guess\n $t_{ij}^{ab}{}^{(0)}$, we can generate subsequent $t$ amplitudes\n that converges to some value. \n\n## Memory considerations\n\n Care should thus be placed into how we store these objects. These are\n objects with four indices and a sensible first implementation\n of the CCD equations would be to create two four-dimensional arrays to store the\n objects. However, it is often more convenient to work with simple\n one-dimensional arrays instead. \n\n The goal of our code is to calculate the correlation energy,\n $\\Delta E_{CCD}$, meaning that after each iteration of our equations, we use\n our newest $t$ amplitudes to update the correlation energy\n\n\n
\n\n$$\n\\begin{equation}\n \\Delta E_{CCD}^{(n)} = \\frac{1}{4} \\sum_{ijab}\n \\langle ij\\vert\\hat{v}\\vert ab\\rangle t^{ab}_{ij}{}^{(n)}.\n\\label{_auto6} \\tag{12}\n\\end{equation}\n$$\n\nWe check that our result is converged by testing whether the\n most recent iteration has changed the correlation energy by less\n than some tolerance threshold $\\eta$,\n\n\n
\n\n$$\n\\begin{equation}\n \\eta > | \\Delta E_{CCD}^{(n+1)} - \\Delta E_{CCD}^{(n)} |.\n\\label{_auto7} \\tag{13}\n\\end{equation}\n$$\n\n## More on memory\n\n One limitation that will be ran into while trying to do realistic\n CCD calculations is that of memory. The four-indexed two-body matrix elements (TBMEs) and\n $t$-amplitudes have to store a lot of elements, and the size of these\n arrays can quickly exceed the available memory on\n a machine. If a calculation wants to use 500 single-particle basis states, then\n a structure like $\\langle pq\\vert v\\vert rs\\rangle $ will need a length of 500 for each of\n its four indices, which means it will have $500^4 = 625\\times 10^8$\n elements. To get a handle on how much memory is used, consider the\n elements as double-precision floating point type. One double takes\n up 8 bytes of memory. This specific array would take up $8\\times 625\\times 10^8$ bytes\n = $5000 \\times 10^8$ bytes = $500$ Gbytes of memory. \n\n\n## Using symmetries\n\nMost personal\n computers in 2016 have 4-8 Gbytes of RAM, meaning that this calculation would\n be way out of reach. There are supercomputers that can handle\n applications using 500 Gbytes of memory, but we can quickly reduce\n the total memory required by applying some physical arguments. In\n addition to vanishing elements with repeated indices, mentioned\n above, elements that do not obey certain symmetries are also\n zero. Almost all realistic two-body forces preserve some quantities\n due to symmetries in the interaction. For example, an interaction\n with rotational symmetry will conserve angular momentum. This means\n that a two-body ket state $\\vert rs\\rangle $, which has some set of quantum\n numbers, will retain quantum numbers corresponding to the\n interaction symmetries after being acted on by $\\hat{v}$. This state\n is then projected onto $\\vert pq\\rangle $ with its own set of quantum\n numbers. Thus $\\langle pq|v|rs\\rangle $ is only non-zero if $\\vert pq\\rangle$ and\n $\\vert rs\\rangle $ share the same quantum numbers that are preserved by\n $\\hat{v}$. In addition, because the cluster operators represent\n excitations due to the interaction, $t_{ij}^{ab}$ is only non-zero\n if $\\vert ij\\rangle $ has the same relevant quantum numbers as $\\vert ab\\rangle $.\n\n\n## Using symmetries II\n\n To take advantage of this, these two-body ket states can be\n organized into \"channels\" of shared quantum numbers. In the case\n of the pairing model, the interaction preserves the total spin\n projection of a two-body state, $S_{z}=s_{z1}+s_{z2}$. The single\n particle states can have spin of +1/2 or -1/2, so there can be three\n two-body channels with $S_{z}=-1,0,+1$. These channels can then be\n indexed with a unique label in a similar way to the single particle\n index scheme. In more complicated systems, there will be many more\n channels involving multiple symmetries, so it is useful to create a\n data structure that stores the relevant two-body quantum numbers to\n keep track of the labeling scheme.\n\n## Using symmetries III\n\n It is more efficient to use two-dimensional array data\n structures, where the first index refers to the channel number and\n the second refers to the element within that channel. So to access\n matrix elements or $t$ amplitudes, you can loop over the channels\n first, then the indices within that channel. To get an idea of the\n savings using this block diagonal structure, let's look at a case\n with a plane wave basis, with three momentum and one spin quantum\n numbers, with an interaction that conserves linear momentum in all\n three dimensions, as well as the total spin projection. Using 502\n basis states, the TBME's require about 0.23 Gb of memory in block\n diagonal form, which is an enormous saving from the 500 Gb mentioned\n earlier in the na\\\"ive storage scheme.\n\n\n## Using intermediates\n\n Since the calculation of all zeros can now be avoided,\n improvements in speed and memory will now follow. To get a handle on\n how these CCD calculations are implemented we need only to look at the\n most expensive sum in equation ([eq:ccd2](#eq:ccd2)). This corresponds to\n the sum over $klcd$. Since this sum is repeated for all $i < j$ and\n $a < b$, it means that these equations will scale as\n $\\mathcal{O}(n_{p}^{4} n_{h}^{4})$. However,\n they can be rewritten using intermediates as\n\n$$\n0 = \\langle ab|\\hat{v}|ij \\rangle + \\hat{P}(ab) \\sum_{c} \\langle b| \\chi\n |c\\rangle \\langle ac| t |ij\\rangle - \\hat{P}(ij) \\sum_{k} \\langle k| \\chi |j\\rangle\n \\langle ab| t |ik\\rangle \\nonumber\n$$\n\n\n
\n\n$$\n\\begin{equation} + \\frac{1}{2}\\sum_{cd} \\langle ab|\n \\chi |cd\\rangle \\langle cd| t |ij\\rangle + \\frac{1}{2} \\sum_{kl} \\langle ab| t\n |kl\\rangle \\langle kl| \\chi |ij\\rangle \n\\label{_auto8} \\tag{14}\n\\end{equation}\n$$\n\n$$\n+ \\hat{P}(ij)\\hat{P}(ab) \\sum_{kc}\n \\langle ac| t |ik\\rangle\\langle kb| \\chi |cj\\rangle \\nonumber\n$$\n\nfor all $i,j,a,b$.\n\n## Defining intermediates\n\nThe intermediates $\\chi$ are defined as\n\n8\n1\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n8\n2\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n8\n3\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n8\n4\n \n<\n<\n<\n!\n!\nM\nA\nT\nH\n_\nB\nL\nO\nC\nK\n\n\n
\n\n$$\n\\begin{equation}\n \\langle ab| \\chi |cd\\rangle = \\langle ab|v|cd\\rangle\n\\label{_auto12} \\tag{19}\n\\end{equation}\n$$\n\nWith the introduction of the above intermediates, the CCD equations scale now as $\\mathcal{O}(n_{h}^{2}n_{p}^{4})$.\n\n## Speed up\n\nTo further speed up these computations, we see that these sums can be\n written in terms of matrix-matrix multiplications. It is not obvious how to\n write all of these sums in such a way, but it is useful to first\n recall that the expression for the multiplication of two matrices $\\hat{C} =\\hat{A}\\times \\hat{B}$ can be written as\n\n\n
\n\n$$\n\\begin{equation}\n C_{ij} = \\sum_{k} A_{ik} \\times B_{kj}.\n\\label{_auto13} \\tag{20}\n\\end{equation}\n$$\n\nWe observe then that equation ([eq:mtxEx](#eq:mtxEx)) can be written as\n \\[\n \\langle K| \\chi |I\\rangle = \\langle K|v|I\\rangle + \\frac{1}{2} \\sum_{C}\n \\langle K|v|C\\rangle \\langle C|t|I\\rangle \n \\]\n by mapping the two index pairs $kl \\to K, ij \\to I, cd \\to C$. The sum looks now \nlike a matrix-matrix multiplication. This is\n useful because there are packages like BLAS (Basic Linear Algebra\n Subprograms) which have extremely fast implementations of\n matrix-matrix multiplication.\n\n\n\n## Testing brute force against block structures for MBPT(2)\n\n\n\n\n

MBPT2 contribution to the correlation for pure neutron matter with $N=14$ neutrons and periodic boundary conditions. Up to approximately 1600 single-particle states have been included in the sums over intermediate states.

\n\n\n\n\n\n\n## Convergence properties for pure neutron matter I\n\n\n\n\n

Energy per particle of pure neutron matter computed in the CCD approximation with the Minnesota potential for different numbers of particles with $\\mathrm{N_{max}=20}$.

\n\n\n\n\n\n\n## Convergence properties for pure neutron matter II\n\n\n\n\n\n

Energy per particle of pure neutron matter computed in the CCD approximation with the Minnesota potential for different model space sizes with $\\mathrm{A=114}$.

\n\n\n\n\n\n\n\n## Comparing CCD with Monte Carlo\n\n\n\n\n

CCD, Reference energy and Diffusion Monte Carlo results for pure neutron matter with $66$ neutrons and $\\mathrm{N_{max}=36}$.

\n\n\n\n", "meta": {"hexsha": "dd374ff21cc07f8ac7db2f20585ea328bfe61297", "size": 84332, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "doc/pub/cc/ipynb/cc.ipynb", "max_stars_repo_name": "ManyBodyPhysics/AbInitioNuclearPhysicsSchool", "max_stars_repo_head_hexsha": "bf804f866e6391905c62de761abbb214bb9b2dbd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-06-19T15:29:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T01:33:13.000Z", "max_issues_repo_path": "doc/pub/cc/ipynb/cc.ipynb", "max_issues_repo_name": "ManyBodyPhysics/AbInitioNuclearPhysicsSchool", "max_issues_repo_head_hexsha": "bf804f866e6391905c62de761abbb214bb9b2dbd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/pub/cc/ipynb/cc.ipynb", "max_forks_repo_name": "ManyBodyPhysics/AbInitioNuclearPhysicsSchool", "max_forks_repo_head_hexsha": "bf804f866e6391905c62de761abbb214bb9b2dbd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2018-07-19T08:45:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T14:24:12.000Z", "avg_line_length": 40.7992259313, "max_line_length": 443, "alphanum_fraction": 0.5197789688, "converted": true, "num_tokens": 17958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3208142509540299}} {"text": "\n\n# ***InfoSelect*** - Mutual Information Based Feature Selection in Python\n\n\n\n\n### *Felipe Maia Polo (felipemaiapolo), Felipe Leno da Silva (f-leno)*\n\n\n## Contents\n1. [ Introduction ](#1)\n2. [ Installing *InfoSelect* ](#2)\n3. [ Main functionalities of *InfoSelect* ](#3)\n4. [ Examples of *InfoSelect* use ](#4)\n5. [ References ](#5)\n\n--------------\n\n\n## 1\\. Introduction \n\nIn this package we implement the ideas proposed by [1, 2] in order to make variable/feature selection prior to regression and classification tasks using Gaussian Mixture Models (GMMs) to estimate the Mutual Information between labels and features. This is an efficient and well-performing alternative and was used in a recent work [3] by one of us.\n\nIf you use our package in your research, you can cite it as follows:\n\n @misc{polo2020infoselect,\n title={InfoSelect - Mutual Information Based Feature Selection in Python},\n author={Polo, Felipe Maia and Da Silva, Felipe Leno},\n journal={GitHub: github.com/felipemaiapolo/infoselect},\n year={2020}\n }\n\n\n--------------\n\n\n## 2\\. Installing *InfoSelect* \n\nYou can install the package from\n[PyPI](https://pypi.org/project/infoselect/)\n\n\n```python\n!pip install infoselect\n```\n\n Requirement already satisfied: infoselect in /usr/local/lib/python3.6/dist-packages (1.0.0)\n Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from infoselect) (1.1.4)\n Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from infoselect) (3.2.2)\n Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from infoselect) (1.4.1)\n Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from infoselect) (1.18.5)\n Requirement already satisfied: sklearn in /usr/local/lib/python3.6/dist-packages (from infoselect) (0.0)\n Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->infoselect) (2018.9)\n Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.6/dist-packages (from pandas->infoselect) (2.8.1)\n Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->infoselect) (0.10.0)\n Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->infoselect) (2.4.7)\n Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->infoselect) (1.3.1)\n Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from sklearn->infoselect) (0.22.2.post1)\n Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.7.3->pandas->infoselect) (1.15.0)\n Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->sklearn->infoselect) (0.17.0)\n\n\n\n## 3\\. Main functionalities of *InfoSelect* \n\n\n### 3.1\\. Main Class `SelectVars`\n\nThis class is used to order features/variables according to their importance and making the selection itself. Next we detail its methods:\n\n1. `__init__(self, gmm, selection_mode = 'forward')`\n - **gmm**: \n - If is *non*-categorical: a [Scikit-Learn GMM](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html) fitted in (y,X) - y should always be in the first column;\n - If is categorical: a Python dictionary containing one [Scikit-Learn GMM](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html) fitted in X conditional on each category - something like X[y==c,:]. Format `{0:gmm0, 1:gmm1, ..., C:gmmC}`;\n - PS: the GMMs must be `covariance_type='full'` at the current *InfoSelect* version.\n - **selection_mode**: `forward`/`backward` algorithms.\n - `forward` selection: we start with an empty set of features and then select the feature that has the largest estimated mutual information with the target variable and. At each subsequent step, we select the feature that marginally maximizes the estimated mutual information of the target and all the chosen features so far. We stop when we have selected/ordered all the features;\n - `backward` elimination: we start with the full set of features and then at each step, we eliminate the feature that marginally maximizes the estimated mutual information of the target and all the remaining features. We stop when we have no more features to eliminate;\n\n2. `fit(self, X, y, verbose=True, eps=0)`\n - **X**: numpy array of features; \n - **y**: numpy array of labels;\n - **verbose**: print or not to print!?\n - **eps**: small value so we can avoid taking log of zero in some cases .\n\n3. `get_info(self)`: \n - This function creates and outputs a Pandas DataFrame with the history of feature selection/elimination. The `mi_mean` column gives the estimated Mutual Information while `mi_error` gives the standard error of that estimate. On the other hand, the `delta` column gives us the percentual information loss/gain in that round, relatively to the latter;\n \n4. `plot_delta(self)`: \n - This function plots the history of percentual changes in the mutual information.\n \n5. `plot_mi(self)`: \n - This function plots the history of the mutual information.\n \n6. `transform(self, X, rd)`: \n - This function takes **X** and transforms it in **X_new**, maintaining the features of Round `rd`; \n \n\n### 3.2\\. Auxiliary Function `get_gmm`\n\n1. `get_gmm(X, y, y_cat=False, num_comps=[2,5,10,15,20], val_size=0.33, reg_covar=1e-06, random_state=42)`: \n\n - Firstly, this function validate the number of GMM components, for each model it will train, in a holdout set using the mean log likelihood of samples in that set. If Y is non-categorical, it returns a [Scikit-Learn GMM](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html) fitted in (y,X) model (in this order). On the other hand, if Y is categorical it returns a Python dictionary containing one [Scikit-Learn GMM](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html) fitted in X conditional on each category - something like X[y==c,:]. Format `{0:gmm0, 1:gmm1, ..., C:gmmC}`.\n\n - **X**: numpy array of features; \n - **y**: numpy array of labels;\n - **y_cat**: if we should consider Y as categorical;\n - **num_comps**: numbers of GMM components to be validated;\n - **val_size**: size of holdout set used to validate the GMMs numbers of components;\n - **reg_covar**: non-negative regularization added to the diagonal of covariance. Ensures the covariance matrices are non-singular.\n - **random_state**: seed.\n\n--------------------\n\n\n## 4\\. Examples of *InfoSelect* use\n\nLoading Packages:\n\n\n```python\nimport infoselect as inf\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n```\n\n### 1.1\\. Dataset\n\nWe generate a dataset $D$ sampled from $\\mathcal{D}=\\{(X_{0,i},...,X_{6,i},Y_i)\\}_{i=1}^{n}$ similar to the one in [here](https://www.cs.toronto.edu/~delve/data/add10/desc.html), in which $Y_i$ is given by\n\n
\n\\begin{align}\nY_i &= f(X_{0,i},...,X_{6,i}) + \\epsilon_i \\\\[.5em]\n&=10\\cdot \\sin(\\pi X_{0,i} X_{1,i}) + 20 (X_{2,i}-0.5)^2 + 10 X_{3,i} + 5 X_{4,i} + \\epsilon_i\n\\end{align}\n
\n\nWhere $X_{0,i},...,X_{6,i} \\overset{iid}{\\sim} U[0,1]$ and $\\epsilon_i \\sim N(0,1)$ independent from all the other random variables for all $i\\in [n]$. In the following we set $n=20000$:\n\n\n```python\ndef f(X,e): return 10*np.sin(np.pi*X[:,0]*X[:,1]) + 20*(X[:,2]-.5)**2 + 10*X[:,3] + 5*X[:,4] + e\n```\n\n\n```python\nn=20000\nd=7\n\nX = np.random.uniform(0,1,d*n).reshape((n,d))\ne = np.random.normal(0,1,n)\ny = f(X,e)\n\nX.shape, y.shape\n```\n\n\n\n\n ((20000, 7), (20000,))\n\n\n\n### 1.2\\. Selecting Features for a Regression Task\n\nTraining (and validating) GMM:\n\n\n```python\n%%time\n\ngmm = inf.get_gmm(X, y)\n```\n\n CPU times: user 27.5 s, sys: 18.2 s, total: 45.7 s\n Wall time: 23.4 s\n\n\n\n```python\ngmm\n```\n\n\n\n\n GaussianMixture(covariance_type='full', init_params='kmeans', max_iter=100,\n means_init=None, n_components=20, n_init=1,\n precisions_init=None, random_state=42, reg_covar=1e-06,\n tol=0.001, verbose=0, verbose_interval=10, warm_start=False,\n weights_init=None)\n\n\n\nOrdering features by their importances using the *Backward Elimination* algorithm:\n\n\n```python\nselect = inf.SelectVars(gmm, selection_mode = 'backward')\nselect.fit(X, y, verbose=True) \n```\n\n Let's start...\n \n Round = 0 | Î = 1.48 | Δ%Î = 0.00 | Features=[0, 1, 2, 3, 4, 5, 6]\n Round = 1 | Î = 1.48 | Δ%Î = -0.00 | Features=[0, 1, 2, 3, 4, 5]\n Round = 2 | Î = 1.48 | Δ%Î = -0.00 | Features=[0, 1, 2, 3, 4]\n Round = 3 | Î = 1.00 | Δ%Î = -0.32 | Features=[0, 1, 3, 4]\n Round = 4 | Î = 0.75 | Δ%Î = -0.25 | Features=[0, 1, 3]\n Round = 5 | Î = 0.39 | Δ%Î = -0.48 | Features=[1, 3]\n Round = 6 | Î = 0.21 | Δ%Î = -0.46 | Features=[3]\n\n\nChecking history:\n\n\n```python\nselect.get_info()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
roundsmi_meanmi_errordeltanum_featfeatures
001.4839690.0061470.0000007[0, 1, 2, 3, 4, 5, 6]
111.4831010.006139-0.0005856[0, 1, 2, 3, 4, 5]
221.4816670.006135-0.0009675[0, 1, 2, 3, 4]
331.0012920.005613-0.3242124[0, 1, 3, 4]
440.7519520.005343-0.2490183[0, 1, 3]
550.3901380.005015-0.4811662[1, 3]
660.2122570.003765-0.4559461[3]
\n
\n\n\n\nIt is possible to see that the estimated mutual information is untouched until Round 2, when it varies around -$30\\%$.\n\nSince there is a 'break' in Round 2, we should choose to stop the algorithm at theta round. This will be clear in the Mutual Information history plot that follows:\n\n\n```python\nselect.plot_mi()\n```\n\nPlotting the percentual variations of the mutual information between rounds:\n\n\n```python\nselect.plot_delta()\n```\n\nMaking the selection choosing to stop at Round 2:\n\n\n```python\nX_new = select.transform(X, rd=2)\n\nX_new.shape\n```\n\n\n\n\n (20000, 5)\n\n\n\n### 1.3\\. Selecting Features for a Classification Task\n\nCategorizing $Y$:\n\n\n```python\nind0 = (y\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
roundsmi_meanmi_errordeltanum_featfeatures
000.0000000.0000000.0000000[]
110.1449040.0037170.0000001[3]
220.2808400.0044930.9381102[3, 1]
330.5245220.0045590.8676913[3, 1, 0]
440.6362690.0043150.2130454[3, 1, 0, 4]
550.7951230.0034000.2496675[3, 1, 0, 4, 2]
660.7926730.003550-0.0030826[3, 1, 0, 4, 2, 6]
770.7913150.003708-0.0017127[3, 1, 0, 4, 2, 6, 5]
\n\n\n\n\nIt is possible to see that the estimated mutual information is untouched from Round 6 onwards.\n\nSince there is a 'break' in Round 5, we should choose to stop the algorithm at theta round. This will be clear in the Mutual Information history plot that follows:\n\n\n```python\nselect.plot_mi()\n```\n\nPlotting the percentual variations of the mutual information between rounds:\n\n\n```python\nselect.plot_delta()\n\n```\n\nMaking the selection choosing to stop at Round 5:\n\n\n```python\nX_new = select.transform(X, rd=5)\n\nX_new.shape\n```\n\n\n\n\n (20000, 5)\n\n\n\n\n## 5\\. References\n\n[1] Eirola, E., Lendasse, A., & Karhunen, J. (2014, July). Variable selection for regression problems using Gaussian mixture models to estimate mutual information. In 2014 International Joint Conference on Neural Networks (IJCNN) (pp. 1606-1613). IEEE.\n\n[2] Lan, T., Erdogmus, D., Ozertem, U., & Huang, Y. (2006, July). Estimating mutual information using gaussian mixture model for feature ranking and selection. In The 2006 IEEE International Joint Conference on Neural Network Proceedings (pp. 5034-5039). IEEE.\n\n[3] Polo, F. M., & Vicente, R. (2020). Covariate Shift Adaptation in High-Dimensional and Divergent Distributions. arXiv preprint arXiv:2010.01184.\n\n\n\n", "meta": {"hexsha": "e87e23e0c81193bdc04b79ee7b64a7d25de2b132", "size": 99644, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "InfoSelect.ipynb", "max_stars_repo_name": "vincecr0ft/infoselect", "max_stars_repo_head_hexsha": "9d3785dadc3f053fc0f6739d8aaf3b331f9c097f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "InfoSelect.ipynb", "max_issues_repo_name": "vincecr0ft/infoselect", "max_issues_repo_head_hexsha": "9d3785dadc3f053fc0f6739d8aaf3b331f9c097f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "InfoSelect.ipynb", "max_forks_repo_name": "vincecr0ft/infoselect", "max_forks_repo_head_hexsha": "9d3785dadc3f053fc0f6739d8aaf3b331f9c097f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88.8884924175, "max_line_length": 16750, "alphanum_fraction": 0.7553289711, "converted": true, "num_tokens": 5701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.32043083010208784}} {"text": "### An Auto correct system is an application that changes mispelled words into the correct ones.\n\n\n\n\n```python\n# In this notebook I'll show how to implement an Auto Correct System that its very usefull.\n# This auto correct system only search for spelling erros, not contextual errors.\n```\n\n\n\n*The implementation can be divided into 4 steps:*\n\n[1]. **Identity a mispelled word.**\n\n[2]. **Find strings n Edit Distance away**\n\n[3]. **Filter Candidates** (*as Real Words that are spelled correct*)\n\n[4]. **Calculate Word Probabilities.** (*Choose the most likely cadidate to be the replacement*)\n\n### 1. Identity a mispelled Word\n\n*To identify if a word was mispelled, you can check if the word is in the dictionary / vocabulary.*\n\n\n```python\nvocab = ['dean','deer','dear','fries','and','coke', 'congratulations', 'my']\n\nword_test = 'Congratulations my deah'\nword_test = word_test.lower()\nword_test = word_test.split()\n\nfor word in word_test:\n if word in vocab:\n print(f'The word: {word} is in the vocab')\n else:\n print(f\"The word: {word} isn't in the vocabulary\")\n\n```\n\n The word: congratulations is in the vocab\n The word: my is in the vocab\n The word: deah isn't in the vocabulary\n\n\n### 2. Find strings n Edit Distance Away\n\n*Edit is a operation performed on a string to change into another string. Edit distance count the number of these operations*\n\n*So **n Edit Distance** tells you how many operations away one string is from another.*\n\n*For this application we'll use the Levenshtein Distance value's cost, where this edit value are:*\n\n* **Insert** - Operation where you insert a letter, the cost is equal to 1.\n\n* **Delete** - Operation where you delete a letter, the cost is equal to 1.\n\n* **Replace** - Operation where you replace one letter to another, the cost is equal to 2.\n\n* **Switch** - Operation where you swap 2 **adjacent** letters\n\n*Also we'll use the Minimum Edit Distance which is the minimum number of edits needed to transform 1 string into the other, for that we are using n = 2 and the Dynamic Programming algorithm. ( will be explained when it is implemented ) for evaluate our model*\n\n\n\n```python\n# To implement this operations we need to split the word into 2 parts in all possible ways\n\nword = 'dear'\n\nsplit_word = [[word[:i], word[i:]] for i in range(len(word) + 1)]\nfor i in split_word:\n print(i)\n```\n\n ['', 'dear']\n ['d', 'ear']\n ['de', 'ar']\n ['dea', 'r']\n ['dear', '']\n\n\n\n```python\n# The delete operation need to delete each possible letter from the original word.\n\ndelete_operation = [[L + R[1:]] for L, R in split_word if R ]\n\nfor i in delete_operation:\n print(i)\n```\n\n ['ear']\n ['dar']\n ['der']\n ['dea']\n\n\n\n```python\n# The same way the insert operation need to add each possible letter from the vocab to the original word\n\nletters = 'abcdefghijklmnopqrstuvwxyz'\ninsert_operation = [L + s + R for L, R in split_word for s in letters]\n\nc = 0\nprint('the first insert operations: ')\nprint()\nfor i in insert_operation:\n print(i)\n c += 1\n if c == 4:\n break\nc = 0\nprint('the last insert operations:')\nprint()\nfor i in insert_operation:\n c += 1\n if c > 126:\n print(i)\n\n```\n\n the first insert operations: \n \n adear\n bdear\n cdear\n ddear\n the last insert operations:\n \n dearw\n dearx\n deary\n dearz\n\n\n\n```python\n# Switch Operation\n\nswitch_operation = [[L[:-1] + R[0] + L[-1] + R[1:]] for L, R in split_word if R and L]\n\nfor i in switch_operation:\n print(i)\n\n```\n\n ['edar']\n ['daer']\n ['dera']\n\n\n\n```python\n# Replace Operation\n\nletters = 'abcdefghijklmnopqrstuvwxyz'\nreplace_operation = [L + s + (R[1:] if len(R) > 1 else '') for L, R in split_word if R for s in letters ] \n\nc = 0\nprint('the first replace operations: ')\nprint()\nfor i in replace_operation:\n print(i)\n c += 1\n if c == 4:\n break\n\nc = 0\nprint('the last replace operations:')\nprint()\nfor i in replace_operation:\n c += 1\n if c > 100:\n print(i)\n\n \n# Remember that at the end we need to remove the word it self\nreplace_operation = set(replace_operation)\nreplace_operation.discard('dear')\n```\n\n the first replace operations: \n \n aear\n bear\n cear\n dear\n the last replace operations:\n \n deaw\n deax\n deay\n deaz\n\n\n### 3. Filter Candidates\n\n*We only want to consider real and correctly spelled words form the candidate lists, so we need to compare to a know dictionary.*\n\n*If the string does not appears in the dict, remove from the candidates, this way resulting in a list of actual words only*\n\n\n```python\nvocab = ['dean','deer','dear','fries','and','coke', 'congratulations', 'my']\n\n# for example we can use the replace operations words to filter in our vocab\n\nfiltered_words = [word for word in replace_operation if word in vocab]\nprint(filtered_words)\n```\n\n ['deer', 'dean']\n\n\n### 4. Calculate the words probabilities\n\n*We need to find the most likely word from the cadidate list, to calculate the probability of a word in the \nsentence we need to first calculate the word frequencies, also we want to count the total number of word in the body of texts\nor corpus.*\n\n*So we compute the probability that each word will appear if randomly selected from the corpus of words.*\n\n$$P(w_i) = \\frac{C(w_i)}{M} \\tag{Eq 01}$$\n*where*\n\n$C(w_i)$ *is the total number of times $w_i$ appears in the corpus.*\n\n$M$ *is the total number of words in the corpus.*\n\n*For example, the probability of the word 'am' in the sentence **'I am happy because I am learning'** is:*\n\n$$P(am) = \\frac{C(w_i)}{M} = \\frac {2}{7} \\tag{Eq 02}.$$\n\n### Now the we know the four steps of the Auto Correct System, we can start to implement it\n\n\n```python\n# import libraries\nimport re\nfrom collections import Counter\nimport numpy as np\nimport pandas as pd\n```\n\n*The first thing to do is the data pre processing, for this example we'll use the file called **'shakespeare.txt'** this file can be found in the directory.*\n\n\n```python\ndef process_data(filename):\n \"\"\"\n Input: \n A file_name which is found in the current directory. We just have to read it in. \n Output: \n words: a list containing all the words in the corpus (text file you read) in lower case. \n \"\"\"\n \n words = []\n with open(filename, 'r') as f:\n text = f.read()\n \n words = re.findall(r'\\w+', text)\n words = [word.lower() for word in words]\n \n return words\n```\n\n\n```python\nwords = process_data('shakespeare.txt')\nvocab = set(words) # eliminate duplicates \n\nprint(f'The vocabulary has {len(vocab)} unique words.')\n```\n\n The vocabulary has 6116 unique words.\n\n\n*The second step, we need to count the frequency of every word in the dictionary to later calculate the probabilities*\n\n\n\n```python\ndef get_count(word):\n '''\n Input:\n word_l: a set of words representing the corpus. \n Output:\n word_count_dict: The wordcount dictionary where key is the word and value is its frequency.\n '''\n word_count_dict = {}\n \n word_count_dict = Counter(word)\n \n return word_count_dict\n\n\nword_count_dict = get_count(words)\nprint(f'There are {len(word_count_dict)} key par values')\nprint(f\"The count for the word 'thee' is {word_count_dict.get('thee',0)}\")\n```\n\n There are 6116 key par values\n The count for the word 'thee' is 240\n\n\n*Now we must calculate the probability that each word appears using the (eq 01):*\n\n\n```python\n\ndef get_probs(word_count_dict):\n '''\n Input:\n word_count_dict: The wordcount dictionary where key is the word and value is its frequency.\n Output:\n probs: A dictionary where keys are the words and the values are the probability that a word will occur. \n '''\n \n probs = {}\n total_words = 0\n \n for word, value in word_count_dict.items():\n total_words += value # we add the quantity of each word appears\n \n for word, value in word_count_dict.items():\n probs[word] = value / total_words\n \n \n return probs\n\nprobs = get_probs(word_count_dict)\nprint(f\"Length of probs is {len(probs)}\")\nprint(f\"P('thee') is {probs['thee']:.4f}\")\n```\n\n Length of probs is 6116\n P('thee') is 0.0045\n\n\n*Now, that we have computed $P(w_i)$ for all the words in the corpus, we'll write the functions such as delete, insert, switch and replace to manipulate strings so that we can edit the erroneous strings and return the right spellings of the words.*\n\n\n```python\ndef delete_letter(word, verbose = False):\n '''\n Input:\n word: the string/word for which you will generate all possible words \n in the vocabulary which have 1 missing character\n Output:\n delete_l: a list of all possible strings obtained by deleting 1 character from word\n '''\n \n delete = []\n split_word = []\n \n split_word = [[word[:i], word[i:]] for i in range(len(word))]\n \n delete = [L + R[1:] for L, R in split_word if R]\n \n if verbose: print(f\"input word {word}, \\nsplit_word = {split_word}, \\ndelete_word = {delete}\")\n\n return delete\n\ndelete_word = delete_letter(word=\"cans\",\n verbose=True)\n```\n\n input word cans, \n split_word = [['', 'cans'], ['c', 'ans'], ['ca', 'ns'], ['can', 's']], \n delete_word = ['ans', 'cns', 'cas', 'can']\n\n\n\n```python\ndef switch_letter(word, verbose = False):\n '''\n Input:\n word: input string\n Output:\n switches: a list of all possible strings with one adjacent charater switched\n ''' \n \n switch = []\n split_word = []\n \n split_word = [[word[:i], word[i:]] for i in range(len(word))]\n \n switch = [L[:-1] + R[0] + L[-1] + R[1:] for L, R in split_word if L and R]\n \n if verbose: print(f\"Input word = {word} \\nsplit = {split_word} \\nswitch = {switch}\") \n\n return switch\n\nswitch_word_l = switch_letter(word=\"eta\",\n verbose=True)\n```\n\n Input word = eta \n split = [['', 'eta'], ['e', 'ta'], ['et', 'a']] \n switch = ['tea', 'eat']\n\n\n\n```python\ndef replace_letter(word, verbose=False):\n '''\n Input:\n word: the input string/word \n Output:\n replaces: a list of all possible strings where we replaced one letter from the original word. \n ''' \n \n letters = 'abcdefghijklmnopqrstuvwxyz'\n replace = []\n split_word = []\n \n\n split_word = [(word[:i], word[i:]) for i in range(len(word))]\n \n replace = [L + s + (R[1:] if len(R) > 1 else '') for L, R in split_word if R for s in letters ]\n \n # we need to remove the actual word from the list\n replace = set(replace)\n replace.discard(word)\n\n \n \n replace = sorted(list(replace)) # turn the set back into a list and sort it, for easier viewing\n \n if verbose: print(f\"Input word = {word} \\nsplit = {split_word} \\nreplace {replace}\") \n \n return replace\n\nreplace_l = replace_letter(word='can',\n verbose=True)\n```\n\n Input word = can \n split = [('', 'can'), ('c', 'an'), ('ca', 'n')] \n replace ['aan', 'ban', 'caa', 'cab', 'cac', 'cad', 'cae', 'caf', 'cag', 'cah', 'cai', 'caj', 'cak', 'cal', 'cam', 'cao', 'cap', 'caq', 'car', 'cas', 'cat', 'cau', 'cav', 'caw', 'cax', 'cay', 'caz', 'cbn', 'ccn', 'cdn', 'cen', 'cfn', 'cgn', 'chn', 'cin', 'cjn', 'ckn', 'cln', 'cmn', 'cnn', 'con', 'cpn', 'cqn', 'crn', 'csn', 'ctn', 'cun', 'cvn', 'cwn', 'cxn', 'cyn', 'czn', 'dan', 'ean', 'fan', 'gan', 'han', 'ian', 'jan', 'kan', 'lan', 'man', 'nan', 'oan', 'pan', 'qan', 'ran', 'san', 'tan', 'uan', 'van', 'wan', 'xan', 'yan', 'zan']\n\n\n\n```python\n\ndef insert_letter(word, verbose=False):\n '''\n Input:\n word: the input string/word \n Output:\n inserts: a set of all possible strings with one new letter inserted at every offset\n ''' \n letters = 'abcdefghijklmnopqrstuvwxyz'\n insert = []\n split_word = []\n \n\n split_word = [(word[:i], word[i:]) for i in range(len(word) + 1 )]\n insert = [L + s + R for L, R in split_word for s in letters]\n\n\n\n if verbose: print(f\"Input word {word} \\nsplit = {split_word} \\ninsert = {insert}\")\n \n return insert\n\ninsert = insert_letter('at', True)\nprint(f\"Number of strings output by insert_letter('at') is {len(insert)}\")\n```\n\n Input word at \n split = [('', 'at'), ('a', 't'), ('at', '')] \n insert = ['aat', 'bat', 'cat', 'dat', 'eat', 'fat', 'gat', 'hat', 'iat', 'jat', 'kat', 'lat', 'mat', 'nat', 'oat', 'pat', 'qat', 'rat', 'sat', 'tat', 'uat', 'vat', 'wat', 'xat', 'yat', 'zat', 'aat', 'abt', 'act', 'adt', 'aet', 'aft', 'agt', 'aht', 'ait', 'ajt', 'akt', 'alt', 'amt', 'ant', 'aot', 'apt', 'aqt', 'art', 'ast', 'att', 'aut', 'avt', 'awt', 'axt', 'ayt', 'azt', 'ata', 'atb', 'atc', 'atd', 'ate', 'atf', 'atg', 'ath', 'ati', 'atj', 'atk', 'atl', 'atm', 'atn', 'ato', 'atp', 'atq', 'atr', 'ats', 'att', 'atu', 'atv', 'atw', 'atx', 'aty', 'atz']\n Number of strings output by insert_letter('at') is 78\n\n\n*Now that we have implemented the string manipulations, we'll create two functions that, given a string, will return all the possible single and double edits on that string. These will be `edit_one_letter()` and `edit_two_letters()`.*\n\n\n```python\ndef edit_one_letter(word, allow_switches = True): # The 'switch' function is a less common edit function, \n # so will be selected by an \"allow_switches\" input argument.\n \"\"\"\n Input:\n word: the string/word for which we will generate all possible wordsthat are one edit away.\n Output:\n edit_one_set: a set of words with one possible edit. Please return a set. and not a list.\n \"\"\"\n \n edit_one_set = set()\n all_word, words = [] , []\n \n words.append(insert_letter(word))\n words.append(delete_letter(word))\n words.append(replace_letter(word))\n if allow_switches == True:\n words.append(switch_letter(word))\n \n for i in words:\n for each_word in i:\n if each_word == word: # we exclude the word it self\n continue\n all_word.append(each_word)\n \n edit_one_set = set(all_word)\n \n return edit_one_set\n\ntmp_word = \"at\"\ntmp_edit_one_set = edit_one_letter(tmp_word)\n# turn this into a list to sort it, in order to view it\ntmp_edit_one = sorted(list(tmp_edit_one_set))\n\nprint(f\"input word: {tmp_word} \\nedit_one \\n{tmp_edit_one}\\n\")\nprint(f\"The type of the returned object should be a set {type(tmp_edit_one_set)}\")\nprint(f\"Number of outputs from edit_one_letter('at') is {len(edit_one_letter('at'))}\")\n```\n\n input word: at \n edit_one \n ['a', 'aa', 'aat', 'ab', 'abt', 'ac', 'act', 'ad', 'adt', 'ae', 'aet', 'af', 'aft', 'ag', 'agt', 'ah', 'aht', 'ai', 'ait', 'aj', 'ajt', 'ak', 'akt', 'al', 'alt', 'am', 'amt', 'an', 'ant', 'ao', 'aot', 'ap', 'apt', 'aq', 'aqt', 'ar', 'art', 'as', 'ast', 'ata', 'atb', 'atc', 'atd', 'ate', 'atf', 'atg', 'ath', 'ati', 'atj', 'atk', 'atl', 'atm', 'atn', 'ato', 'atp', 'atq', 'atr', 'ats', 'att', 'atu', 'atv', 'atw', 'atx', 'aty', 'atz', 'au', 'aut', 'av', 'avt', 'aw', 'awt', 'ax', 'axt', 'ay', 'ayt', 'az', 'azt', 'bat', 'bt', 'cat', 'ct', 'dat', 'dt', 'eat', 'et', 'fat', 'ft', 'gat', 'gt', 'hat', 'ht', 'iat', 'it', 'jat', 'jt', 'kat', 'kt', 'lat', 'lt', 'mat', 'mt', 'nat', 'nt', 'oat', 'ot', 'pat', 'pt', 'qat', 'qt', 'rat', 'rt', 'sat', 'st', 't', 'ta', 'tat', 'tt', 'uat', 'ut', 'vat', 'vt', 'wat', 'wt', 'xat', 'xt', 'yat', 'yt', 'zat', 'zt']\n \n The type of the returned object should be a set \n Number of outputs from edit_one_letter('at') is 129\n\n\n\n```python\ndef edit_two_letters(word, allow_switches = True):\n '''\n Input:\n word: the input string/word \n Output:\n edit_two_set: a set of strings with all possible two edits\n '''\n \n edit_two_set = set()\n \n \n if allow_switches == True:\n first_edit = edit_one_letter(word)\n \n else:\n first_edit = edit_one_letter(word, allow_switches = False)\n \n \n \n \n first_edit = set(first_edit)\n second_edit = []\n final_edit = []\n \n if allow_switches == True:\n for each_word in first_edit:\n second_edit.append(edit_one_letter(each_word))\n for i in second_edit:\n for each_word in i:\n final_edit.append(each_word)\n edit_two_set = set(final_edit)\n \n else:\n for each_word in first_edit:\n second_edit.append(edit_one_letter(each_word, allow_switches = False))\n for i in second_edit:\n for each_word in i:\n final_edit.append(each_word)\n edit_two_set = set(final_edit)\n \n \n return edit_two_set\n\n\n```\n\n\n```python\ntmp_edit_two_set = edit_two_letters(\"a\")\ntmp_edit_two_l = sorted(list(tmp_edit_two_set))\nprint(f\"Number of strings with edit distance of two: {len(tmp_edit_two_l)}\")\nprint(f\"First 10 strings {tmp_edit_two_l[:10]}\")\nprint(f\"Last 10 strings {tmp_edit_two_l[-10:]}\")\nprint(f\"The data type of the returned object should be a set {type(tmp_edit_two_set)}\")\nprint(f\"Number of strings that are 2 edit distances from 'at' is {len(edit_two_letters('at'))}\")\n```\n\n Number of strings with edit distance of two: 2654\n First 10 strings ['', 'a', 'aa', 'aaa', 'aab', 'aac', 'aad', 'aae', 'aaf', 'aag']\n Last 10 strings ['zv', 'zva', 'zw', 'zwa', 'zx', 'zxa', 'zy', 'zya', 'zz', 'zza']\n The data type of the returned object should be a set \n Number of strings that are 2 edit distances from 'at' is 7154\n\n\n*Now we will use the `edit_two_letters` function to get a set of all the possible 2 edits on our word. We will then use those strings to get the most probable word we meant to substitute our word typing suggestion.*\n\n\n```python\ndef get_corrections(word, probs, vocab, n=2, verbose = False):\n '''\n Input: \n word: a user entered string to check for suggestions\n probs: a dictionary that maps each word to its probability in the corpus\n vocab: a set containing all the vocabulary\n n: number of possible word corrections you want returned in the dictionary\n Output: \n n_best: a list of tuples with the most probable n corrected words and their probabilities.\n '''\n \n suggestions = []\n n_best = []\n \n # look if the word exist in the vocab, if doesn't, the edit_one_letter fuction its used, if any of the letter created \n # exists in the vocab, take the two letter edit function, if any of this situations are in the vocab, take the input word\n suggestions = list((word in vocab) or (edit_one_letter(word).intersection(vocab)) or (edit_two_letter(word).intersection(vocab)) or word)\n \n\n n_best= [[word, probs[word]] for word in (suggestions)] # make a list with the possible word and probability.\n \n \n if verbose: print(\"entered word = \", word, \"\\nsuggestions = \", set(suggestions))\n\n return n_best\n\n\n```\n\n\n```python\nmy_word = 'dys' \ntmp_corrections = get_corrections(my_word, probs, vocab, 2, verbose=True) # keep verbose=True\nfor i, word_prob in enumerate(tmp_corrections):\n print(f\"word {i}: {word_prob[0]}, probability {word_prob[1]:.6f}\")\n\nprint(f'The highest score for all the candidates is the word {tmp_corrections[np.argmax(word_prob)][0]}')\n\n```\n\n entered word = dys \n suggestions = {'days', 'dye'}\n word 0: days, probability 0.000410\n word 1: dye, probability 0.000019\n The highest score for all the candidates is the word days\n\n\n*Now that we have implemented the auto-correct system, how do you evaluate the similarity between two strings? For example: 'waht' and 'what'.*\n\n*Also how do you efficiently find the shortest path to go from the word, 'waht' to the word 'what'?*\n\n*We will implement a dynamic programming system that will tell you the minimum number of edits required to convert a string into another string.*\n\n### Dynamic Programming\n\n*Dynamic Programming breaks a problem down into subproblems which can be combined to form the final solution. Here, given a string source[0..i] and a string target[0..j], we will compute all the combinations of substrings[i, j] and calculate their edit distance. To do this efficiently, we will use a table to maintain the previously computed substrings and use those to calculate larger substrings.*\n\n*You have to create a matrix and update each element in the matrix as follows:*\n\n$$\\text{Initialization}$$\n\n\\begin{align}\nD[0,0] &= 0 \\\\\nD[i,0] &= D[i-1,0] + del\\_cost(source[i]) \\tag{eq 03}\\\\\nD[0,j] &= D[0,j-1] + ins\\_cost(target[j]) \\\\\n\\end{align}\n\n*So converting the source word **play** to the target word **stay**, using an insert cost of one, a delete cost of 1, and replace cost of 2 would give you the following table:*\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n
# s t a y
# 0 1 2 3 4
p 1 2 3 4 5
l 23456
a 34545
y 45654
\n\n\n\n*The operations used in this algorithm are 'insert', 'delete', and 'replace'. These correspond to the functions that we defined earlier: insert_letter(), delete_letter() and replace_letter(). switch_letter() is not used here.*\n\n*The diagram below describes how to initialize the table. Each entry in D[i,j] represents the minimum cost of converting string source[0:i] to string target[0:j]. The first column is initialized to represent the cumulative cost of deleting the source characters to convert string \"EER\" to \"\". The first row is initialized to represent the cumulative cost of inserting the target characters to convert from \"\" to \"NEAR\".*\n\n
Figure 1 Initializing Distance Matrix
\n\n*Note that the formula for $D[i,j]$ shown in the image is equivalent to:*\n\n\\begin{align}\n \\\\\nD[i,j] =min\n\\begin{cases}\nD[i-1,j] + del\\_cost\\\\\nD[i,j-1] + ins\\_cost\\\\\nD[i-1,j-1] + \\left\\{\\begin{matrix}\nrep\\_cost; & if src[i]\\neq tar[j]\\\\\n0 ; & if src[i]=tar[j]\n\\end{matrix}\\right.\n\\end{cases}\n\\tag{5}\n\\end{align}\n\n*The variable `sub_cost` (for substitution cost) is the same as `rep_cost`; replacement cost. We will stick with the term \"replace\" whenever possible.*\n\n
Figure 2 Examples Distance Matrix
\n\n\n```python\ndef min_edit_distance(source, target, ins_cost = 1, del_cost = 1, rep_cost = 2):\n '''\n Input: \n source: a string corresponding to the string you are starting with\n target: a string corresponding to the string you want to end with\n ins_cost: an integer setting the insert cost\n del_cost: an integer setting the delete cost\n rep_cost: an integer setting the replace cost\n Output:\n D: a matrix of len(source)+1 by len(target)+1 containing minimum edit distances\n med: the minimum edit distance (med) required to convert the source string to the target\n '''\n \n m = len(source)\n n = len(target)\n \n # initialize cost matrix with zeros and dimensions (m+1, n+1)\n D = np.zeros((m+1, n+1), dtype = int)\n \n # Fill in column 0, from row 1 to row m, both inclusive\n for row in range(1, m+1): # Replace None with the proper range\n D[row, 0] = D[row -1, 0] + del_cost\n \n # Fill in row 0, for all columns from 1 to n, both inclusive\n for column in range(1, n+1):\n D[0, column] = D[0, column - 1] + ins_cost\n \n # Loop through row 1 to row m, both inclusive\n for row in range(1, m+1):\n \n # Loop through column 1 to column n, both inclusive\n for column in range(1, n+1):\n \n # initialize r_cost to the 'replace' cost that is passed into this function\n r_cost = rep_cost\n \n # check to see if source character at the previous row\n # matches the target haracter at the previous column\n if source[row - 1] == target[column - 1]:\n # Update the replacement cost to 0 if source and\n # target are equal\n r_cost = 0\n \n # Update the cost atow, col based on previous entries in the cost matrix\n # Refer to the equation calculate for D[i,j] (the mininum of the three calculated)\n D[row, column] = min([D[row-1, column] + del_cost, D[row, column-1] + ins_cost, D[row-1, column-1] + r_cost])\n \n # Set the minimum edit distance with the cost found at row m, column n\n \n med = D[m, n]\n return D, med\n```\n\n\n```python\n# testing your implementation \nsource = 'play'\ntarget = 'stay'\nmatrix, min_edits = min_edit_distance(source, target)\nprint(\"minimum edits: \",min_edits, \"\\n\")\nidx = list('#' + source)\ncols = list('#' + target)\ndf = pd.DataFrame(matrix, index=idx, columns= cols)\nprint(df)\n```\n\n minimum edits: 4 \n \n # s t a y\n # 0 1 2 3 4\n p 1 2 3 4 5\n l 2 3 4 5 6\n a 3 4 5 4 5\n y 4 5 6 5 4\n\n\n\n```python\n# testing your implementation \nsource = 'eer'\ntarget = 'near'\nmatrix, min_edits = min_edit_distance(source, target)\nprint(\"minimum edits: \",min_edits, \"\\n\")\nidx = list(source)\nidx.insert(0, '#')\ncols = list(target)\ncols.insert(0, '#')\ndf = pd.DataFrame(matrix, index=idx, columns= cols)\nprint(df)\n```\n\n minimum edits: 3 \n \n # n e a r\n # 0 1 2 3 4\n e 1 2 1 2 3\n e 2 3 2 3 4\n r 3 4 3 4 3\n\n", "meta": {"hexsha": "d0faf997baf116d4270aa66f3606d4264f1b9969", "size": 38662, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Auto Correct System/.ipynb_checkpoints/Auto Correct System-checkpoint.ipynb", "max_stars_repo_name": "rodrigoamorimml/NaturalLanguageProcessing", "max_stars_repo_head_hexsha": "d7729cff87fb0cb5c326d52010cf869456ea48bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-06T06:47:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-06T14:41:45.000Z", "max_issues_repo_path": "Auto Correct System/Auto Correct System.ipynb", "max_issues_repo_name": "rodrigoamorimml/NaturalLanguageProcessing", "max_issues_repo_head_hexsha": "d7729cff87fb0cb5c326d52010cf869456ea48bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Auto Correct System/Auto Correct System.ipynb", "max_forks_repo_name": "rodrigoamorimml/NaturalLanguageProcessing", "max_forks_repo_head_hexsha": "d7729cff87fb0cb5c326d52010cf869456ea48bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4345637584, "max_line_length": 859, "alphanum_fraction": 0.5076302312, "converted": true, "num_tokens": 7433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.32030014908712984}} {"text": "```python\n%matplotlib notebook\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sympy as sp\nfrom plots import *\n\nsp.init_printing()\nfreqs = [f for f in np.random.standard_cauchy(11) if abs(f) < 10]\nomega = [2+ f for f in freqs] + [1 - f for f in freqs] + [1]\n\nfrom BondGraphTools import version\nimport BondGraphTools as bgt\nassert version == \"0.3.7\"\nscale = 2\n\nfrom matplotlib.font_manager import FontProperties\n\ndef plot_graph(t, x):\n fontP = FontProperties()\n fontP.set_size('small')\n fig = plt.figure(figsize=(scale*4,scale*4))\n plt.plot(t,x)\n ax = fig.gca()\n ax.set_xlabel('t')\n ax.set_title(f\"System response to {impulse}\")\n ax.legend(\n [f\"$x_{i}$\" for i in range(len(x))],\n bbox_to_anchor=(1.,1.),\n loc=1,\n borderaxespad=0.,\n prop=fontP\n )\n return fig\n\ndef print_tree(bond_graph, pre=\"\"):\n print(f\"{pre}{bond_graph}\")\n try:\n for component in reversed(bond_graph.components):\n if pre == \"\": print_tree(component, pre +\"|-\" )\n else: print_tree(component, pre +\"-\" )\n except AttributeError:\n pass\n```\n\n\n```python\n\n```\n\n\n\n# On Emergence in Complex Physical Systems\n\n\nhttps://github.com/peter-cudmore\n\n \n\n Dr. Peter Cudmore. \n Systems Biology Labratory, \n The School of Chemical and Biomedical Engineering, \n The University of Melbourne. \n\nMany problems in biology, physics and engineering involve predicting and controlling complex systems, loosely defined as interconnected system-of-systems. Such systems can exhibit a variety of interesting non-equilibrium features such as emergence and phase transitions, which result from mutual interactions between nonlinear subsystems. \n\nModelling these systems is a task in-and-of itself, as systems can span many physical domains and evolve on multiple time scales. Nonetheless, one wishes to analyse the geometry of these models and relate both qualitative and quantitative insights back to the physical system.\n\nBeginning with the modelling and analysis of a coupled optomechanical systems, this talk presents some recent results concerning the existence and stability of emergent oscillations. This forms the basis for a discussion of new directions in symbolic computational techniques for complex physical systems as a means to discuss emergence more generally.\n\n\n## The problem with big systems is that they're _big_...\n\n## Example: Human Metabolism\n\n
\n\n(Image courtesy of Human Metabolism map https://www.vmh.life )\n\n# Example: Ecosystems\n\n
\n\n## Complex Physical Systems \n\nA dynamical system is said to be a _complex physical system_ when:\n* It is made up of many _interacting_ parts, or subsystems (High-dimensional).\n* The subsystems are not all of the same (Heterogenenous).\n* The subsystems are complicated (Nonlinear and/or Noisy).\n* There are well defined boundaries between the subsystems (Network Topology).\n* **Coupling takes place via resource exchange (Conservation Laws).**\n\n\n> There is a fact, or if you wish, a law, governing all natural phenomena that are known to date. There is no known exception to this law—it is exact so far as we know. The law is called the conservation of energy. \n\n\\- R. Feynman, 1963. http://www.feynmanlectures.caltech.edu/I_04.html\n\n## Complex Systems can exhibit _emergence_.\n\n- _Emergence_ is a phenomenom where the system displays novel new behaviour that could not be produced by individuals alone.\n- _Synchronisation_ is the most studied example of emergence, and can occur in systems of coupled oscillator.\n\n
How can one predict and control emergent phenomenon?
\n\n## The problem with big systems...\n\n$$\\begin{align}\n\\dot{x} &= f(x, u;\\lambda),\\\\\n0 &= g(x,u;\\lambda),\\\\\n y &= h(x,u).\n\\end{align}\n$$\n\nWhat do we do when $x$ is high dimensional and $f$ doesn't have exploitable structure?\n\n\n\n
\nHow can nonlinear dynamics be \"scaled up\"? \n
\n\n## Geometry and Physics\n\nGeometric features often correspond to physically interesting features (Noether Theroem).\n\n\nIn systems biology in particular:\n- Conserved Moieties $\\iff$ first integrals \n- Transport pathways $\\iff$ invariant manifolds.\n\n\n\n
\nHow can nonlinear dynamics be \"scaled up\"? \n
\n\n## Goals of this talk\n\nI want to convince you that:\n1. Emergence is a nonlinear phenomenon, so we need to look at _nonlinear_ systems.\n2. As systems get big, the usual ad-hoc techniques stop working so we need an alternative.\n3. Thinking about energy provides a means to _systematically_ model systems.\n4. Symbolic modelling software makes this scalable.\n5. This provides a pathway to study system level dynamics, in particular emergence.\n\n## Outline of this talk\n\n\n\n\n1. Briefly discuss synchronisation as it's the best example of emergence.\n\n2. Discuss some challenges and present solutions for modelling big systems.\n\n3. Discuss software to make this work.\n\n## Part 1: Synchronisation as the prototype for emergence\n\n## The Kuramoto Model\n\n_Self-entrainment of a population of coupled non-linear oscillators_ Kuramoto, Y. (1975).\n\n$$\n\\text{limit cycle oscillator:}\\qquad \\dot{z_j} = \\gamma(1 - |z_j|^2)z_j + i\\omega_j z_j + \\frac{K}{n}\\sum_{k=1}^nz_k,\n\\quad j=1,\\ldots n, \\qquad \\gamma \\gg 1, 0 \\le K, \\omega_j \\in \\mathbb{R}\n$$\n\nThe phase $\\theta_j =\\text{Arg}\\ z_j$ of each oscillator with a natural frequency $\\omega_j$ is given by\n\n\\begin{equation}\n\\dot{\\theta}_j = \\omega_j + \\frac{K}{n}\\sum_{k=1}^n\\sin(\\theta_k - \\theta_j),\\qquad j=1,\\ldots n\n\\end{equation}\n- When $0\\le K K_c$ more oscillator are recruited to collective.\n\nThe value of $K_c$ depends upon the distribution of $\\{\\omega_j\\}$. For symmetric distribtuions we have\n$$K_c = \\frac{2}{\\pi g(0)}$$\n\n\n\n```python\n# Omega = Cauchy(2,1) so that K_c = 2\np = KuramotoModel(omega=omega, scale=scale)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nPoints:\n- Wiener -> Winfree -> Kuramoto\n- Comes from studying BZ reaction\n- Motion on a strongly attracive limit cycle (invariant manifold) such that coupling\n- All-to-all coupling on a complete graph.\n- sinusoidal in phase -> linear in complex co-ordinates.\n- Kuramoto showed that at $K_c=2$ a Hopf bifurcation creates a synchronised state, that becomes progressive more stable as $K_c$ increases.\n\n## The Kuramoto Model (Cont.)\n\n$$\n\\text{limit cycle oscillator:}\\qquad \\dot{z_j} = \\gamma(1 - |z_j|^2)z_j + i\\omega_j z_j + \\frac{K}{n}\\sum_{k=1}^nz_k,\n\\quad j=1,\\ldots n, \\qquad \\gamma \\gg 1, 0 \\le K, \\omega_j \\in \\mathbb{R}\n$$\n\nKuramoto introduced an 'order parameter' $r$ to measure phase coherence\n\\begin{equation}\nz = r\\mathrm{e}^{\\mathrm{i}\\Theta} = \\frac{1}{n}\\sum_{k=1}^n \\exp{\\mathrm{i}\\theta_k} \\implies r = \\frac{1}{n}\\sum_{k=1}^n \\exp\\mathrm{i}(\\theta_k-\\Theta)\n\\end{equation}\nIt follows that\n$$\n\\Im\\left[\\frac{1}{n}\\sum_{k=1}^n\\exp i(\\theta_k - \\theta_j)\\right] = \n\\Im\\left[r\\exp i(\\Theta - \\theta_j)\\right] \n$$\n\n\nHence\n$$\n\\dot{\\theta}_j = \\omega_j + \\frac{K}{n}\\sum_{k=1}^n\\sin(\\theta_k - \\theta_j)$$\n\nbecomes \n$$\n\\dot{\\theta}_j = \\omega_j + rK\\sin(\\Theta - \\theta_j).\n$$\n\n\n```python\np = KuramotoOrderModel(omega,scale=scale)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\nPoints:\n- Mean phase is a kind of coordinate for the synchronous manifold.\n- Weak interactions with entire populations <=> strong coupling to collective statistics\n- Feedback look means that if coupling increases coherence, then $r$ increases asymptotically to $r_\\infty = \\sqrt{1-K_c/K}$$.\n\n## The Status of the Kuramoto Model \n\n$$\n\\dot{\\theta}_j = \\omega_j + rK\\sin(\\Theta - \\theta_j),\\qquad j = 1,\\ldots n.\\qquad r = \\frac{1}{n}\\sum_{k=1}^n \\exp i (\\theta_k - \\Theta).\n$$\n\n- Identical oscillators evolve on a 3 dimensional manifold (Watanabe and Strogatz, Physica D 1994. Ott and Antonsen, Chaos 2008).\n- Heterogenous oscillator dynamics represented in terms of collective co-ordinates in the thermodynamic limit (Pikovsky and Rosenblum, Physica D, 2011) and for finite-n (Gottwald, Chaos 2015).\n- Active research into applications in biology (particuarly neuroscience), physics and chemsitry.\n- Extensions to noisy, graph coupled and with various different coupling mechanisms.\n- Very few global results for heterogenous oscillators (Dietert, J. Math. Pures Appl. 2016).\n- _No results as yet for geometrical interpretation of transtion to synchrony._\n\n## Implications\n\n#### From the Kuramoto Model\n\n$$\n\\dot{\\theta}_j = \\omega_j + rK\\sin(\\Theta - \\theta_j),\\qquad j = 1,\\ldots n.\\qquad r = \\frac{1}{n}\\sum_{k=1}^n \\exp i (\\theta_k - \\Theta).\n$$\n1. When thinking about emergence, we want to think about mutual coupling between population statistics and individuals.\n2. This means that, for a given system, we need to understand both mechanisms on the individual scale _and_ dynamics on the population scale.\n\n#### For complex physical systems\n\n1. We expect to see mutual coupling between the population, particularly via resource competition.\n2. Statistical approaches (like stat-mech) will not be suffient for our purposes.\n\n\n
In order to look at emergence more generally, we must be able to model nonlinear systems more generally
\n\n  \n\n  \n\n  \n\n\n# Modelling Complex Physical Systems \n\n \n\n### Inheritance, Composition and Encapsulation\n\n## Ad-hoc modelling.\n\n\n\n1. Start with a Hamiltonian\n2. Derive equations of motion and do a whole bunch of algebra.\n3. Work out the appropriate coordinates (here, a non-standard slow fast system)\n4. More algebra to reduce model.\n5. Investigate the dynamics of the reduced models.\n6. Relate results in reduced model to observables in the original system\n\nIn the case of emergent phenomenon, the 'reduced' subspace involves the whole (or at least a large part of) system. E.g. mean fields.\n\n## Ad-hoc approaches won't scale.\n\n
\n\nAs an example:\n- individual processes are far more heterogenous\n- network topolgy is complicated\n- many parameters are unknown\n- almost guaranteed to be a differential-algebraic system\n- **too big for one person, or even one lab**\n\nWe must have:\n- Ways to respresent and manipulate such systems,\n- Ways to manage congnitive complexity,\n- Ways to automate model capture and reduction,\n- Ways to effective share work between researchers\n\n## Energetic Network Modelling\n\n\n\n\n\n## The Structure of Complex Physical Systems\n\nAn approach based on 'bond graph' modelling, and port-Hamiltonian systems.\n\n- Energy is stored in 'state variables' $q,p$\n- Power is distributed via 'power variables' $e,f$\n- Formally describes the hyrdo-mechanical-electrical analogies.\n\nFor example; \n- Dissipation $R$ relates $e,f$ variables. (eg. Ohm's law, friction, etc)\n- Potential storage $q$ to $e$ (eg, capacitors, gravity) \n\n**Translational Mechanics**\n- $q, p$ are position and momentum\n- $f, e$ are velocity and force\n\n**Electromagnetics**\n\n- $q, p$ are charge and flux linkage\n- $f, e$ are current and voltage\n\n**Hydraulics**\n- $q, p$ are volume and pressure momentum\n- $f, e$ are fow and pressure\n\n**Chemistry**\n- $q,p $ is moles and.. chemical momentum?\n- $f,e$ are molar flow and chemical potential\n\n\n## An Object Oriented Representation of Energetic Systems\n\nObject Oriented Programming (OOP) is a software development paradigm that seeks to manage large, complicated projects by breaking problems into _data_ plus _methods_ that act on the data. \n\nThree big ideas in OOP are:\n1. _Inheritance_ or is-a relationships. \n2. _Composition_ or has-a relationships.\n3. _Encapsulation_ or infomation hiding.\n\nThis allows for _hierarchical_ and _modular_ design which reduces model complexity.\n\n'Energetic systems' draws from:\n- Network based analysis from engineering; in particular circuit analysis and the more general (and less well known) bond graph methodology,\n- Classical mechanics, and in particular recent advances in port based Hamiltonian mechanics,\n- The effective was of managing complexity within software engineering.\n\nAll in service of describing _whole systems_ so as to understand _emergent processes_.\n\n## Inheritance\n\n \n\nFor networked dynamic systems, _inheritance_ means we:\n- define what the base components are,\n- impose conditions on the dynamical sub-systems,\n- describe the interface between nodes.\n\n\n\n\n### Definition (Energetic System)\n\nAn energetic system is a tuple $(M, \\mathcal{D}, U,\\Phi)$\nwhere the\n* *state space* $M$ is a manifold of $\\dim(M) = m\\ge 0$\n* *port space* $\\mathcal{D} \\subset \\mathcal{F} \\times \\mathcal{E}$ where, $\\mathcal{E} = \\mathcal{F}^*$ and $ \\dim{\\mathcal{D}} = \\mathcal{F}|_\\mathcal{D} =n$. \n* *control space* $U \\subset C^r:\\mathbb{R}_+ \\rightarrow \\mathbb{R^k}$ with $k\\ge 0$ \n* *constitutive relation* is a smooth map $\\Phi: TM \\times \\mathcal{D} \\times U\\times\\mathbb{R}_+ \\rightarrow\n \\mathbb{R}^{m+n}$ \n such that\n $$\\Phi\\left(\\frac{dx}{dt},x,f,e,u,t\\right)=0.$$\n\n$\\Phi$ relates the _internal state_ $M$ and the _external environment_ (via $\\mathcal{D}$).\n\n \n\n\n\n\n \n\nThe incoming *power* is $P_\\text{in} = \\left$ for $(f,e)\\in \\mathcal{D}$\n\n## Energy Storage\n\n**Example (Potential Energy)**\n\nPotential energy storage can be defined as\n\n$$\n\\Phi_\\text{C}(\\dot{x},e,f,x) = \n\\left(\\begin{matrix}\nx - Ce\\\\ \n\\dot{x} - f\n\\end{matrix}\\right) = 0.\n$$\n\n**Example (Kinetic Energy)**\n\nSimiarly for generalised 'kinetic energy'\n\n$$\n\\Phi_\\text{L}(\\dot{x},e,f,x) = \n\\left(\\begin{matrix}\nx - Lf\\\\ \n\\dot{x} - e\n\\end{matrix}\\right) = 0.\n$$\n\n\n\n\n \n\n\n\n\n\n## Port-Hamiltonains\n\nOne can show that for conservative systems, one can define a storage function $H(x)$ and choose \n\n$$\\Phi(\\dot{x}, x, f,e,t) = \n\\left(\\begin{matrix}\n\\dot{x} - f\\\\\ne - \\nabla_x H(x)\n\\end{matrix}\\right) = 0.$$\n\nTo recover Hamiltons equations, one must additionally connect ports $(e,f)_i$ to $(e,f)_j$, and hence impose a particular _Dirac structure_ on $\\mathcal{D}$.\n\n**Example (Harmonic Oscillator Part 1)**\nGiven the storage function\n\n$$H(x) = \\frac{\\omega}{2}(x_1^2 + x_2^2)$$ \n\nwe have\n\n$$\\Phi(\\dot{x},e,f,x) = (e_1 - \\omega x_1, f_1-\\dot{x}_1, e_2-\\omega x_2, f_2-\\dot{x}_2) = 0.$$\n\n\n\n \n\n\n\n\n\n# Connecting Ports\n\nTwo ports can be connected with via a _Dirac structure_\n\n**Example (Common Effort Bond)**\n\nA common _effort_ or force connection is simply the power conserving relation $e_1 =e_2$ and $f_1 = -f_2$. \n\nThis can be interpreted as \n\n$$\n\\Phi_\\text{Bond}(e,f) = \\left(e_1 - e_2, f_1 + f_2\\right) = 0\n$$\n\n\n\n\n\n \n\n\n\n\n\n## Conservation Laws\n\n**Example (0 Junction)**\n\nOne can define 'conservation of mass' (equally Kirchoffs voltage law) as \n\n$$\n\\Phi(e,f) \n=\n\\left(\\begin{matrix}\ne_1 - e_2\\\\\n\\vdots\\\\\ne_1 - e_{n}\\\\\n\\sum_{k=1}^n f_n\n\\end{matrix}\\right) = 0.$$\n\none can easily check that this implies\n\n$$\nP_\\text{in} = \\sum_{k=1}^n e_kf_k = 0.\n$$\n\nThis is called the 'zero junction' for historical reasons...\n\n\n \n\n\n \n\n\n\n\n## Dissipation\n\n**Example (Dissipation)**\n\nLinear Dissipation has no state and relates effort $e$ to flow $f$:\n\n$$ \\Phi_\\text{R}(e,f) = \ne_1 - Rf_1 =0$$\n\nsuch that the power entering the subsystem\n\n$$P_\\text{in} = e_1f_1 = R (f_1)^2 \\ge 0$$\n\nis always positive, hence dissipation.\n\n\n \n\n\n \n\n\n\n\n\n\n```python\n\n```\n\n## Inheritance\n\nFor energetic systems:\n\n### Nodes are particular _energetic systems_ \nEach node is described by a set of differential-algebraic equations $\\Phi(\\dot{x},x,e,f) = 0$.\n\n### Edges are constraints on port variables.\n\nAn edge represents how state is shared between systems.\n\n\n\n\n\n## Composition\n\n \n\nFor networked dynamic systems _composition_ means that we can replace nodes with subgraphs and vice-versa.\n\n\n\n\n\n## Corollary (Composition)\nIf $\\Psi_1 = (M_1, \\mathcal{D}_1, U_1,\\Phi_1)$ and $\\Psi_2 = (M_2, \\mathcal{D}_2, U_2,\\Phi_2)$ are energetic systems, then \n\n$$\\begin{eqnarray}\\Psi_0 &=& \\Psi_1 \\oplus\\Psi_2\\\\\n&=& \n\\left(M_1\\oplus M_2,\\mathcal{D}_1 \\oplus\\mathcal{D}_2,U_1\\oplus U_2, \\Phi_1\\oplus\\Phi_2\\right)\n\\end{eqnarray}$$\nis also an energetic system.\n\nSuppose (abusing notation) $\\Psi_0 = (\\Psi_1,\\Psi_2)$ is an energetic system with ports \n\n$$(e_i, f_i) \\in \\mathcal{D}_1, \\quad (e_j,f_j) \\in \\mathcal{D}_2$$\n\nThen $\\Phi_0$ with the additional power conserving constraint \n\n$$e_i - e_j = 0\\qquad f_i+f_j=0$$\n\nis also a energetic system\n\n\n\n\n\n## Encapsulation\n\n \n\nFor a networked dynamical system _encapsulation_ means that we can apply simplification methods to a subgraph so that the replacement system is less complicated, while representing the same behaviour.\n\n \n\nOne can also go the other way by replacing a node with a more complicated subgraph.\n\n\n\n# Example: Linear Damped Harmonic Motion\n\nConsider the following __nodes__\n$$\n\\Phi_\\text{C}= \n\\left(\\begin{matrix}\nx_c - Ce_c\\\\ \n\\dot{x}_c - f_c\n\\end{matrix}\\right)\n$$\n\n$$\n\\Phi_\\text{L} = \n\\left(\\begin{matrix}\nx_L - Lf_L\\\\ \n\\dot{x}_L - e_L\n\\end{matrix}\\right)\n$$\n\n$$ \\Phi_\\text{R} = \n(e_R - Rf_R)$$\n\n$$\n\\Phi_\\text{0}\n=\n\\left(\\begin{matrix}\ne_1 - e_2\\\\\ne_1 - e_3\\\\\ne_1 - e_\\text{port}\\\\\nf_1+f_2+f_3 + f_\\text{port}\n\\end{matrix}\\right)$$\n\nWiththe __edges__ as power connections:\n\n$$P_1 = P_c,\\qquad P_2 = P_L\\qquad P_3 = P_R.$$\n\nRecall $P_1 = P_c$ implies \n$$e_1 = e_c\\qquad f_1 = -f_c$$\n\nSince $\\Phi_0$ implies $e$ are equal\n$$\ne_\\text{port} = \\frac{1}{C}x_c = \\dot{x}_L = rf_R\n$$\nand the 'flow' sum gives\n$$\nf_\\text{port} = \\dot{x}_c + \\frac{1}{RC}x_c +\\frac{1}{L}x_L \n$$\n\nIf there is no flow allowed through $f_\\text{port}$, then we have the usual equation for damped harmonic motion.\n\n- It is not difficult to extend this to nonlinaer $\\Phi$\n- _Most of the heavy lifting can be done via linear algebra_\n\n## Object Oriented Modelling and Energetic Systems\n\nEnergetic systems provide:\n- _Inheritance_; an abstract base representation of energetic systems.\n- _Composition_; a way to hierarchically compose systems of systems.\n- _Encapsulation_; a framework inside which simplifications can occur.\n\n
By systematically modelling physical systems, we can begin to understand system dynamics, and hence emergence.
\n\n  \n\n  \n\n  \n\n# `BondGraphTools`\n\n## `BondGraphTools`: a `python` library for energetic systems.\n\n`BondGraphTools` (https://github.com/BondGraphTools) a framework for modelling energetic systems.\n* Based upon an extension of bond graph and port-Hamiltonian modelling.\n* Provies a simple, *minimal* object-oriented interface for constructing models.\n* Implemented in `python` and uses the standard `scipy` stack.\n* Performs symbolic model reduction and simulation.\n* Simulations with DAE solvers in `julia`.\n* Developed with sustainable software practices.\n* Intended to be used in _conjunction_ with other tools.\n\n'Bond Graphs' are a multi-domain port-based graphical modelling technique used predominantly in mechatronics. \nPort-Hamiltonian systems integrate geometric approaches from classical mechanics and control theory with port based modelling. \n\n## `BondGraphTools` is an API for modelling energetic systems\n\n \n\n
Hence modelling a complex physical system is equivalent to writing code
\n\n## Example: Linear Oscillator\n\n\n```python\nclass Linear_Osc(bgt.BondGraph): \n damping_rate = 0.1 #D amping rate common across oscillator array\n \n def __init__(self, freq, index):\n \"\"\"Linear Oscillator Class\n\n Args:\n freq: Natural (undamped) frequency of this oscillator\n index: Oscillator number (used for naming).\n \n Instances of this class are bond graph models of externally forced\n damped harmonic oscillators. \n In the electrical analogy, these is simply an open loop series RLC \n circuit.\"\"\"\n\t\n # Create the components\n r = bgt.new(\"R\", name=\"R\", value=self.damping_rate)\n l = bgt.new(\"I\", name=\"L\", value=1/freq)\n c = bgt.new(\"C\", name=\"C\", value=1/freq)\n port = bgt.new(\"SS\")\n conservation_law = bgt.new(\"1\")\n\t\n # Create the composite model and add the components\n super().__init__(\n name=f\"Osc_{index}\",\n components=(r, l, c, port, conservation_law)\n )\n\t\n # Wire the model up\n for component in (r,l,c):\n bgt.connect(conservation_law, component)\n bgt.connect(port, conservation_law)\n \n # Expose the SS component as an external port\n bgt.expose(port, label=\"P_in\")\n```\n\n`Linear_Osc` \n- _inherits_ from BondGraph, which is a base 'class' containing much of functionality\n- is _composed_ of a variety of subcomponents\n- _encapsulates_ a one port RLC component.\n\n\n\n```python\nexample_osc = Linear_Osc(1000,1)\nexample_osc.constitutive_relations \n```\n\n## Automating Model Capture\n\n\n```python\nfrom BondGraphTools.reaction_builder import Reaction_Network\n\nTCA_reactions = {\n \"Citrate synthase\": \n [\"acetyl-CoA + oxaloacetate + H2O = citrate + CoA-SH\"],\n \"Aconitase\": \n [\"Citrate = cis-Aconitate + H2O\", \"cis-Aconitate + H2O = Isocitrate\"],\n \"Isocitrate dehydrogenase\": \n [\"Isocitrate + NAD = Oxalosuccinate + NADH + H\", \n \"Oxalosuccinate = a-Ketoglutarate + CO2\" ],\n \"a-Ketoglutarate dehydrogenase\": \n [\"a-Ketoglutarate + NAD + CoA-SH = Succinyl-CoA + NADH + H + CO2\"],\n \"Succinyl-CoA synthetase\": \n [\"Succinyl-CoA + ADP + Pi = Succinate + CoA-SH + ATP\"],\n \"Succinate dehydrogenase\": \n [\"Succinate + Q = Fumarate + QH2\"],\n \"Fumarase\":\n [\"Fumarate + H2O = L-Malate\"],\n \"Malate dehydrogenase\":\n [\"L-Malate + NAD = Oxaloacetate + NADH + H\"]\n} \n\ndef TCA_Cycle():\n reaction_net = Reaction_Network(name=\"TCA_Cycle\")\n for enzyme in TCA_reactions:\n for index, reaction in enumerate(TCA_reactions[enzyme]):\n reaction_name = f\"{enzyme} - {index}\"\n reaction_net.add_reaction(reaction, name=reaction_name)\n return reaction_net \n```\n\n\n```python\ntca_bg = TCA_Cycle().as_network_model()\ntca_bg.constitutive_relations\n```\n\n## Constructing big models with BondGraphTools.\n1. Define the _nodes_ (processes that act on energy).\n2. Define the _edges_ (the 'power ports', or shared variables).\n3. Feed this into `BondGraphTools`.\n4. ...?\n5. Profit! (Use the resulting equations of motion for whatever you want). \n\n\n\n```python\nbgt.draw(tca_bg)\nplt.show()\n```\n\n\n \n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n## State of `BondGraphTools`\n\nCurrent Status:\n- In active development (v.0.3.7) and active use within the lab.\n- Documentation at https://bondgraphtools.readthedocs.io/en/latest/\n- Available on PyPI https://pypi.org/project/BondGraphTools/\n- Source on GitHub https://github.com/BondGraphTools/BondGraphTools\n- Manuscript in preparation.\n\n### Planned Future Developments\n- Extraction of first integrals and invariant manifolds.\n- Robust parameter and control value network.\n- Interface for measuring port space.\n- Algorithmic model reduction (particularly manifold reductions).\n- Bifurcation analysis (particularly fixed point tracking).\n\n# In Summary\n\n- Energetic Modelling gives us a framework to systematically desrcibe complex physical systems.\n\n- `BondGraphTools` provides a way to build and recude big model in symbolic form.\n\n\n- The resutls can feed into algorithmic model reduction, parameter estimation and sensitivity analysis.\n\n# Thank You!\n\nThanks to\n- Vera, Amadine and Gary\n- The University of New South Wales\n- Prof. Edmund Crampin, Prof. Peter Gawthrop, Michael Pan.\n- The Systems Biology Lab at The University of Melbourne\n\n\n \n \n \n \n
\n\n \n\n \n\n# Please check out `BondGraphTools`\n\n# https://github.com/BondGraphTools/\n\n\n```python\nprint_tree(tca_bg)\n```\n\n BG: TCA_Cycle\n |-1: OxaloacetateNADHH\n |-1: L-MalateNAD\n |-R: Malate dehydrogenase - 0\n |-1: FumarateH2O\n |-R: Fumarase - 0\n |-1: FumarateQH2\n |-1: SuccinateQ\n |-R: Succinate dehydrogenase - 0\n |-1: SuccinateCoA-SHATP\n |-1: Succinyl-CoAADPPi\n |-R: Succinyl-CoA synthetase - 0\n |-1: Succinyl-CoANADHHCO2\n |-1: a-KetoglutarateNADCoA-SH\n |-R: a-Ketoglutarate dehydrogenase - 0\n |-1: a-KetoglutarateCO2\n |-R: Isocitrate dehydrogenase - 1\n |-1: OxalosuccinateNADHH\n |-1: IsocitrateNAD\n |-R: Isocitrate dehydrogenase - 0\n |-1: cis-AconitateH2O\n |-R: Aconitase - 1\n |-1: cis-AconitateH2O\n |-R: Aconitase - 0\n |-1: citrateCoA-SH\n |-1: acetyl-CoAoxaloacetateH2O\n |-R: Citrate synthase - 0\n |-C: Oxaloacetate\n |-0: L-Malate\n |-C: L-Malate\n |-C: QH2\n |-0: Fumarate\n |-C: Fumarate\n |-C: Q\n |-C: ATP\n |-0: Succinate\n |-C: Succinate\n |-C: Pi\n |-C: ADP\n |-0: Succinyl-CoA\n |-C: Succinyl-CoA\n |-0: CO2\n |-C: CO2\n |-0: a-Ketoglutarate\n |-C: a-Ketoglutarate\n |-0: H\n |-C: H\n |-0: NADH\n |-C: NADH\n |-0: Oxalosuccinate\n |-C: Oxalosuccinate\n |-0: NAD\n |-C: NAD\n |-0: Isocitrate\n |-C: Isocitrate\n |-0: cis-Aconitate\n |-C: cis-Aconitate\n |-C: Citrate\n |-0: CoA-SH\n |-C: CoA-SH\n |-C: citrate\n |-0: H2O\n |-C: H2O\n |-C: oxaloacetate\n |-C: acetyl-CoA\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "6902100a9e62313221855ede2263cfeabc80ec4b", "size": 477388, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Sydney2019/seminar_2.ipynb", "max_stars_repo_name": "peter-cudmore/seminars", "max_stars_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sydney2019/seminar_2.ipynb", "max_issues_repo_name": "peter-cudmore/seminars", "max_issues_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sydney2019/seminar_2.ipynb", "max_forks_repo_name": "peter-cudmore/seminars", "max_forks_repo_head_hexsha": "bdc60024e5c43c41cff5a7bc86c2810323ef0f70", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 92.949376947, "max_line_length": 81873, "alphanum_fraction": 0.7700109764, "converted": true, "num_tokens": 7346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.32020412364706874}} {"text": "```python\nfrom IPython.display import HTML\nHTML(\"\"\"\n

\n\nCUSPEA Talks\n\n

\n
\n\"\"\")\n```\n\n\n\n\n\n

\n\nCUSPEA Talks\n\n

\n
\n\n\n\n\n\n```python\n\n```\n\n# Fun with [Jupyter](http://jupyter.org/)\n\n## Table of Contents\n\n* [Motivation](#hid_why)\n* [Introduction](#hid_intro)\n* [Problem Statement](#hid_problem)\n* [Import packages](#hid_pkg)\n* [Estimate x range](#hid_guess)\n* [Use IPython as a calculator](#hid_calculator)\n* [Use Python programming to find solution](#hid_program)\n* [Graph the solution with matplotlib](#hid_graph)\n* [Solve equation precisely using SymPy](#hid_sympy)\n* [Pandas for Big Data Analytics](#hid_panda)\n* [Multimedia with HTML5 -Text, Image, Audio, Video](#hid_html5)\n* [Interactive widgets](#hid_widget)\n* [Working with SQLite Databases](#hid_sqlite)\n* [References](#hid_ref)\n* [Contributors](#hid_author)\n* [Appendix](#hid_apend)\n - [How to install Jupyter Notebook](#hid_setup)\n - [How to share a notebook](#hid_share)\n \n\n## Motivation \n\n* Current Choice\n\n\n\n* A New Option\n\n> The __Jupyter Notebook__ is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more.\n\nUseful for many tasks\n\n* Programming\n* Blogging\n* Learning\n* Research\n* Documenting work\n* Collaborating\n* Communicating\n* Publishing results\n\nor even\n\n* Doing homework as a student\n\n\n\n```python\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\nSee this [Demo Notebook](https://nbviewer.jupyter.org/github/waltherg/notebooks/blob/master/2013-12-03-Crank_Nicolson.ipynb) \n\n\n\n## Introduction \n\nBy solving a simple math problem here, I hope to demonstrate many basic features of Jupyter Notebook. \n\n## Problem Statement \n\nA hot startup is selling a hot product. \n\nIn 2014, it had 30 customers; 3 years later, its customer base expands to 250.\n\nQuestion: What is its annual growth rate?\n\n_Translate into math:_ Let $x$ be annual growth rate, \n\nthen\n$$ 30 \\cdot (1 + x)^3 = 250 $$\n\n## Import packages (check out from Library)\n\n\n```python\n# math function\nimport math\n\n# create np array\nimport numpy as np\n\n# pandas for data analysis\nimport pandas as pd\n\n# plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n# symbolic math\nimport sympy as sy\n\n# html5\nfrom IPython.display import HTML, SVG, YouTubeVideo\n\n# widgets\nfrom collections import OrderedDict\nfrom IPython.display import display, clear_output\nfrom ipywidgets import Dropdown\n\n# csv file\nimport csv\n\n# work with Sqlite database\nimport sqlite3\n```\n\n## Estimate x range (in Elementary School)\n\nIf $x$ = 1, then _l.h.s_ = 240, therefore $x$ > 1\n\nIf $x$ = 1.2, then l.h.s = \n\n\n```python\n30*(1+1.2)**3\n```\n\n\n\n\n 319.4400000000001\n\n\n\ntherefore we know $x$ range = (1.0, 1.2)\n\n## Use IPython as a calculator (in Middle School)\n\n\n```python\n# import math\n```\n\n\n```python\nmath.exp(math.log(250/30)/3) - 1\n```\n\n\n\n\n 1.0274006651911334\n\n\n\n\n```python\n10**(math.log10(250/30)/3) - 1\n```\n\n\n\n\n 1.0274006651911334\n\n\n\n\n```python\nmath.pow(10, math.log10(250/30)/3) -1\n```\n\n\n\n\n 1.0274006651911334\n\n\n\n** annual customer growth rate = 102% **\n\n## Use Python programming to find solution (in High School)\n\n### use loop\n\n\n```python\nnstep = 100\nx_min, x_max = 1.0, 1.2\ndd = (x_max-x_min)/float(nstep)\nx_l = [(x_min + i*dd) for i in range(nstep)]\ntype(x_l)\n```\n\n\n\n\n list\n\n\n\n\n```python\nprint(x_l)\n```\n\n [1.0, 1.002, 1.004, 1.006, 1.008, 1.01, 1.012, 1.014, 1.016, 1.018, 1.02, 1.022, 1.024, 1.026, 1.028, 1.03, 1.032, 1.034, 1.036, 1.038, 1.04, 1.042, 1.044, 1.046, 1.048, 1.05, 1.052, 1.054, 1.056, 1.058, 1.06, 1.062, 1.064, 1.066, 1.068, 1.07, 1.072, 1.074, 1.076, 1.078, 1.08, 1.082, 1.084, 1.086, 1.088, 1.09, 1.092, 1.094, 1.096, 1.0979999999999999, 1.1, 1.1019999999999999, 1.104, 1.1059999999999999, 1.108, 1.1099999999999999, 1.1119999999999999, 1.1139999999999999, 1.1159999999999999, 1.1179999999999999, 1.1199999999999999, 1.1219999999999999, 1.1239999999999999, 1.126, 1.128, 1.13, 1.132, 1.134, 1.136, 1.138, 1.14, 1.142, 1.144, 1.146, 1.148, 1.15, 1.152, 1.154, 1.156, 1.158, 1.16, 1.162, 1.164, 1.166, 1.168, 1.17, 1.172, 1.174, 1.176, 1.178, 1.18, 1.182, 1.184, 1.186, 1.188, 1.19, 1.192, 1.194, 1.196, 1.198]\n\n\n\n```python\nfor t in x_l:\n err = abs(30*(1+t)**3 - 250)\n if err <= 0.5:\n print(\"t={x}: error={e:.4f}\".format(x=t,e=err))\n```\n\n t=1.028: error=0.2218\n\n\n### create a numpy array\n\n\n```python\n# import numpy as np\n# import pandas as pd\n```\n\n\n```python\nprint(x_l)\n```\n\n [1.0, 1.002, 1.004, 1.006, 1.008, 1.01, 1.012, 1.014, 1.016, 1.018, 1.02, 1.022, 1.024, 1.026, 1.028, 1.03, 1.032, 1.034, 1.036, 1.038, 1.04, 1.042, 1.044, 1.046, 1.048, 1.05, 1.052, 1.054, 1.056, 1.058, 1.06, 1.062, 1.064, 1.066, 1.068, 1.07, 1.072, 1.074, 1.076, 1.078, 1.08, 1.082, 1.084, 1.086, 1.088, 1.09, 1.092, 1.094, 1.096, 1.0979999999999999, 1.1, 1.1019999999999999, 1.104, 1.1059999999999999, 1.108, 1.1099999999999999, 1.1119999999999999, 1.1139999999999999, 1.1159999999999999, 1.1179999999999999, 1.1199999999999999, 1.1219999999999999, 1.1239999999999999, 1.126, 1.128, 1.13, 1.132, 1.134, 1.136, 1.138, 1.14, 1.142, 1.144, 1.146, 1.148, 1.15, 1.152, 1.154, 1.156, 1.158, 1.16, 1.162, 1.164, 1.166, 1.168, 1.17, 1.172, 1.174, 1.176, 1.178, 1.18, 1.182, 1.184, 1.186, 1.188, 1.19, 1.192, 1.194, 1.196, 1.198]\n\n\n#### using arange()\n\n\n```python\nx = np.arange(1.0, 1.2, 0.005)\nprint(x)\n```\n\n [ 1. 1.005 1.01 1.015 1.02 1.025 1.03 1.035 1.04 1.045\n 1.05 1.055 1.06 1.065 1.07 1.075 1.08 1.085 1.09 1.095 1.1\n 1.105 1.11 1.115 1.12 1.125 1.13 1.135 1.14 1.145 1.15\n 1.155 1.16 1.165 1.17 1.175 1.18 1.185 1.19 1.195]\n\n\ncheck its type\n\n\n```python\ntype(x)\n```\n\n\n\n\n numpy.ndarray\n\n\n\n\n```python\nlen(x)\n```\n\n\n\n\n 40\n\n\n\n\n```python\nprint(30*(1+x)**3 - 250)\n```\n\n [-10. -8.19549625 -6.38197 -4.55939875 -2.72776 -0.88703125\n 0.96281 2.82178625 4.68992 6.56723375 8.45375 10.34949125\n 12.25448 14.16873875 16.09229 18.02515625 19.96736 21.91892375\n 23.87987 25.85022125 27.83 29.81922875 31.81793 33.82612625\n 35.84384 37.87109375 39.90791 41.95431125 44.01032 46.07595875\n 48.15125 50.23621625 52.33088 54.43526375 56.54939 58.67328125\n 60.80696 62.95044875 65.10377 67.26694625]\n\n\n\n```python\nx_ge_0 = (30*(1+x)**3 - 250) >= 0\nx_ge_0\n```\n\n\n\n\n array([False, False, False, False, False, False, True, True, True,\n True, True, True, True, True, True, True, True, True,\n True, True, True, True, True, True, True, True, True,\n True, True, True, True, True, True, True, True, True,\n True, True, True, True], dtype=bool)\n\n\n\n\n```python\nx_lt_0 = (30*(1+x)**3 - 250) < 0\nx_lt_0\n```\n\n\n\n\n array([ True, True, True, True, True, True, False, False, False,\n False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n False, False, False, False, False, False, False, False, False,\n False, False, False, False], dtype=bool)\n\n\n\nx_ge_0 and x_lt_0 are logical array\n\n\n```python\nfor t in x:\n err = abs(30*(1+t)**3 - 250)\n if err <= 1.0:\n print(\"t={x}: error={e:.4f}\".format(x=t,e=err))\n```\n\n t=1.0249999999999995: error=0.8870\n t=1.0299999999999994: error=0.9628\n\n\n#### using [linspace](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html)\n\n\n```python\nx1 = np.linspace(1.0, 1.2, 100)\nx1\n```\n\n\n\n\n array([ 1. , 1.0020202 , 1.0040404 , 1.00606061, 1.00808081,\n 1.01010101, 1.01212121, 1.01414141, 1.01616162, 1.01818182,\n 1.02020202, 1.02222222, 1.02424242, 1.02626263, 1.02828283,\n 1.03030303, 1.03232323, 1.03434343, 1.03636364, 1.03838384,\n 1.04040404, 1.04242424, 1.04444444, 1.04646465, 1.04848485,\n 1.05050505, 1.05252525, 1.05454545, 1.05656566, 1.05858586,\n 1.06060606, 1.06262626, 1.06464646, 1.06666667, 1.06868687,\n 1.07070707, 1.07272727, 1.07474747, 1.07676768, 1.07878788,\n 1.08080808, 1.08282828, 1.08484848, 1.08686869, 1.08888889,\n 1.09090909, 1.09292929, 1.09494949, 1.0969697 , 1.0989899 ,\n 1.1010101 , 1.1030303 , 1.10505051, 1.10707071, 1.10909091,\n 1.11111111, 1.11313131, 1.11515152, 1.11717172, 1.11919192,\n 1.12121212, 1.12323232, 1.12525253, 1.12727273, 1.12929293,\n 1.13131313, 1.13333333, 1.13535354, 1.13737374, 1.13939394,\n 1.14141414, 1.14343434, 1.14545455, 1.14747475, 1.14949495,\n 1.15151515, 1.15353535, 1.15555556, 1.15757576, 1.15959596,\n 1.16161616, 1.16363636, 1.16565657, 1.16767677, 1.16969697,\n 1.17171717, 1.17373737, 1.17575758, 1.17777778, 1.17979798,\n 1.18181818, 1.18383838, 1.18585859, 1.18787879, 1.18989899,\n 1.19191919, 1.19393939, 1.1959596 , 1.1979798 , 1.2 ])\n\n\n\n\n```python\nfor t in x1:\n err = math.fabs(30*(1+t)**3 - 250)\n if err <= 1.0:\n print(\"t={x}: error={e:.4f}\".format(x=t,e=err))\n```\n\n t=1.0262626262626262: error=0.4208\n t=1.0282828282828282: error=0.3265\n\n\n## Graph the solution using Matplotlib (in High School)\n\n\n\n\n[matplotlib](http://matplotlib.org/contents.html?v=20170307111739) is visualization pkg for python\n\n\n```python\n# import matplotlib.pyplot as plt\n# %matplotlib inline\n```\n\n\n```python\nx2 = np.linspace(1.0, 1.05, 100)\nf1 = 30*(1+x2)**3 - 250\n\nf2 = np.zeros_like(x2) # draw a horizontal line at y=0\n```\n\n$x$ intersection of two lines f1/f2 gives the solution\n\n\n```python\nplt.xlabel(r'$x$')\nplt.ylabel(r'$\\delta$')\nplt.grid(True)\nplt.title('IPython is a great analytical tool')\nplt.axis([0.995,1.055, -11, 9])\n#plt.axis([1.02, 1.04, -11, 9])\nplt.plot(x2, f1, 'r+')\nplt.plot(x2, f2, 'b-', lw=2)\nplt.show()\n```\n\n## Solve equation precisely using SymPy (in High School) \n\n\n```python\n# from sympy import *\n# import sympy as sy\n```\n\n\n```python\nsy.var('x')\n```\n\n\n\n\n x\n\n\n\n\n```python\nsy.solve(30*(1+x)**3 - 250, x)\n```\n\n\n\n\n [-1 + 15**(2/3)/3,\n -1 + 15**(2/3)*(-1/2 - sqrt(3)*I/2)/3,\n -1 + 15**(2/3)*(-1/2 + sqrt(3)*I/2)/3]\n\n\n\nIgnore other 2 solutions because they are complex numbers\n\n\n```python\ngrow_rate = -1 + 15**(2/3)/3\ngrow_rate\n```\n\n\n\n\n 1.027400665191133\n\n\n\n## Pandas for Big Data Analytics (in College) \n\n[pandas](http://pandas.pydata.org/pandas-docs/stable/?v=20170307111739) stands for powerful Python data analysis toolkit\n\n\n```python\n# import pandas as pd\n```\n\n\n```python\nyear = [2014, 2015, 2016, 2017]\n```\n\n\n```python\ncustomer_count = [30*(1+grow_rate)**i for i in range(4)]\nprint(customer_count)\n```\n\n [30.0, 60.822019955733985, 123.31060371652346, 249.9999999999998]\n\n\n\n```python\ndf = pd.DataFrame(list(zip(year,customer_count)), columns=['Year','Customers'])\ndf\n```\n\n\n\n\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
YearCustomers
0201430.000000
1201560.822020
22016123.310604
32017250.000000
\n
\n\n\n\n\n```python\ndf.head(2)\n```\n\n\n\n\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
YearCustomers
0201430.00000
1201560.82202
\n
\n\n\n\n\n```python\ndf.tail(2)\n```\n\n\n\n\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
YearCustomers
22016123.310604
32017250.000000
\n
\n\n\n\n#### Line chart\n\n\n```python\nplt.plot(df['Year'], df['Customers'])\n```\n\n#### Bar chart\n\n\n```python\nplt.xlabel('Year')\nplt.ylabel('Customer Count')\nplt.grid(True)\nplt.title('Customer Growth')\n\nplt.bar(df['Year'], df['Customers'])\n\nplt.plot(df['Year'], df['Customers'], 'r-')\n```\n\n## Multimedia with HTML5 -Text, Image, Audio, Video (Having graduated from all the schools)\n\n\n```python\n# from IPython.display import HTML, SVG, YouTubeVideo\n```\n\n### create an HTML table dynamically with Python, and we display it in the (HTML-based) notebook.\n\nLet me create a multiplication table\n\n\n```python\nHTML('''\n\n''' + \n''.join(['' + \n ''.join([''.format(\n row=row, col=col, prod=row*col\n ) for col in range(10)]) +\n '' for row in range(10)]) +\n'''\n
{row}x{col}={prod}
\n''')\n```\n\n\n\n\n\n\n\n
0x0=00x1=00x2=00x3=00x4=00x5=00x6=00x7=00x8=00x9=0
1x0=01x1=11x2=21x3=31x4=41x5=51x6=61x7=71x8=81x9=9
2x0=02x1=22x2=42x3=62x4=82x5=102x6=122x7=142x8=162x9=18
3x0=03x1=33x2=63x3=93x4=123x5=153x6=183x7=213x8=243x9=27
4x0=04x1=44x2=84x3=124x4=164x5=204x6=244x7=284x8=324x9=36
5x0=05x1=55x2=105x3=155x4=205x5=255x6=305x7=355x8=405x9=45
6x0=06x1=66x2=126x3=186x4=246x5=306x6=366x7=426x8=486x9=54
7x0=07x1=77x2=147x3=217x4=287x5=357x6=427x7=497x8=567x9=63
8x0=08x1=88x2=168x3=248x4=328x5=408x6=488x7=568x8=648x9=72
9x0=09x1=99x2=189x3=279x4=369x5=459x6=549x7=639x8=729x9=81
\n\n\n\n\n### display image\n\n\n```python\nHTML(\"\"\"\n\n\"\"\")\n```\n\n\n\n\n\n\n\n\n\n\n### create a SVG graphics dynamically.\n\n\n```python\nSVG('''''' + \n''.join(['''\n '''.format(\n x=(30+3*i)*(10-i), y=30, r=3.*float(i)\n ) for i in range(10)]) + \n'''''')\n```\n\n\n\n\n \n\n \n\n\n\n### embed an audio clip\n\n\n```python\nHTML(\"\"\"\n\n\n\n\n\n
\nTalkPython \n

Guido van Rossum

(Python Creator & Tsar)\n

Python past, present, and future

\n
\n\n
\n\n
\n\"\"\")\n\n```\n\n\n\n\n\n\n\n\n\n\n
\nTalkPython \n

Guido van Rossum

(Python Creator & Tsar)\n

Python past, present, and future

\n
\n\n
\n\n
\n\n\n\n\n### display a Youtube video by giving its identifier to YoutubeVideo.\n\n#### SciPy 2013 Keynote: IPython\n\n\n```python\nYouTubeVideo('j9YpkSX7NNM')\n```\n\n\n\n\n\n\n\n\n\n\n## Interactive widgets \n\nwe illustrate the latest interactive features in IPython 2.0+. \n\nThis version brings graphical widgets in the notebook that can interact with Python objects. \n\nWe will create a drop-down menu allowing us to display one among several videos.\n\n\n```python\n# How to comment out multiple lines of code in python\n\"\"\" \nfrom collections import OrderedDict\nfrom IPython.display import display, clear_output\nfrom ipywidgets import Dropdown\n\"\"\"\n```\n\n\n\n\n ' \\nfrom collections import OrderedDict\\nfrom IPython.display import display, clear_output\\nfrom ipywidgets import Dropdown\\n'\n\n\n\n\n```python\n# We create a Dropdown widget, with a dictionary containing\n# the keys (video name) and the values (Youtube identifier) of every menu item.\n\ndw = Dropdown(options=OrderedDict([\n ('SciPy 2012', 'iwVvqwLDsJo'), \n ('PyCon 2012', '2G5YTlheCbw'),\n ('SciPy 2013', 'j9YpkSX7NNM'),\n ('Guido Van Rossum', 'EBRMq2Ioxsc'),\n ('Mendelssohn Violin', 'o1dBg__wsuo')\n ]))\n\n# We create a callback function that displays the requested Youtube video.\ndef on_value_change(name, val):\n clear_output()\n display(YouTubeVideo(val))\n# Every time the user selects an item, the function\n# `on_value_change` is called, and the `val` argument\n# contains the value of the selected item.\ndw.on_trait_change(on_value_change, 'value')\n# We choose a default value.\ndw.value = dw.options['Mendelssohn Violin']\n\n# Finally, we display the widget.\ndisplay(dw)\n```\n\n\n\n\n\n\n\n Widget Javascript not detected. It may not be installed properly. Did you enable the widgetsnbextension? If not, then run \"jupyter nbextension enable --py --sys-prefix widgetsnbextension\"\n\n\n## Working with SQLite Databases \n\nread [blog](https://www.dataquest.io/blog/python-pandas-databases/) at [DataQuest](https://www.dataquest.io)\n\n\n```python\n# open connection to db\nconn = sqlite3.connect(\"dataset/open_src.sqlite\")\n\n# create a cursor\ncur = conn.cursor()\n\n# select query\nresults = cur.execute(\"select * from os_history limit 100;\").fetchall()\n#print(results)\n\n# count # of rows\nresults = cur.execute(\"select count(*) from os_history;\").fetchall()\n#print(results)\n\n# store data from csv file into db\nwith open('dataset/open_src_move_v2_1.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n #print(row['Year'])\n insert_str=\"\"\"\n insert into os_history(year,subject,subjecturl,person,picture,history)\n values ({year}, \"{subject}\", \"{subject_url}\", \"{person}\", \"{picture}\", \"{history}\")\n \"\"\"\n #print(insert_str.format(year=row['Year'],subject=row['Subject'],subject_url=row['SubjectURL'],person=row['Person'],picture=row['Picture'],history=row['History']))\n cur.execute(insert_str.format(year=row['Year'],subject=row['Subject'],subject_url=row['SubjectURL'],person=row['Person'],picture=row['Picture'],history=row['History']))\n conn.commit()\n \n# create a dataframe\ndf = pd.read_sql_query(\"select * from os_history limit 5;\",conn)\n\n# inspect data\ndf\n```\n\n\n\n\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
yearsubjectsubjecturlpersonpicturehistory
01983GNU Project : gcc, Emacs, gdbhttps://en.wikipedia.org/wiki/GNU_ProjectRichard Stallmanhttps://upload.wikimedia.org/wikipedia/commons...Launch of the free software movement and found...
11984X Window Systermhttps://en.wikipedia.org/wiki/X_Window_SystemX.Orghttps://upload.wikimedia.org/wikipedia/commons...basic framework for a GUI environment
21983GNU Project : gcc, Emacs, gdbhttps://en.wikipedia.org/wiki/GNU_ProjectRichard Stallmanhttps://upload.wikimedia.org/wikipedia/commons...Launch of the free software movement and found...
31984X Window Systermhttps://en.wikipedia.org/wiki/X_Window_SystemX.Orghttps://upload.wikimedia.org/wikipedia/commons...basic framework for a GUI environment
41985GNU Manifesto: GNU's Not Unixhttps://en.wikipedia.org/wiki/GNU_ManifestoRichard Stallmanhttps://upload.wikimedia.org/wikipedia/en/thum...disagreement between Stallman and Symbolics, I...
\n
\n\n\n\n## References \n\n### Websites\n\n* [DataCamp - Jupyter Notebook Tutorial](https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook#gs.ClmI4Jc)\n\n\n* http://docs.python.org\n\nIt goes without saying that Python’s own online documentation is an excellent resource if you need to delve into the finer details of the language and modules. Just make sure you’re looking at the documentation for Python 3 and not earlier versions.\n\n* http://www.python.org/dev/peps\n\nPython Enhancement Proposals (PEPs) are invaluable if you want to understand the motivation for adding new features to the Python language as well as subtle implementation details. This is especially true for some of the more advanced language features. In writing this book, the PEPs were often more useful than the official documentation.\n\n* http://pyvideo.org\n\nThis is a large collection of video presentations and tutorials from past PyCon conferences, user group meetings, and more. It can be an invaluable resource for learning about modern Python development. Many of the videos feature Python core developers talking about the new features being added in Python 3.\n\n* http://code.activestate.com/recipes/langs/python\n\nThe ActiveState Python recipes site has long been a resource for finding the solution to thousands of specific programming problems. As of this writing, it contains approximately 300 recipes specific to Python 3. You’ll find that many of its recipes either expand upon topics covered in this book or focus on more narrowly defined tasks. As such, it’s a good companion.\n\n* http://stackoverflow.com/questions/tagged/python\n\nStack Overflow currently has more than 175,000 questions tagged as Python-related (and almost 5000 questions specific to Python 3). Although the quality of the questions and answers varies, there is a lot of good material to be found.\n\n### Books\n\n* [Learning IPython for Interactive Computing and Data Visualization - Second Edition (By Cyrille Rossant)](https://github.com/ipython-books/minibook-2nd-code)\n* [IPython Interactive Computing and Visualization Cookbook (By Cyrille Rossant)](https://github.com/ipython-books/cookbook-code)\n* [Python Cookbook, 3rd Edition by David Beazley; Brian K. Jones](https://github.com/dabeaz/python-cookbook)\n* [Python for Data Analysis by Wes McKinney](https://github.com/wesm/pydata-book)\n\n\n### Other Resources\n\n* Idea\n - [Google Search](http://www.google.com)\n* Text\n - [Wikipedia](https://www.wikipedia.org/)\n* Image\n - [Google Images](https://www.google.com/imghp)\n* Video\n - [YouTube](https://www.youtube.com/)\n\n\n## Contributors \n\n* wen.gong@oracle.com (first created on 2017-03-09)\n\n## Appendix \n\n### How to install Jupyter Notebook \n\nI use Windows and follow this link to [install Ananconda Python distribution](https://www.tensorflow.org/install/)\n\n* Follow the instructions on the [Anaconda download site](https://www.continuum.io/downloads) to download and install Anaconda.\n\n* open a DOS command box, launch jupyter by typing\n > jupyter notebook\n \n* wait till Jupyter homepage to open in a browser\n\n* start to create your own Notebook\n\n### How to share a notebook \n\nshare your learning or work via nbviewer at http://nbviewer.jupyter.org/\n\n\n```python\nHTML(\"\")\n```\n\n\n\n\n\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a148c55521beae26e635d9e0475599c10824f6cd", "size": 186061, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fun_with_jupyter.ipynb", "max_stars_repo_name": "wgong/open_source_learning", "max_stars_repo_head_hexsha": "ccf819626bf17125abcee8edf66401e4a0d2dc20", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-04-11T13:27:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-11T13:27:29.000Z", "max_issues_repo_path": "fun_with_jupyter.ipynb", "max_issues_repo_name": "wgong/open_source_learning", "max_issues_repo_head_hexsha": "ccf819626bf17125abcee8edf66401e4a0d2dc20", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2017-03-09T18:42:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-19T21:06:23.000Z", "max_forks_repo_path": "fun_with_jupyter.ipynb", "max_forks_repo_name": "wgong/open_source_learning", "max_forks_repo_head_hexsha": "ccf819626bf17125abcee8edf66401e4a0d2dc20", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5536048689, "max_line_length": 18665, "alphanum_fraction": 0.6780464471, "converted": true, "num_tokens": 9231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.31989712377313917}} {"text": "\n\n\n# Tutorial-IllinoisGRMHD: reconstruct_set_of_prims_PPM.C\n\n## Authors: Leo Werneck & Zach Etienne\n\n**This module is currently under development**\n\n## In this tutorial module we explain the piecewise parabolic method (PPM) used to reconstruct the primitive variables within IllinoisGRMHD\n\n### Required and recommended citations:\n\n* **(Required)** Etienne, Z. B., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L. IllinoisGRMHD: an open-source, user-friendly GRMHD code for dynamical spacetimes. Class. Quantum Grav. 32 (2015) 175009. ([arxiv:1501.07276](http://arxiv.org/abs/1501.07276)).\n* **(Required)** Noble, S. C., Gammie, C. F., McKinney, J. C., Del Zanna, L. Primitive Variable Solvers for Conservative General Relativistic Magnetohydrodynamics. Astrophysical Journal, 641, 626 (2006) ([astro-ph/0512420](https://arxiv.org/abs/astro-ph/0512420)).\n* **(Recommended)** Del Zanna, L., Bucciantini N., Londrillo, P. An efficient shock-capturing central-type scheme for multidimensional relativistic flows - II. Magnetohydrodynamics. A&A 400 (2) 397-413 (2003). DOI: 10.1051/0004-6361:20021641 ([astro-ph/0210618](https://arxiv.org/abs/astro-ph/0210618)).\n\nIf using the version of `IllinoisGRMHD` with piecewise polytropic *or* tabulated (coming soon!) EOS support, then the following citation is also required:\n\n* **(Required)** Etienne, Z. B., Werneck, L., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L., *IllinoisGRMHD github repository* (2019). Source Code URL: https://github.com/zachetienne/nrpytutorial/tree/master/IllinoisGRMHD/.\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis module is organized as follows\n\n0. [Step 0](#src_dir): **Source directory creation**\n1. [Step 1](#introduction): **Introduction**\n 1. [Step 1.a](#ppm): *The Piecewise Parabolic Method (PPM)*\n 1. [Step 1.b](#loop_defines_reconstruction): *The `loop_defines_reconstruction.h` header file*\n 1. [Step 1.c](#preamble_reconstruct_set_of_prims_ppm): *The preamble to the `reconstruct_set_of_prims_PPM.C` code file*\n1. [Step 2](#reconstruct_set_of_prims_ppm): **The `reconstruct_set_of_prims_PPM()` function**\n 1. [Step 2.a](#reading_the_input_gfs): *Reading the input gridfunctions*\n 1. [Step 2.b](#computation_of_du): *Evaluation of $\\delta U_{i}$*\n 1. [Step 2.c](#computation_of_ur_and_ul): *Computing $U_{r}$ and $U_{l}$*\n 1. [Step 2.d](#steepening_rhob): *Steepening $\\rho_{b}$*\n 1. [Step 2.e](#flattening_and_monotonizing): *Flattening and monotonizing*\n 1. [Step 2.f](#shifting_ur_and_ul): *Shifting $U_{r}$ and $U_{l}$*\n1. [Step 3](#slope_limit): **The `slope_limit()` function**\n1. [Step 4](#steepen_rho): **The `steepen_rho()` function**\n1. [Step 5](#monotonize): **The `monotonize()` function**\n1. [Step 6](#compute_p_cold__Gamma_cold): **The `compute_P_cold__Gamma_cold()` function**\n1. [Step 7](#ftilde_gf_compute): **The `ftilde_gf_compute()` function**\n1. [Step 8](#ftilde_compute): **The `ftilde_compute()` function**\n1. [Step 9](#code_validation): **Code validation**\n 1. [Step 9.a](#loop_defines_reconstruction__h_validation): *`loop_defines_reconstruction.h`*\n 1. [Step 9.b](#reconstruct_set_of_prims_ppm__c_validation): *`reconstruct_set_of_prims_PPM.C`*\n1. [Step 10](#latex_pdf_output): **Output this notebook to $\\LaTeX$-formatted PDF file**\n\n\n\n# Step 0: Source directory creation \\[Back to [top](#toc)\\]\n$$\\label{src_dir}$$\n\nWe will now use the [cmdline_helper.py NRPy+ module](Tutorial-Tutorial-cmdline_helper.ipynb) to create the source directory within the `IllinoisGRMHD` NRPy+ directory, if it does not exist yet.\n\n\n```python\n# Step 0: Creation of the IllinoisGRMHD source directory\n# Step 0a: Add NRPy's directory to the path\n# https://stackoverflow.com/questions/16780014/import-file-from-parent-directory\nimport os,sys\nnrpy_dir_path = os.path.join(\"..\",\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Step 0b: Load up cmdline_helper and create the directory\nimport cmdline_helper as cmd\noutdir = os.path.join(\"..\",\"src\")\ncmd.mkdir(outdir)\n```\n\n\n\n# Step 1: Introduction \\[Back to [top](#toc)\\]\n$$\\label{introduction}$$\n\nIn this tutorial module we will go through the implementation of the piecewise parabolic method (PPM), introduced by [Colella & Woodward (1984)](https://crd.lbl.gov/assets/pubs_presos/AMCS/ANAG/A141984.pdf) (which shall henceforth be our main reference), used by `IllinoisGRMHD`.\n\n\n\n## Step 1.a: The Piecewise Parabolic Method (PPM) \\[Back to [top](#toc)\\]\n$$\\label{ppm}$$\n\nThe piecewise parabolic method (PPM) is an algorithm used to construct the values of primitive variables, $U$, at cell interfaces. The interpolation procedure alone can lead to unstable evolutions. To remedy this, we introduce three different techniques:\n\n1. Steepening\n1. Flatenning\n1. Monotonizing\n\nThese algorithms are intended to also produce narrower profiles near the vicinity of a shock. These steps tend to reduce the third-order accuracy of the interpolation code, but only in cases where a third-order interpolation algorithm would produce *worse* results (e.g. at local extrema).\n\nThe algorithmic flow of the code is as follows:\n\n1. **Read the input**: determine which primitives are to be \"reconstructed\" (i.e. interpolated)\n2. **Slope-limited gradient**: this must be computed for each of the primitives that will be reconstructed. We have:\n\n$$\n\\boxed{\\delta U^{\\rm slope-lim} \\equiv\n\\left\\{\n\\begin{matrix}\n{\\rm sign}\\left(\\delta_{m} U_{i}\\right)\\min\\left(\\left|\\delta_{m} U_{i}\\right|,c\\left|\\delta U_{i}\\right|,c\\left|\\delta U_{i+1}\\right|\\right) & ,\\ {\\rm if}\\ dU_{i}dU_{i+1} > 0\\\\\n0 &,\\ {\\rm otherwise}\n\\end{matrix}\n\\right.}\\ ,\n$$\n\n where $\\delta U^{\\rm slope-lim}$ is referred to as the slope-limited gradient of $U$ and\n\n\\begin{align}\n\\delta U_{i} &\\equiv U_{i} - U_{i-1}\\ ,\\\\\n\\delta_{m} U_{i} &\\equiv \\frac{\\delta U_{i} + \\delta U_{i+1}}{2} = \\frac{U_{i+1} - U_{i-1}}{2}\\ .\n\\end{align}\n\n3. **Perform the interpolation**: We wish to determine $U_{r}$ and $U_{l}$, the values of $U$ at the cell interfaces. From the given set of known values $\\left\\{U_{i-2},U_{i-1},U_{i},U_{i+1},U_{i+2}\\right\\}$, one *interpolates* (with third-order accuracy) the values\n\n$$\n\\begin{matrix}\nU_{i+1/2} \\equiv U_{r,i} = U_{i+0} + \\frac{1}{2}\\left(U_{i+1} - U_{i+0}\\right) + \\frac{1}{6}\\left(\\delta U^{\\rm slope-lim}_{i+0} - \\delta U^{\\rm slope-lim}_{i+1}\\right)\\\\\nU_{i-1/2} \\equiv U_{l,i} = U_{i-1} + \\frac{1}{2}\\left(U_{i+0} - U_{i-1}\\right) + \\frac{1}{6}\\left(\\delta U^{\\rm slope-lim}_{i-1} - \\delta U^{\\rm slope-lim}_{i+0}\\right)\n\\end{matrix}\n$$\n\n4. **Compute $P_{\\rm cold}$ and $\\Gamma_{\\rm cold}$**: In order to decide whether or not to apply the steepening procedure, we must evaluate the contact discontinuity condition:\n\n$$\n\\boxed{\\Gamma_{\\rm cold} K_{0}\\frac{\\left|\\rho_{i+1}-\\rho_{i-1}\\right|}{\\min\\left(\\rho_{i+1},\\rho_{i-1}\\right)} \\geq \\frac{\\left|\\left(P_{\\rm cold}\\right)_{i+1}-\\left(P_{\\rm cold}\\right)_{i-1}\\right|}{\\min\\left[\\left(P_{\\rm cold}\\right)_{i+1},\\left(P_{\\rm cold}\\right)_{i-1}\\right]}}\\ ,\n$$\n\nwith $K_{0}$ a problem dependent constant.\n\n5. **Steepening**: *if necessary*, apply the steepening proceedure *only* to $U = \\rho_{b}^{\\color{red}\\ddagger}$. This involves performing the replacement\n\n$$\n\\boxed{\n\\begin{matrix}\n\\rho_{r}\\to \\rho_{r}(1-\\eta) + \\rho^{\\rm MC}_{r}\\eta\\\\\n\\rho_{l}\\to \\rho_{l}(1-\\eta) + \\rho^{\\rm MC}_{l}\\eta\n\\end{matrix}\n}\\ ,\n$$\n\nwhere\n\n\\begin{align}\n\\rho^{\\rm MC}_{r,i+1} &= \\rho_{i+1} - \\frac{1}{2}\\delta\\rho^{\\rm slope-lim}_{i+1}\\ ,\\\\\n\\rho^{\\rm MC}_{l,i+0} &= \\rho_{i-1} + \\frac{1}{2}\\delta\\rho^{\\rm slope-lim}_{i-1}\\ ,\\\\\n\\eta_{i} &= \\max\\left\\{0,\\min\\left[\\eta_{1}\\left(\\tilde\\eta_{i}-\\eta_{2}\\right),1\\right]\\right\\}\\ ,\n\\end{align}\n\nwith $\\eta_{1}$ and $\\eta_{2}$ constants and\n\n$$\n\\tilde\\eta_{i} = \n\\left\\{\n\\begin{matrix}\n0&, \\ {\\rm if}\\ \\delta\\rho_{i} = 0\\ ,\\\\\n-\\frac{1}{6}\\left(\\frac{\\delta^{2}\\rho_{i+1} - \\delta^{2}\\rho_{i-1}}{2\\delta\\rho_{i}}\\right)&, \\ {\\rm otherwise}\\ ,\n\\end{matrix}\n\\right.\n$$\n\nand finally\n\n\\begin{align}\n\\delta\\rho_{i+0} &= \\frac{\\rho_{i+1} - \\rho_{i-1}}{2}\\ ,\\\\\n\\delta^{2}\\rho_{i-1} &= \\rho_{i+0} - 2\\rho_{i-1} + \\rho_{i-2}\\ ,\\\\\n\\delta^{2}\\rho_{i+1} &= \\rho_{i+2} - 2\\rho_{i+1} + \\rho_{i+0}\\ .\n\\end{align}\n\n$^{\\color{red}\\ddagger}$: note that the common notation is $\\rho_{0}$, but we will use $\\rho_{b}$ to represent the baryonic matter density.\n\n6. **Flattening**: *if necessary*, apply the flattening procedure to *all* primitives which are to be reconstructed. In the flattening procedure we modify either $U_{r}$, $U_{l}$, or both of them, according to\n\n$$\n\\boxed{\n\\begin{matrix}\nU_{r,i+0} = U_{i+0}\\tilde{f} + U_{r,i+0}\\left(1-\\tilde{f}\\right)\\\\\nU_{l,i+0} = U_{i+0}\\tilde{f} + U_{l,i+0}\\left(1-\\tilde{f}\\right)\n\\end{matrix}\n}\\ ,\n$$\n\nwhere\n\n\\begin{align}\n\\tilde{f} &= \\min\\left[1,w\\max\\left(0,q_{1}\\right)\\right]\\ ,\\\\\nw &= \n\\left\\{\n\\begin{matrix}\n1\\ , &\\ {\\rm if}\\ q_{2} > \\epsilon_{2}\\ {\\rm and}\\ q_{2}\\left(v^{\\rm flux\\ dirn}_{i-1}-v^{\\rm flux\\ dirn}_{i+1}\\right)>0\\ \\left({\\rm inside\\ shock}\\right)\\ ,\\\\\n0\\ , &\\ {\\rm otherwise}\\ \\left({\\rm outside\\ shock}\\right)\\ ,\n\\end{matrix}\n\\right.\n\\end{align}\n\nand\n\n\\begin{align}\nq_{1} &= \\left(\\frac{\\delta P_{1}}{\\delta P_{2}}-\\omega_{1}\\right)\\omega_{2}\\ ,\\\\\nq_{2} &= \\frac{\\left|\\delta P_{1}\\right|}{\\min\\left(P_{i+1},P_{i-1}\\right)}\\ ,\n\\end{align}\n\nwith $\\omega_{1}$ and $\\omega_{2}$ constants and $\\delta P_{n} \\equiv P_{i+n} - P_{i-n}$.\n\n7. **Monotonizing**: *if necessary*, apply the monotonizing procedure to *all* primitives which are to be reconstructed. We check three different cases, modifying $U_{r}$ and $U_{l}$ as follows:\n\n$$\n\\boxed{\n\\begin{matrix}\n\\text{Case 1: if}\\ \\left(U_{r} - U\\right)\\left(U - U_{l}\\right)\\leq 0 \\ \\text{then:}\\ \n\\left\\{\n\\begin{matrix}\nU_{r} \\to U\\ ,\\\\\n\\ U_{l}\\to U\\ .\n\\end{matrix}\n\\right.\\\\\n\\text{Case 2: if}\\ \\delta U\\left(U - \\delta_{m}U\\right) > \\frac{\\left(\\delta U\\right)^{2}}{6} \\ \\text{then:}\\ \n\\left\\{\n\\begin{matrix}\nU_{r} \\to U_{r}\\ ,\\\\\n\\ U_{l}\\to 3U-2U_{r}\\ .\n\\end{matrix}\n\\right.\\\\\n\\text{Case 3: if}\\ \\delta U\\left(U - \\delta_{m}U\\right) < -\\frac{\\left(\\delta U\\right)^{2}}{6} \\ \\text{then:}\\ \n\\left\\{\n\\begin{matrix}\nU_{r} \\to 3U-2U_{l}\\ ,\\\\\n\\ U_{l}\\to U_{l}\\ .\n\\end{matrix}\n\\right.\n\\end{matrix}\n}\\ ,\n$$\n\nwhere\n\n\\begin{align}\n\\delta U &\\equiv U_{r} - U_{l}\\ ,\\\\\n\\delta_{m}U &\\equiv \\frac{U_{r} + U_{l}}{2}\\ .\n\\end{align}\n\n8. **Index shifting**: shift the indices of $U_{r}$ and $U_{l}$. We have, at this point\n\n\\begin{align}\nU_{r,i} = U_{i+1/2}\\ ,\\\\\nU_{l,i} = U_{i-1/2}\\ .\n\\end{align}\n\nWe then perform the following shift\n\n$$\n\\boxed{\n\\begin{matrix}\nU_{i-1/2+\\epsilon} = U_{l,i}^{\\rm old} = U_{r,i}^{\\rm new}\\ ,\\\\\nU_{i-1/2-\\epsilon} = U_{r,i-1}^{\\rm old} = U_{l,i}^{\\rm new}\\ .\\\\\n\\end{matrix}\n}\n$$\n\n\n\n## Step 1.b: The `loop_defines_reconstruction.h` header file \\[Back to [top](#toc)\\]\n$$\\label{loop_defines_reconstruction}$$\n\nThis header file defines useful quantities to be used throughout the `reconstruct_set_of_prims_PPM.C` code. They are:\n\n1. LOOP_DEFINE $\\rightarrow$ sets up a loop over the $x$, $y$, and $z$ directions, including the ghostzones\n1. SET_INDEX_ARRAYS $\\rightarrow$ for a given direction, $x^{j}$, and coordinate range, $i\\in\\left[i_\\min,i_\\max\\right]$, finds the appropriate array indices\n1. SET_INDEX_ARRAYS_3DBLOCK $\\rightarrow$ finds the appropriate array indices in all directions of a given range\n\n\n```python\n%%writefile $outdir/loop_defines_reconstruction.h\n#ifndef LOOP_DEFINES_RECONSTRUCTION_H_\n#define LOOP_DEFINES_RECONSTRUCTION_H_\n\n#define LOOP_DEFINE(gz_shift_lo,gz_shift_hi, ext,flux_dirn, ijkgz_lo_hi,gz_lo,gz_hi) \\\n for(int rr=1;rr<=3;rr++) { \\\n ijkgz_lo_hi[rr][0]= gz_lo[rr]; \\\n ijkgz_lo_hi[rr][1]=ext[rr-1]-gz_hi[rr]; \\\n } \\\n ijkgz_lo_hi[flux_dirn][0] += gz_shift_lo; \\\n ijkgz_lo_hi[flux_dirn][1] -= gz_shift_hi; \\\n /* The following line is valid C99 */ \\\n _Pragma(\"omp parallel for private(U,dU,slope_lim_dU,Ur,Ul)\") \\\n for(int k=ijkgz_lo_hi[3][0];kmax_shift) CCTK_VError(VERR_DEF_PARAMS,\"FIX MAXNUMINDICES!\"); */ \\\n int index_arr[4][MAXNUMINDICES]; \\\n for(int idx=IMIN;idx<=IMAX;idx++) { \\\n index_arr[flux_dirn][idx+max_shift]= \\\n CCTK_GFINDEX3D(cctkGH, \\\n i+idx*kronecker_delta[flux_dirn][0], \\\n j+idx*kronecker_delta[flux_dirn][1], \\\n k+idx*kronecker_delta[flux_dirn][2]); \\\n }\n\n#define SET_INDEX_ARRAYS_3DBLOCK(IJKLOHI) \\\n int max_shift=(MAXNUMINDICES/2); \\\n int index_arr_3DB[MAXNUMINDICES][MAXNUMINDICES][MAXNUMINDICES]; \\\n for(int idx_k=IJKLOHI[4];idx_k<=IJKLOHI[5];idx_k++) for(int idx_j=IJKLOHI[2];idx_j<=IJKLOHI[3];idx_j++) for(int idx_i=IJKLOHI[0];idx_i<=IJKLOHI[1];idx_i++) { \\\n index_arr_3DB[idx_k+max_shift][idx_j+max_shift][idx_i+max_shift]=CCTK_GFINDEX3D(cctkGH,i+idx_i,j+idx_j,k+idx_k); \\\n }\n\n#endif /* LOOP_DEFINES_RECONSTRUCTION_H_ */\n\n\n```\n\n Overwriting ../src/loop_defines_reconstruction.h\n\n\n\n\n## Step 1.c: The preamble to the `reconstruct_set_of_prims_PPM.C` code file \\[Back to [top](#toc)\\]\n$$\\label{preamble_reconstruct_set_of_prims_ppm}$$\n\nWe then initialize the `reconstruct_set_of_prims_PPM.C` code file with a basic preamble, some simple definitions, and function headers. Notice that these functions are defined in the other Steps of this tutorial notebook. See the [table of contents](#toc) above for more information.\n\n\n```python\n%%writefile $outdir/reconstruct_set_of_prims_PPM.C\n/*****************************************\n * PPM Reconstruction Interface.\n * Zachariah B. Etienne (2013)\n *\n * This version of PPM implements the standard \n * Colella & Woodward PPM, though modified as in GRHydro\n * to have 3 ghostzones instead of 4. \n *****************************************/\n\n#define MINUS2 0\n#define MINUS1 1\n#define PLUS0 2\n#define PLUS1 3\n#define PLUS2 4\n#define MAXNUMINDICES 5\n// ^^^^^^^^^^^^^ Be _sure_ to define MAXNUMINDICES appropriately!\n\n// You'll find the #define's for LOOP_DEFINE and SET_INDEX_ARRAYS inside:\n#include \"loop_defines_reconstruction.h\"\n\nstatic inline CCTK_REAL ftilde_compute(const int flux_dirn,const CCTK_REAL rho_b_atm,CCTK_REAL U[MAXNUMVARS][MAXNUMINDICES]);\nstatic inline CCTK_REAL slope_limit(CCTK_REAL dU,CCTK_REAL dUp1);\nstatic inline void steepen_rho(CCTK_REAL U[MAXNUMVARS][MAXNUMINDICES],CCTK_REAL slope_lim_dU[MAXNUMVARS][MAXNUMINDICES],\n CCTK_REAL Gamma_th,CCTK_REAL P_cold,CCTK_REAL Gamma_cold,\n CCTK_REAL *rho_br_ppm,CCTK_REAL *rho_bl_ppm);\nstatic inline void compute_P_cold__Gamma_cold(CCTK_REAL rho_b,eos_struct &eos, CCTK_REAL &P_cold,CCTK_REAL &Gamma_cold);\nstatic inline void monotonize(CCTK_REAL U,CCTK_REAL &Ur,CCTK_REAL &Ul);\n```\n\n Overwriting ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 2: The `reconstruct_set_of_prims_PPM()` function \\[Back to [top](#toc)\\]\n$$\\label{reconstruct_set_of_prims_ppm}$$\n\nThe `reconstruct_set_of_prims_PPM()` function receives as input the direction in which to perform the reconstruction ($\\rm flux\\_dirn$), the number of primitives which are to be reconstructed ($\\rm num\\_prims\\_to\\_reconstruct$), which primitives are to be reconstructed ($\\rm which\\_prims\\_to\\_reconstruct$), the equation of state ($\\rm eos$), and the array which stores the primitives ($\\rm in\\_prims$). The reconstructed primitive values are then stored in the output arrays $\\rm out\\_prims\\_r$ and $\\rm out\\_prims\\_l$. **Note**: you can find more information on the ETK specific parameters (such as ${\\rm cctkGH}$ and $\\rm cctk\\_lsh$) by looking at the [official Einstein Toolkit documentation](http://cactuscode.org/documentation/referencemanual/ReferenceManualch2.html).\n\nNotice that we will start a loop that runs from 0 to $\\rm num\\_prims\\_to\\_reconstruct$, meaning that the discussion here will apply to *each* of the primitives that we wish to reconstruct.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\nstatic void reconstruct_set_of_prims_PPM(const cGH *cctkGH,const int *cctk_lsh,const int flux_dirn,const int num_prims_to_reconstruct,const int *which_prims_to_reconstruct,eos_struct &eos,\n gf_and_gz_struct *IN_PRIMS,gf_and_gz_struct *OUT_PRIMS_R,gf_and_gz_struct *OUT_PRIMS_L,CCTK_REAL *ftilde_gf, CCTK_REAL *temporary) {\n\n DECLARE_CCTK_PARAMETERS;\n\n CCTK_REAL U[MAXNUMVARS][MAXNUMINDICES],dU[MAXNUMVARS][MAXNUMINDICES],slope_lim_dU[MAXNUMVARS][MAXNUMINDICES],\n Ur[MAXNUMVARS][MAXNUMINDICES],Ul[MAXNUMVARS][MAXNUMINDICES];\n int ijkgz_lo_hi[4][2];\n\n for(int ww=0;ww\n\n## Step 2.a: Reading the input gridfunctions \\[Back to [top](#toc)\\]\n$$\\label{reading_the_input_gfs}$$\n\nWe start by reading in the input primitive gridfunction and storing them to a variable $U$. Notice that for a given direction and a given point $i$, we will know: $\\left\\{U_{i-2},U_{i-1},U_{i},U_{i+1},U_{i+2}\\right\\}$.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n \n // *** LOOP 1: Interpolate to Ur and Ul, which are face values ***\n // You will find that Ur depends on U at MINUS1,PLUS0, PLUS1,PLUS2, and\n // Ul depends on U at MINUS2,MINUS1,PLUS0,PLUS1.\n // However, we define the below loop from MINUS2 to PLUS2. Why not split\n // this up and get additional points? The reason is that later on,\n // Ur and Ul depend on ftilde, which is defined from MINUS2 to PLUS2,\n // so we would lose those points anyway.\n LOOP_DEFINE(2,2, cctk_lsh,flux_dirn, ijkgz_lo_hi,IN_PRIMS[whichvar].gz_lo,IN_PRIMS[whichvar].gz_hi) {\n SET_INDEX_ARRAYS(-2,2,flux_dirn);\n /* *** LOOP 1a: READ INPUT *** */\n // Read in a primitive at all gridpoints between m = MINUS2 & PLUS2, where m's direction is given by flux_dirn. Store to U. \n for(int ii=MINUS2;ii<=PLUS2;ii++) U[whichvar][ii] = IN_PRIMS[whichvar].gf[index_arr[flux_dirn][ii]];\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n## Step 2.b: Evaluation of $\\delta U_{i}$ \\[Back to [top](#toc)\\]\n$$\\label{computation_of_du}$$\n\nWe will need $\\delta U_{i} \\equiv U_{i} - U_{i-1}$ in order to compute $U_{r}$ and $U_{l}$. We will then compute (notice the notation change $i\\to i+0$ so that it is easier to understand the C code that follows):\n\n\\begin{align}\n\\delta U_{i-1} &= U_{i-1} - U_{i-2}\\ ,\\\\\n\\delta U_{i+0} &= U_{i+0} - U_{i-1}\\ ,\\\\\n\\delta U_{i+1} &= U_{i+1} - U_{i+0} \\ ,\\\\\n\\delta U_{i+2} &= U_{i+2} - U_{i+1}\\ .\n\\end{align}\n\nAfter evaluating the differences $\\delta U$, we compute the slope-limited $\\delta U$, $\\delta U^{\\rm slope-lim}$, using the [`slope_limit()` function](#slope_limit).\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n \n /* *** LOOP 1b: DO COMPUTATION *** */\n /* First, compute simple dU = U(i) - U(i-1), where direction of i \n * is given by flux_dirn, and U is a primitive variable: \n * {rho_b,P,vx,vy,vz,Bx,By,Bz}. */\n // Note that for Ur and Ul at i, we must compute dU(i-1),dU(i),dU(i+1), \n // and dU(i+2)\n dU[whichvar][MINUS1] = U[whichvar][MINUS1]- U[whichvar][MINUS2]; \n dU[whichvar][PLUS0] = U[whichvar][PLUS0] - U[whichvar][MINUS1]; \n dU[whichvar][PLUS1] = U[whichvar][PLUS1] - U[whichvar][PLUS0]; \n dU[whichvar][PLUS2] = U[whichvar][PLUS2] - U[whichvar][PLUS1];\n \n //static int iii=14, jjj=14, kkk=13;\n \n //if( (i==iii) && (j==jjj) && (k==kkk) ) printf(\"UUUU0 %d | %e %e %e %e %e\\n\",whichvar,U[whichvar][MINUS2],U[whichvar][MINUS1],U[whichvar][PLUS0],U[whichvar][PLUS1],U[whichvar][PLUS2]);\n\n // Then, compute slope-limited dU, using MC slope limiter:\n slope_lim_dU[whichvar][MINUS1]=slope_limit(dU[whichvar][MINUS1],dU[whichvar][PLUS0]);\n slope_lim_dU[whichvar][PLUS0] =slope_limit(dU[whichvar][PLUS0], dU[whichvar][PLUS1]);\n slope_lim_dU[whichvar][PLUS1] =slope_limit(dU[whichvar][PLUS1], dU[whichvar][PLUS2]);\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n## Step 2.c: Computing $U_{r}$ and $U_{l}$ \\[Back to [top](#toc)\\]\n$$\\label{computation_of_ur_and_ul}$$\n\nWe now compute $U_{r}$ and $U_{l}$. Keep in mind that $U_{r,i} = U_{i+1/2}$, while $U_{l,i} = U_{i-1/2}$. The implemented equation follows eq. A1 in [Duez *et al.* (2005)](http://arxiv.org/pdf/astro-ph/0503420.pdf), but with the standardd PPM coefficient of $\\frac{1}{6}$ (i.e. eq. A1 with $\\frac{1}{8}\\to\\frac{1}{6}$). Keep in mind that we simplify the equation slightly before implementing it:\n\n\\begin{align}\nU_{r,i+0} &= U_{i+0} + \\frac{1}{2}\\left(U_{i+1} - U_{i+0}\\right) + \\frac{1}{6}\\left(\\delta U^{\\rm slope-lim}_{i+0} - \\delta U^{\\rm slope-lim}_{i+1}\\right) \\Rightarrow \\boxed{U_{r,i+0} = \\frac{1}{2}\\left(U_{i+1} + U_{i+0}\\right) + \\frac{1}{6}\\left(\\delta U^{\\rm slope-lim}_{i+0} - \\delta U^{\\rm slope-lim}_{i+1}\\right)}\\ ,\\\\\nU_{l,i+0} &= U_{i-1} + \\frac{1}{2}\\left(U_{i+0} - U_{i-1}\\right) + \\frac{1}{6}\\left(\\delta U^{\\rm slope-lim}_{i-1} - \\delta U^{\\rm slope-lim}_{i+0}\\right) \\Rightarrow \\boxed{U_{l,i+0} = \\frac{1}{2}\\left(U_{i+0} + U_{i-1}\\right) + \\frac{1}{6}\\left(\\delta U^{\\rm slope-lim}_{i-1} - \\delta U^{\\rm slope-lim}_{i+0}\\right)}\\ .\n\\end{align}\n\nAfter this step, the values of $U_{r,l,i+0}$ are stored as outputs.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n // Finally, compute face values Ur and Ul based on the PPM prescription \n // (Eq. A1 in http://arxiv.org/pdf/astro-ph/0503420.pdf, but using standard 1/6=(1.0/6.0) coefficient)\n // Ur[PLUS0] represents U(i+1/2)\n // We applied a simplification to the following line: Ur=U+0.5*(U(i+1)-U) + ... = 0.5*(U(i+1)+U) + ...\n Ur[whichvar][PLUS0] = 0.5*(U[whichvar][PLUS1] + U[whichvar][PLUS0] ) + (1.0/6.0)*(slope_lim_dU[whichvar][PLUS0] - slope_lim_dU[whichvar][PLUS1]);\n //if( (i==iii) && (j==jjj) && (k==kkk) ) printf(\"UURR0 %d | %e\\n\",whichvar,Ur[whichvar][PLUS0]);\n // Ul[PLUS0] represents U(i-1/2)\n // We applied a simplification to the following line: Ul=U(i-1)+0.5*(U-U(i-1)) + ... = 0.5*(U+U(i-1)) + ...\n Ul[whichvar][PLUS0] = 0.5*(U[whichvar][PLUS0] + U[whichvar][MINUS1]) + (1.0/6.0)*(slope_lim_dU[whichvar][MINUS1] - slope_lim_dU[whichvar][PLUS0]);\n //if( (i==iii) && (j==jjj) && (k==kkk) ) printf(\"UULL0 %d | %e\\n\",whichvar,Ul[whichvar][PLUS0]);\n\n /* *** LOOP 1c: WRITE OUTPUT *** */\n // Store right face values to {rho_br,Pr,vxr,vyr,vzr,Bxr,Byr,Bzr},\n // and left face values to {rho_bl,Pl,vxl,vyl,vzl,Bxl,Byl,Bzl}\n OUT_PRIMS_R[whichvar].gf[index_arr[flux_dirn][PLUS0]] = Ur[whichvar][PLUS0];\n OUT_PRIMS_L[whichvar].gf[index_arr[flux_dirn][PLUS0]] = Ul[whichvar][PLUS0]; \n }\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n## Step 2.d: Steepening $\\rho_{b}$ \\[Back to [top](#toc)\\]\n$$\\label{steepening_rhob}$$\n\nFollowing the procedure described in [Step 4](#steepen_rho), we will now steepen $\\rho_{b}$ using the [`steepen_rho()` function](#steepen_rho). Keep in mind that although we will loop over all primitives which are set for reconstruction, the steepening procedure is applied to $\\rho_{b}$ *only*.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n // *** LOOP 2: STEEPEN RHOB ***\n // Note that this loop applies ONLY to RHOB.\n if(whichvar==RHOB) {\n LOOP_DEFINE(2,2, cctk_lsh,flux_dirn, ijkgz_lo_hi,IN_PRIMS[whichvar].gz_lo,IN_PRIMS[whichvar].gz_hi) {\n\tSET_INDEX_ARRAYS(-2,2,flux_dirn);\n\t// Set rho and P separately, since within this loop,\n\t// 1) steepen_rho() depends on RHOB(MINUS2,MINUS1,PLUS0,PLUS1,PLUS2)\n\n\t// Read in all primitives between MINUS2 & PLUS2. Store to U.\n\tfor(int ii=MINUS2;ii<=PLUS2;ii++) U[RHOB][ii] = IN_PRIMS[RHOB ].gf[index_arr[flux_dirn][ii]];\n\tfor(int ii=MINUS1;ii<=PLUS1;ii++) U[PRESSURE][ii] = IN_PRIMS[PRESSURE].gf[index_arr[flux_dirn][ii]];\n\tUr[RHOB][PLUS0] = OUT_PRIMS_R[RHOB].gf[index_arr[flux_dirn][PLUS0]];\n\tUl[RHOB][PLUS0] = OUT_PRIMS_L[RHOB].gf[index_arr[flux_dirn][PLUS0]];\n\n\tdU[whichvar][MINUS1] = U[whichvar][MINUS1]- U[whichvar][MINUS2]; \n\tdU[whichvar][PLUS0] = U[whichvar][PLUS0] - U[whichvar][MINUS1]; \n\tdU[whichvar][PLUS1] = U[whichvar][PLUS1] - U[whichvar][PLUS0]; \n\tdU[whichvar][PLUS2] = U[whichvar][PLUS2] - U[whichvar][PLUS1]; \n\n\tslope_lim_dU[whichvar][MINUS1]=slope_limit(dU[whichvar][MINUS1],dU[whichvar][PLUS0]);\n\t//slope_lim_dU[whichvar][PLUS0] =slope_limit(dU[whichvar][PLUS0], dU[whichvar][PLUS1]);\n\tslope_lim_dU[whichvar][PLUS1] =slope_limit(dU[whichvar][PLUS1], dU[whichvar][PLUS2]);\n\n\t// Steepen rho\n\t// DEPENDENCIES: RHOB face values, RHOB(MINUS2,MINUS1,PLUS0,PLUS1,PLUS2), P(MINUS1,PLUS0,PLUS1), and slope_lim_dU[RHOB](MINUS1,PLUS1)\n\tCCTK_REAL P_cold,Gamma_cold;\n\tcompute_P_cold__Gamma_cold(U[RHOB][PLUS0],eos, P_cold,Gamma_cold);\n\tsteepen_rho(U,slope_lim_dU, Gamma_th,P_cold,Gamma_cold, Ur[RHOB],Ul[RHOB]);\n\n\t// Output rho\n\tOUT_PRIMS_R[RHOB].gf[index_arr[flux_dirn][PLUS0]] = Ur[RHOB][PLUS0];\n\tOUT_PRIMS_L[RHOB].gf[index_arr[flux_dirn][PLUS0]] = Ul[RHOB][PLUS0];\n }\n }\n }\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n## Step 2.e: Flattening and monotonizing \\[Back to [top](#toc)\\]\n$$\\label{flattening_and_monotonizing}$$\n\nThe flattening procedure modifies $U_{r}$ and $U_{l}$ via\n\n$$\n\\boxed{\n\\begin{matrix}\nU_{r,i+0} = U_{i+0}\\tilde{f} + U_{r,i+0}\\left(1-\\tilde{f}\\right)\\\\\nU_{l,i+0} = U_{i+0}\\tilde{f} + U_{l,i+0}\\left(1-\\tilde{f}\\right)\n\\end{matrix}\n}\\ ,\n$$\n\nwhere $\\tilde{f}$ is computed by the `ftilde_compute()` function, described in [Step 8](#ftilde_compute).\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n /* ORIGINAL PPM REQUIRES AT LEAST 4 GHOSTZONES, which can add\n * significantly to the size of AMR ref. boundaries.\n * To reduce to 3 ghostzones, we comment the following lines out:\n * if ((P[indexp1] - P[indexm1]) <= 0.0) {\n * f = MAX(ftilde,ftilde_p1);\n * } else {\n * f = MAX(ftilde,ftilde_m1);\n * }\n */\n\n // *** LOOP 3: FLATTEN BASED ON FTILDE AND MONOTONIZE ***\n for(int ww=0;ww\n\n## Step 2.f: Shifting $U_{r}$ and $U_{l}$ \\[Back to [top](#toc)\\]\n$$\\label{shifting_ur_and_ul}$$\n\nAt this point, we have\n\n\\begin{align}\nU_{r,i} &= U_{i+1/2}\\ ,\\\\\nU_{l,i} &= U_{i-1/2}\\ .\n\\end{align}\n\nTo keep things consistent, we shift indices to get\n\n$$\n\\boxed{\n\\begin{matrix}\nU_{i-1/2+\\epsilon} = U_{l,i}^{\\rm old} = U_{r,i}^{\\rm new}\\ ,\\\\\nU_{i-1/2-\\epsilon} = U_{r,i-1}^{\\rm old} = U_{l,i}^{\\rm new}\\ ,\\\\\n\\end{matrix}\n}\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n // Ur depends on ftilde, which depends on points of U between MINUS2 and PLUS2\n OUT_PRIMS_R[whichvar].gz_lo[flux_dirn]+=2; \n OUT_PRIMS_R[whichvar].gz_hi[flux_dirn]+=2;\n // Ul depends on ftilde, which depends on points of U between MINUS2 and PLUS2\n OUT_PRIMS_L[whichvar].gz_lo[flux_dirn]+=2;\n OUT_PRIMS_L[whichvar].gz_hi[flux_dirn]+=2;\n }\n\n // *** LOOP 4: SHIFT Ur AND Ul ***\n /* Currently face values are set so that\n * a) Ur(i) represents U(i+1/2), and\n * b) Ul(i) represents U(i-1/2)\n * Here, we shift so that the indices are consistent:\n * a) U(i-1/2+epsilon) = oldUl(i) = newUr(i)\n * b) U(i-1/2-epsilon) = oldUr(i-1) = newUl(i)\n * Note that this step is not strictly necessary if you keep\n * track of indices when computing the flux. */\n for(int ww=0;ww\n\n# Step 3: The `slope_limit()` function \\[Back to [top](#toc)\\]\n$$\\label{slope_limit}$$\n\nWe will now show the definition of $\\delta U^{\\rm slope-lim}$. The reason why we introduce this slope-limited procedure is twofold. First, it leads to steeper representations of discontinuities, and second it guarantees that $U_{i+1/2}$ lies inside the range $\\left[U_{i},U_{i+1}\\right]$.\n\nWe start by defining\n\n\\begin{align}\n\\delta U_{i} &\\equiv U_{i} - U_{i-1}\\ ,\\\\\n\\delta_{m} U_{i} &\\equiv \\frac{\\delta U_{i} + \\delta U_{i+1}}{2} = \\frac{U_{i+1} - U_{i-1}}{2}\\ .\n\\end{align}\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n// Set SLOPE_LIMITER_COEFF = 2.0 for MC, 1 for minmod\n#define SLOPE_LIMITER_COEFF 2.0\n\n//Eq. 60 in JOURNAL OF COMPUTATIONAL PHYSICS 123, 1-14 (1996) \n// [note the factor of 2 missing in the |a_{j+1} - a_{j}| term]. \n// Recall that dU = U_{i} - U_{i-1}.\nstatic inline CCTK_REAL slope_limit(CCTK_REAL dU,CCTK_REAL dUp1) {\n if(dU*dUp1 > 0.0) {\n //delta_m_U=0.5 * [ (u_(i+1)-u_i) + (u_i-u_(i-1)) ] = (u_(i+1) - u_(i-1))/2 <-- first derivative, second-order; this should happen most of the time (smooth flows)\n CCTK_REAL delta_m_U = 0.5*(dU + dUp1);\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nNext we implement the slope-limited $\\delta U$ as\n\n$$\n\\boxed{\\delta U^{\\rm slope-lim} \\equiv\n\\left\\{\n\\begin{matrix}\n{\\rm sign}\\left(\\delta_{m} U_{i}\\right)\\min\\left(\\left|\\delta_{m} U_{i}\\right|,c\\left|\\delta U_{i}\\right|,c\\left|\\delta U_{i+1}\\right|\\right) & ,\\ {\\rm if}\\ dU_{i}dU_{i+1} > 0\\\\\n0 &,\\ {\\rm otherwise}\n\\end{matrix}\n\\right.}\\ .\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n // EXPLANATION OF BELOW LINE OF CODE.\n // In short, sign_delta_a_j = sign(delta_m_U) = (0.0 < delta_m_U) - (delta_m_U < 0.0).\n // If delta_m_U>0, then (0.0 < delta_m_U)==1, and (delta_m_U < 0.0)==0, so sign_delta_a_j=+1\n // If delta_m_U<0, then (0.0 < delta_m_U)==0, and (delta_m_U < 0.0)==1, so sign_delta_a_j=-1\n // If delta_m_U==0,then (0.0 < delta_m_U)==0, and (delta_m_U < 0.0)==0, so sign_delta_a_j=0\n int sign_delta_m_U = (0.0 < delta_m_U) - (delta_m_U < 0.0);\n //Decide whether to use 2nd order derivative or first-order derivative, limiting slope.\n return sign_delta_m_U*MIN(fabs(delta_m_U),MIN(SLOPE_LIMITER_COEFF*fabs(dUp1),SLOPE_LIMITER_COEFF*fabs(dU)));\n }\n return 0.0;\n}\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 4: The `steepen_rho()` function \\[Back to [top](#toc)\\]\n$$\\label{steepen_rho}$$\n\nThe steepening procedure withing the PPM algorithm is applied only to $\\rho_{b}$. The idea here is to produce narrower profiles near the vicinity of a contact discontinuity.\n\n**A NOTE ON NOTATION**: in the discussion below we will refer to $\\rho$ as $\\rho$ to keep the notation a bit lighter. No confusion should arise from this since there is no other quantity $\\rho$ involved.\n\nWe start the algorithm by computing\n\n\\begin{align}\n\\delta\\rho_{i+0} &= \\frac{\\rho_{i+1} - \\rho_{i-1}}{2}\\ ,\\\\\n\\delta^{2}\\rho_{i-1} &= \\rho_{i+0} - 2\\rho_{i-1} + \\rho_{i-2}\\ ,\\\\\n\\delta^{2}\\rho_{i+1} &= \\rho_{i+2} - 2\\rho_{i+1} + \\rho_{i+0}\\ .\n\\end{align}\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n// standard Colella-Woodward parameters:\n// K0 = 0.1d0, eta1 = 20.0, eta2 = 0.05, epsilon = 0.01d0\n#define K0 0.1\n#define ETA1 20.0\n#define ETA2 0.05\n#define EPSILON 0.01\nstatic inline void steepen_rho(CCTK_REAL U[MAXNUMVARS][MAXNUMINDICES],CCTK_REAL slope_lim_dU[MAXNUMVARS][MAXNUMINDICES],CCTK_REAL Gamma_th,CCTK_REAL P_cold,CCTK_REAL Gamma_cold,\n CCTK_REAL *rho_br_ppm,CCTK_REAL *rho_bl_ppm) {\n\n // Next compute centered differences d RHOB and d^2 RHOB\n CCTK_REAL d1rho_b = 0.5*(U[RHOB][PLUS1] - U[RHOB][MINUS1]);\n CCTK_REAL d2rho_b_m1 = U[RHOB][PLUS0] - 2.0*U[RHOB][MINUS1] + U[RHOB][MINUS2];\n CCTK_REAL d2rho_b_p1 = U[RHOB][PLUS2] - 2.0*U[RHOB][PLUS1] + U[RHOB][PLUS0];\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nThen we evaluate\n\n$$\n\\Gamma = \\left.\\left(\\frac{\\partial P}{\\partial\\rho}\\right)\\middle/\\left(\\frac{P}{\\rho}\\right)\\right. = \\Gamma_{\\rm th} + \\left(\\Gamma_{\\rm cold} - \\Gamma_{\\rm th}\\right)\\frac{P_{\\rm cold}}{P}\\ .\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n // Compute effective Gamma = (partial P / partial rho0)_s /(P/rho0)\n CCTK_REAL Gamma = Gamma_th + (Gamma_cold-Gamma_th)*P_cold/U[PRESSURE][PLUS0];\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nNext the contact discontinuity condition, eq. (3.2) of [Colella & Woodward (1984)](https://crd.lbl.gov/assets/pubs_presos/AMCS/ANAG/A141984.pdf), is checked:\n\n$$\n\\Gamma K_{0}\\frac{\\left|\\rho_{i+1}-\\rho_{i-1}\\right|}{\\min\\left(\\rho_{i+1},\\rho_{i-1}\\right)} \\geq \\frac{\\left|P_{i+1}-P_{i-1}\\right|}{\\min\\left(P_{i+1},P_{i-1}\\right)}\\ ,\n$$\n\nwhere $K_{0}$ is a problem dependent constant. Keep in mind that we implement the quantity\n\n$$\n\\boxed{{\\rm contact\\_discontinuity\\_check} \\equiv \\Gamma K_{0}\\left|\\rho_{i+1}-\\rho_{i-1}\\right|\\min\\left(P_{i+1},P_{i-1}\\right) - \\left|P_{i+1}-P_{i-1}\\right|\\min\\left(\\rho_{i+1},\\rho_{i-1}\\right)}\\ ,\n$$\n\nand verify whether ${\\rm contact\\_discontinuity\\_check} \\geq 0$ to verify the discontinuity condition. We also define the quantities\n\n$$\n\\boxed{{\\rm second\\_deriv\\_check} \\equiv - \\delta^{2}\\rho_{i-1}\\delta^{2}\\rho_{i+1}}\\ ,\n$$\n\nand\n\n$$\n\\boxed{{\\rm relative\\_change\\_check} \\equiv 2\\left|\\delta\\rho\\right| - \\epsilon\\min\\left(\\rho_{i+1},\\rho_{i-1}\\right)}\\ ,\n$$\n\nwhere again $\\epsilon$ is a constant. The contact discontinuity condition is then satisfied when all three quantities inside boxes above are non-negative. When that is the case, we evaluate\n\n$$\n\\boxed{\\eta_{i} = \\max\\left\\{0,\\min\\left[\\eta_{1}\\left(\\tilde\\eta_{i}-\\eta_{2}\\right),1\\right]\\right\\}}\\ ,\n$$\n\nwhere $\\eta_{1}$ and $\\eta_{2}$ are constants and\n\n$$\n\\boxed{\\tilde\\eta_{i} = \n\\left\\{\n\\begin{matrix}\n0&, \\ {\\rm if}\\ \\delta\\rho_{i} = 0\\ ,\\\\\n-\\frac{1}{6}\\left(\\frac{\\delta^{2}\\rho_{i+1} - \\delta^{2}\\rho_{i-1}}{2\\delta\\rho_{i}}\\right)&, \\ {\\rm otherwise}\\ .\n\\end{matrix}\n\\right.}\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n CCTK_REAL contact_discontinuity_check = Gamma*K0*fabs(U[RHOB][PLUS1]-U[RHOB][MINUS1])* \n MIN(U[PRESSURE][PLUS1],U[PRESSURE][MINUS1]) \n -fabs(U[PRESSURE][PLUS1]-U[PRESSURE][MINUS1])*MIN(U[RHOB][PLUS1],U[RHOB][MINUS1]);\n CCTK_REAL second_deriv_check = -d2rho_b_p1*d2rho_b_m1;\n CCTK_REAL relative_change_check = fabs(2.0*d1rho_b) - EPSILON*MIN(U[RHOB][PLUS1],U[RHOB][MINUS1]);\n\n if(contact_discontinuity_check >= 0.0 && second_deriv_check >= 0.0 \n && relative_change_check >= 0.0) {\n\n CCTK_REAL eta_tilde=0.0;\n if (fabs(d1rho_b) > 0.0) {\n eta_tilde = -(1.0/6.0)*(d2rho_b_p1-d2rho_b_m1)/(2.0*d1rho_b);\n }\n CCTK_REAL eta = MAX(0.0,MIN(ETA1*(eta_tilde - ETA2),1.0));\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nWe then apply the monotonized central (MC) scheme of [van Leer](https://www.sciencedirect.com/science/article/pii/002199917790095X) (see also [Step 3](#slope_limit) for a discussion on the quantities $\\delta\\rho^{\\rm slope-lim}_{i}$ below),\n\n\\begin{align}\n\\rho^{\\rm MC}_{r,i+1} &= \\rho_{i+1} - \\frac{1}{2}\\delta\\rho^{\\rm slope-lim}_{i+1}\\ ,\\\\\n\\rho^{\\rm MC}_{l,i+0} &= \\rho_{i-1} + \\frac{1}{2}\\delta\\rho^{\\rm slope-lim}_{i-1}\\ ,\n\\end{align}\n\nso that, finally, the steepening algorithm sets\n\n$$\n\\begin{matrix}\n\\rho_{r}\\to \\rho_{r}(1-\\eta) + \\rho^{\\rm MC}_{r}\\eta\\ ,\\\\\n\\rho_{l}\\to \\rho_{l}(1-\\eta) + \\rho^{\\rm MC}_{l}\\eta\\ ,\n\\end{matrix}\n$$\n\nor, as implemented below:\n\n$$\n\\boxed{\\begin{matrix}\n\\rho_{r,i+0}\\rightarrow \\rho_{r,i+0}\\left(1-\\eta_{i+0}\\right) + \\rho^{\\rm MC}_{r,i+1}\\eta_{i+0}\\ ,\\\\\n\\rho_{l,i+0}\\rightarrow \\rho_{r,i+0}\\left(1-\\eta_{i+0}\\right) + \\rho^{\\rm MC}_{l,i+0}\\eta_{i+0}\\ .\n\\end{matrix}}\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n // Next compute Urp1 and Ul for RHOB, using the MC prescription:\n // Ur_p1 = U_p1 - 0.5*slope_lim_dU_p1\n CCTK_REAL rho_br_mc_p1 = U[RHOB][PLUS1] - 0.5*slope_lim_dU[RHOB][PLUS1];\n // Ul = U_m1 + 0.5*slope_lim_dU_m1\n // Based on this line of code, Ur[index] = a_j - \\delta_m a_j / 2. (cf. Eq. 65 in Marti & Muller's \"PPM Method for 1D Relativistic Hydro.\" paper)\n // So: Ur[indexp1] = a_{j+1} - \\delta_m a_{j+1} / 2. This is why we have rho_br_mc[indexp1]\n CCTK_REAL rho_bl_mc = U[RHOB][MINUS1] + 0.5*slope_lim_dU[RHOB][MINUS1];\n\n rho_bl_ppm[PLUS0] = rho_bl_ppm[PLUS0]*(1.0-eta) + rho_bl_mc*eta; \n rho_br_ppm[PLUS0] = rho_br_ppm[PLUS0]*(1.0-eta) + rho_br_mc_p1*eta;\n\n }\n}\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 5: The `monotonize()` function \\[Back to [top](#toc)\\]\n$$\\label{monotonize}$$\n\nThe value $U_{i+1/2}$ will be assigned to $U_{l,i}$ and $U_{r,i-1}$ for most values of $i$, but in some cases this would lead to incorrect interpolation results. Near discontinuities, the value of either $U_{l}$, $U_{r}$, or both needs to be adjusted.\n\nConsider, then, the following quantities:\n\n\\begin{align}\n\\delta U &\\equiv U_{r} - U_{l}\\ ,\\\\\n\\delta_{m}U &\\equiv \\frac{U_{r} + U_{l}}{2}\\ .\n\\end{align}\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\nstatic inline void monotonize(CCTK_REAL U,CCTK_REAL &Ur,CCTK_REAL &Ul) {\n CCTK_REAL dU = Ur - Ul;\n CCTK_REAL mU = 0.5*(Ur+Ul);\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nThen, following eq. (1.10) of [Colella & Woodward (1984)](https://crd.lbl.gov/assets/pubs_presos/AMCS/ANAG/A141984.pdf), we will check the following three cases:\n\n$$\n\\boxed{\\text{Case 1: if}\\ \\left(U_{r} - U\\right)\\left(U - U_{l}\\right)\\leq 0 \\ \\text{then:}\\ \n\\left\\{\n\\begin{matrix}\nU_{r} \\to U\\ ,\\\\\n\\ U_{l}\\to U\\ .\n\\end{matrix}\n\\right.}\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n \n if ( (Ur-U)*(U-Ul) <= 0.0) { \n Ur = U;\n Ul = U;\n return;\n }\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n$$\n\\boxed{\\text{Case 2: if}\\ \\delta U\\left(U - \\delta_{m}U\\right) > \\frac{\\left(\\delta U\\right)^{2}}{6} \\ \\text{then:}\\ \n\\left\\{\n\\begin{matrix}\nU_{r} \\to U_{r}\\ ,\\\\\n\\ U_{l}\\to 3U-2U_{r}\\ .\n\\end{matrix}\n\\right.}\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n if ( dU*(U-mU) > (1.0/6.0)*SQR(dU)) { \n Ul = 3.0*U - 2.0*Ur;\n return;\n }\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n$$\n\\boxed{\\text{Case 3: if}\\ \\delta U\\left(U - \\delta_{m}U\\right) < -\\frac{\\left(\\delta U\\right)^{2}}{6} \\ \\text{then:}\\ \n\\left\\{\n\\begin{matrix}\nU_{r} \\to 3U-2U_{l}\\ ,\\\\\n\\ U_{l}\\to U_{l}\\ .\n\\end{matrix}\n\\right.}\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n if ( dU*(U-mU) < -(1.0/6.0)*SQR(dU)) {\n Ur = 3.0*U - 2.0*Ul;\n return;\n }\n}\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 6: The `compute_P_cold__Gamma_cold()` function \\[Back to [top](#toc)\\]\n$$\\label{compute_p_cold__Gamma_cold}$$\n\nThis part of the code evaluates $P_{\\rm cold}$ and $\\Gamma_{\\rm cold}$ for the equations of state (EOS) presented in eqs. 13-16 of [Stephens *et al.* (2008)](http://arxiv.org/pdf/0802.0200.pdf).\n\nFirst, if $\\rho_{b} = 0$, then $P_{\\rm cold} = 0$ and $\\Gamma_{\\rm cold}$ simply receives its tabulated value.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\nstatic inline void compute_P_cold__Gamma_cold(CCTK_REAL rho_b,eos_struct &eos, CCTK_REAL &P_cold,CCTK_REAL &Gamma_cold) {\n // This code handles equations of state of the form defined\n // in Eqs 13-16 in http://arxiv.org/pdf/0802.0200.pdf\n\n // Default in case rho_b == 0.0\n if(rho_b==0.0) { P_cold = 0.0; Gamma_cold = eos.Gamma_ppoly_tab[0]; return; }\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nNext we consider the case where the EOS is given by a single-polytrope\n\n$$\n\\boxed{P_{\\rm cold} = \\kappa \\rho_{b}^{\\Gamma_{\\rm cold}}}\\ ,\n$$\n\nand also the piecewise polytrope EOS\n\n$$\n\\boxed{\nP_{\\rm cold} =\n\\left\\{\n\\begin{matrix}\nK_{0}\\rho^{\\Gamma_{0}} & , & \\rho \\leq \\rho_{0}\\\\\nK_{1}\\rho^{\\Gamma_{1}} & , & \\rho_{0} \\leq \\rho \\leq \\rho_{1}\\\\\n\\vdots & & \\vdots\\\\\nK_{j}\\rho^{\\Gamma_{j}} & , & \\rho_{j-1} \\leq \\rho \\leq \\rho_{j}\\\\\n\\vdots & & \\vdots\\\\\nK_{N-1}\\rho^{\\Gamma_{N-1}} & , & \\rho_{N-2} \\leq \\rho \\leq \\rho_{N-1}\\\\\nK_{N}\\rho^{\\Gamma_{N}} & , & \\rho \\geq \\rho_{N-1}\n\\end{matrix}\n\\right.\n}\\ .\n$$\n\nNotice that we left the fact that $\\Gamma_{i} \\equiv \\Gamma_{{\\rm cold},i}$ implicit above.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n /***********************************\n * Piecewise Polytropic EOS Patch *\n * Computing P_cold and Gamma_cold *\n ***********************************/\n int polytropic_index = find_polytropic_K_and_Gamma_index(eos,rho_b);\n Gamma_cold = eos.Gamma_ppoly_tab[polytropic_index];\n P_cold = eos.K_ppoly_tab[polytropic_index]*pow(rho_b,Gamma_cold);\n \n}\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 7: The `ftilde_gf_compute()` function \\[Back to [top](#toc)\\]\n$$\\label{ftilde_gf_compute}$$\n\nThis is the driver function of the `ftilde_compute()` function, setting up the dependencies needed to compute $\\tilde{f}$. Please refer to the next step to see how $\\tilde{f}$ is computed.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n#define OMEGA1 0.75\n#define OMEGA2 10.0\n#define EPSILON2 0.33\nstatic void ftilde_gf_compute(const cGH *cctkGH,const int *cctk_lsh,const int flux_dirn,gf_and_gz_struct *in_prims,CCTK_REAL *ftilde_gf) {\n\n DECLARE_CCTK_PARAMETERS;\n\n int ijkgz_lo_hi[4][2];\n CCTK_REAL U[MAXNUMVARS][MAXNUMINDICES];\n /*Remove gcc unused variable warning/error Re: Pragma statement in loop define:*/\n CCTK_REAL dU,slope_lim_dU,Ur,Ul; dU=slope_lim_dU=Ur=Ul=0.0; dU*=0;\n // Compute ftilde, which is used for flattening left and right face values\n LOOP_DEFINE(2,2, cctk_lsh,flux_dirn, ijkgz_lo_hi,in_prims[VX+(flux_dirn-1)].gz_lo,in_prims[VX+(flux_dirn-1)].gz_hi) {\n SET_INDEX_ARRAYS(-2,2,flux_dirn);\n for(int ii=MINUS2;ii<=PLUS2;ii++) U[RHOB][ii] = in_prims[RHOB ].gf[index_arr[flux_dirn][ii]];\n for(int ii=MINUS2;ii<=PLUS2;ii++) U[PRESSURE][ii] = in_prims[PRESSURE].gf[index_arr[flux_dirn][ii]];\n U[VX+(flux_dirn-1)][MINUS1] = in_prims[VX+(flux_dirn-1)].gf[index_arr[flux_dirn][MINUS1]];\n U[VX+(flux_dirn-1)][PLUS1] = in_prims[VX+(flux_dirn-1)].gf[index_arr[flux_dirn][PLUS1]];\n\n // Compute ftilde, which is used for flattening left and right face values\n // DEPENDENCIES: P(MINUS2,MINUS1,PLUS1,PLUS2) and v^m(MINUS1,PLUS1), where m=flux_dirn={1,2,3}={x,y,z}.\n ftilde_gf[index_arr[flux_dirn][PLUS0]] = ftilde_compute(flux_dirn,rho_b_atm,U);\n }\n}\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 8: The `ftilde_compute()` function \\[Back to [top](#toc)\\]\n$$\\label{ftilde_compute}$$\n\nWe start by evaluating\n\n\\begin{align}\n\\delta P_{1} &\\equiv P_{i+1} - P_{i-1}\\ ,\\\\\n\\delta P_{2} &\\equiv P_{i+2} - P_{i-2}\\ .\n\\end{align}\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\nstatic inline CCTK_REAL ftilde_compute(const int flux_dirn,const CCTK_REAL rho_b_atm,CCTK_REAL U[MAXNUMVARS][MAXNUMINDICES]) {\n CCTK_REAL dP1 = U[PRESSURE][PLUS1] - U[PRESSURE][MINUS1];\n CCTK_REAL dP2 = U[PRESSURE][PLUS2] - U[PRESSURE][MINUS2];\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nThen we modify the standard PPM algorithm slightly by introducing the following conditions:\n\n\\begin{align}\n{\\rm if}\\ \\left|\\frac{\\delta P_{1}}{\\delta_{m}P_{1}}\\right| = 0\\ {\\rm or}\\ \\left|\\left(\\rho_{b}\\right)_{i+1}+\\left(\\rho_{b}\\right)_{i-1}\\right| < 10\\rho_{\\rm atm}\\ {\\rm then\\ set}\\ \\delta P_{1}=0\\ ,\\\\\n{\\rm if}\\ \\left|\\frac{\\delta P_{2}}{\\delta_{m}P_{2}}\\right| = 0\\ {\\rm or}\\ \\left|\\left(\\rho_{b}\\right)_{i+1}+\\left(\\rho_{b}\\right)_{i-1}\\right| < 10\\rho_{\\rm atm}\\ {\\rm then\\ set}\\ \\delta P_{2}=0\\ ,\n\\end{align}\n\nwhere\n\n\\begin{align}\n\\delta_{m} P_{1} &\\equiv \\frac{P_{i+1} + P_{i-1}}{2}\\ ,\\\\\n\\delta_{m} P_{2} &\\equiv \\frac{P_{i+2} + P_{i-2}}{2}\\ .\n\\end{align}\n\nNote that if the first condition above is satisfied then we are *not* inside a shock, while if the second condition is triggered *alone* there *may* be a shock.\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n // MODIFICATION TO STANDARD PPM:\n // Cure roundoff error issues when dP1==0 or dP2==0 to 15 or more significant digits.\n CCTK_REAL avg1=0.5*(U[PRESSURE][PLUS1] + U[PRESSURE][MINUS1]);\n CCTK_REAL avg2=0.5*(U[PRESSURE][PLUS2] + U[PRESSURE][MINUS2]);\n if(fabs(dP1)/avg1<1e-15 || fabs(U[RHOB][PLUS1] + U[RHOB][MINUS1])<10.0*rho_b_atm ) dP1=0.0; /* If this is triggered, there is NO shock. Also ignore \"shocks\" that appear entirely in the atmosphere (or regions with densities ~ 10*rho_b_atm). */\n if(fabs(dP2)/avg2<1e-15 || fabs(U[RHOB][PLUS2] + U[RHOB][MINUS2])<10.0*rho_b_atm ) dP2=0.0; /* If this is triggered alone, there may be a shock. Otherwise if triggered with above, NO shock. Also ignore \"shocks\" that appear entirely in the atmosphere (or regions with densities ~ 10*rho_b_atm). */\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nNext we set\n\n$$\n{\\rm dP1\\_over\\_dP2} = \n\\left\\{\n\\begin{matrix}\n\\frac{\\delta P_{1}}{\\delta P_{2}} &,\\ {\\rm if}\\ \\delta P_{2} \\neq 0\\\\\n1 &,\\ {\\rm otherwise}\n\\end{matrix}\n\\right.\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n CCTK_REAL dP1_over_dP2=1.0;\n if (dP2 != 0.0) dP1_over_dP2 = dP1/dP2;\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nWe then construct\n\n\\begin{align}\nq_{1} &= \\left({\\rm dP1\\_over\\_dP2}-\\omega_{1}\\right)\\omega_{2}\\ ,\\\\\nq_{2} &= \\frac{\\left|\\delta P_{1}\\right|}{\\min\\left(P_{i+1},P_{i-1}\\right)}\\ .\n\\end{align}\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n CCTK_REAL q1 = (dP1_over_dP2-OMEGA1)*OMEGA2;\n CCTK_REAL q2 = fabs(dP1)/MIN(U[PRESSURE][PLUS1],U[PRESSURE][MINUS1]);\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\nWe then initialize a new variable, $w$, to 0, i.e. we assume there is no shock. In the old version of `IllinoisGRMHD`, we would perform the following check:\n\n$$\n\\text{OLD LOGIC: }w = \n\\left\\{\n\\begin{matrix}\n1\\ , &\\ {\\rm if}\\ q_{2} > \\epsilon_{2}\\ {\\rm and}\\ q_{2}\\left(v^{\\rm flux\\ dirn}_{i-1}-v^{\\rm flux\\ dirn}_{i+1}\\right)>0, & \\left({\\rm inside\\ shock}\\right)\\ ,\\\\\n0\\ , &\\ {\\rm otherwise}, & \\left({\\rm outside\\ shock}\\right)\\ ,\n\\end{matrix}\n\\right.\n$$\n\nwhere $v^{\\rm flux\\ dirn}$ represents either $v^{x}$, $v^{y}$, or $v^{z}$, depending on the flux direction. This would, then, set $w=1$ when the shock condition above is satisfied. However, upon revision, a more robust logic is the following:\n\n* Compute $\\delta v \\equiv v^{\\rm flux\\ dirn}_{i-1} - v^{\\rm flux\\ dirn}_{i+1}$.\n* Compute $\\delta_{m} v \\equiv v^{\\rm flux\\ dirn}_{i-1} + v^{\\rm flux\\ dirn}_{i+1}$.\n* Compute $v_{\\rm rel\\ err} \\equiv \\left|\\delta v\\right|/\\delta_{m} v$.\n\nThen, the shock condition becomes:\n\n$$\n{\\rm if}\\ v_{\\rm rel\\ err} > 10^{-15}\\ {\\rm and}\\ q_{2}>\\epsilon_{2}\\ {\\rm and}\\ \\delta v > 0 \\implies \\left({\\rm inside\\ shock}\\right).\n$$\n\nThis is a more robust test of whether we are in a shock or not, because we avoid problems in the atmosphere where the values of $v^{\\rm flux\\ dirn}_{i\\pm1}$ can differ only by machine precision and cause an undesired trigger of the shock flag. We also take advantage of the fact that $q_{2}$ is necessarily positive, by definition, so it was not helping in the second Boolean comparison of the previous logic.\n\nFinally, $\\tilde{f}$ is given by\n\n$$\n\\boxed{\\tilde{f} = \\min\\left[1,w\\max\\left(0,q_{1}\\right)\\right]}\\ .\n$$\n\n\n```python\n%%writefile -a $outdir/reconstruct_set_of_prims_PPM.C\n\n\n // w==0 -> NOT inside a shock\n CCTK_REAL w=0.0;\n\n // w==1 -> inside a shock\n // Original code: if (q2 > EPSILON2 && q2*( (U[VX+(flux_dirn-1)][MINUS1]) - (U[VX+(flux_dirn-1)][PLUS1]) ) > 0.0) w = 1.0;\n // comments: 1. q2 = (positive number) / (positive number) is always positive, so it's useless in the second Boolean comparison\n // comments: 2. It may be the case that (U[VX+(flux_dirn-1)][MINUS1]) and (U[VX+(flux_dirn-1)][PLUS1]) differ at 1 part in 1e16 or so. We don't want the point to be marked as a shock due to this imperceptible difference.\n // New code addresses above comments by removing the \"q2*\" and computing the relative error between the velocities.\n const CCTK_REAL v_fluxdirn_minus1 = U[VX+(flux_dirn-1)][MINUS1];\n const CCTK_REAL v_fluxdirn_plus1 = U[VX+(flux_dirn-1)][PLUS1];\n const CCTK_REAL dv = v_fluxdirn_minus1 - v_fluxdirn_plus1;\n const CCTK_REAL avgabsv = 0.5*(fabs(v_fluxdirn_minus1) + fabs(v_fluxdirn_plus1));\n CCTK_REAL v_rel_error = 0.0; //dv/avgabsv;\n if(avgabsv != 0) v_rel_error = fabs(dv)/avgabsv; // We should never flag a point as a shock if the velocities agree to\n if(v_rel_error > 1e-15 && q2 > EPSILON2 && dv > 0.0) w = 1.0;\n\n return MIN(1.0, w*MAX(0.0,q1));\n}\n\n\n```\n\n Appending to ../src/reconstruct_set_of_prims_PPM.C\n\n\n\n\n# Step 9: Code validation \\[Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n\n## Step 9.a: `loop_defines_reconstruction.h` \\[Back to [top](#toc)\\]\n$$\\label{loop_defines_reconstruction__h_validation}$$\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/loop_defines_reconstruction.h\"\n# original_IGM_file_name = \"loop_defines_reconstruction-original.h\"\n# original_IGM_file_path = os.path.join(IGM_src_dir_path,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__loop_defines_reconstruction__h = !diff $original_IGM_file_path $outfile_path__loop_defines_reconstruction__h\n\n# if Validation__loop_defines_reconstruction__h == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for loop_defines_reconstruction.h: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for loop_defines_reconstruction.h: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__loop_defines_reconstruction__h:\n# print(diff_line)\n```\n\n\n\n## Step 9.b: `reconstruct_set_of_prims_PPM.C` \\[Back to [top](#toc)\\]\n$$\\label{reconstruct_set_of_prims_ppm__c_validation}$$\n\n\n```python\n# # Verify if the code generated by this tutorial module\n# # matches the original IllinoisGRMHD source code\n\n# # First download the original IllinoisGRMHD source code\n# import urllib\n# from os import path\n\n# original_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/reconstruct_set_of_prims_PPM.C\"\n# original_IGM_file_name = \"reconstruct_set_of_prims_PPM-original.C\"\n# original_IGM_file_path = os.path.join(IGM_src_dir_path,original_IGM_file_name)\n\n# # Then download the original IllinoisGRMHD source code\n# # We try it here in a couple of ways in an attempt to keep\n# # the code more portable\n# try:\n# original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# try:\n# original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n# # Write down the file the original IllinoisGRMHD source code\n# with open(original_IGM_file_path,\"w\") as file:\n# file.write(original_IGM_file_code)\n# except:\n# # If all else fails, hope wget does the job\n# !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# # Perform validation\n# Validation__reconstruct_set_of_prims_PPM__C = !diff $original_IGM_file_path $outfile_path__reconstruct_set_of_prims_PPM__C\n\n# if Validation__reconstruct_set_of_prims_PPM__C == []:\n# # If the validation passes, we do not need to store the original IGM source code file\n# !rm $original_IGM_file_path\n# print(\"Validation test for reconstruct_set_of_prims_PPM.C: PASSED!\")\n# else:\n# # If the validation fails, we keep the original IGM source code file\n# print(\"Validation test for reconstruct_set_of_prims_PPM.C: FAILED!\")\n# # We also print out the difference between the code generated\n# # in this tutorial module and the original IGM source code\n# print(\"Diff:\")\n# for diff_line in Validation__reconstruct_set_of_prims_PPM__C:\n# print(diff_line)\n```\n\n\n\n# Step 10: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-IllinoisGRMHD_reconstruct_set_of_prims_PPM.pdf](Tutorial-IllinoisGRMHD_reconstruct_set_of_prims_PPM.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means).\n\n\n```python\nlatex_nrpy_style_path = os.path.join(nrpy_dir_path,\"latex_nrpy_style.tplx\")\n#!jupyter nbconvert --to latex --template $latex_nrpy_style_path --log-level='WARN' Tutorial-IllinoisGRMHD__reconstruct_set_of_prims_PPM.ipynb\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD_reconstruct__set_of_prims_PPM.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD_reconstruct__set_of_prims_PPM.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD_reconstruct__set_of_prims_PPM.tex\n!rm -f Tut*.out Tut*.aux Tut*.log\n```\n", "meta": {"hexsha": "0f3a6af01189400955879dce92dd88e1aed8a338", "size": 81801, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__reconstruct_set_of_prims_PPM.ipynb", "max_stars_repo_name": "leowerneck/NRPyIGM", "max_stars_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__reconstruct_set_of_prims_PPM.ipynb", "max_issues_repo_name": "leowerneck/NRPyIGM", "max_issues_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__reconstruct_set_of_prims_PPM.ipynb", "max_forks_repo_name": "leowerneck/NRPyIGM", "max_forks_repo_head_hexsha": "f483d6123424fb3e6860dfac4325dd232b223005", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0354573484, "max_line_length": 806, "alphanum_fraction": 0.5557267026, "converted": true, "num_tokens": 21003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.31804576486159986}} {"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility here.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''''')\n# display(tag)\n```\n\n\n\nToggle cell visibility here.\n\n\n\n```python\n%matplotlib notebook\nimport numpy as np\nimport control as control\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nimport scipy.signal as signal\ncontinuous_update=False\n```\n\n## Time response of the first-order system\n\nThe transfer function of the selected first-order system is defined as\n\n\\begin{equation}\n \\frac{K_p}{\\tau_p s+1},\n\\end{equation}\n\nwhere $K_p$ and $\\tau_p$ are parameters of the system. \n\nSystem response depends on the input signal. In this example unit step function (with the Laplace transform $\\frac{1}{s}$), unit impulse function (with the Laplace transform $1$), unit ramp function (with the Laplace transform $\\frac{1}{s^2}$) and a sine signal (with the Laplace transform $\\frac{1}{s^2+1}$) are used as possible input signals. \n\nThe plot below shows the input signal and the corresponding output signal for the chosen values of parameters $K_p$ and $\\tau_p$.\n\n### How to use this notebook?\n\nToogle between different input functions (unit step, unit impulse, unit ramp or sine). Move the sliders to change the values of $K_p$ and $\\tau_p$. \n\n\n```python\n# sinus, step, ramp, x^2, sqrt(x)\nfunctionSelect = widgets.ToggleButtons(\n options=[('unit step function', 0), ('unit impulse function', 1), ('unit ramp function', 2), ('sine function', 3)],\n description='Select: ')\n\nfig = plt.figure(num='Time response of the first-order system')\nfig.set_size_inches((9.8, 3))\nfig.set_tight_layout(True)\nf1 = fig.add_subplot(1, 1, 1)\n\nf1.grid(which='both', axis='both', color='lightgray')\n\nf1.set_xlabel('$t$ [s]')\nf1.set_ylabel('input, output')\n\nf1.axhline(0,Color='black',linewidth=0.5)\nf1.axvline(0,Color='black',linewidth=0.5)\n\ninputf, = f1.plot([],[])\nresponsef, = f1.plot([],[])\narrowf, = f1.plot([],[])\n\nnum_samples=2041\n\ndef create_draw_functions(Kp,taup,index):\n t=np.linspace(-0.1,5,num_samples)\n\n num=[Kp]\n den=[taup,1]\n Wsys=control.tf(num,den)\n \n global inputf,responsef, arrowf\n \n if index==0:\n yin=np.zeros(2041)\n yin[40:num_samples]=1\n tnew=np.linspace(0,5,2001)\n tout,yout=control.step_response(Wsys, T=tnew)\n elif index==1:\n yin=signal.unit_impulse(2001, 0)\n tnew=np.linspace(0,5,2001)\n t=tnew\n tout,yout=control.impulse_response(Wsys,tnew,X0=0)\n elif index==2:\n yin=np.zeros(num_samples)\n yin[40:num_samples]=np.linspace(0,5,2001)\n tnew=np.linspace(0,5,2001)\n tout,yout,xx=control.forced_response(Wsys,tnew,yin[40:])\n elif index==3: \n yin=np.sin(np.linspace(0,30,2001))\n tnew=np.linspace(0,30,2001)\n t=tnew\n tout,yout,xx=control.forced_response(Wsys,tnew,yin)\n \n f1.lines.remove(inputf)\n f1.lines.remove(responsef)\n f1.lines.remove(arrowf)\n \n inputf, = f1.plot(t,yin,color='C0',label='input')\n responsef, = f1.plot(tout,yout,color='C1',label='output')\n\n if index == 1:\n arrowf, = f1.plot([-0.1,0,0.1],[0.95,1,0.95],color='C0')\n else:\n arrowf, = f1.plot([],[])\n \n \n f1.legend()\n \n f1.relim()\n f1.relim()\n f1.autoscale_view()\n f1.autoscale_view()\n \nKp_slider = widgets.FloatSlider(value=1, min=0, max=2, step=0.1, description='$K_p$',\n continuous_update=True, layout=widgets.Layout(width='auto', flex='5 5 auto'),readout_format='.1f')\n\ntaup_slider = widgets.FloatSlider(value=1, min=0, max=2, step=0.1, description='$\\\\tau_p$',\n continuous_update=True, layout=widgets.Layout(width='auto', flex='5 5 auto'),readout_format='.1f')\n\n\ninput_data = widgets.interactive_output(create_draw_functions, {'Kp':Kp_slider,\n 'taup':taup_slider,\n 'index':functionSelect})\n\ndef update_sliders(index):\n global x0_slider\n \n Kpval = [1,1,1,1]\n Kp_slider.value = Kpval[index]\n taupval = [1,1,1,1]\n taup_slider.value = taupval[index] \n \ninput_data2 = widgets.interactive_output(update_sliders, {'index':functionSelect})\n\ndisplay(functionSelect)\n\ndisplay(Kp_slider,taup_slider,input_data)\n\n# display(Markdown(\"The system can be represented as $f(x)=5$ for small excursions of x about x0.\"))\n```\n\n\n \n\n\n\n\n\n\n\n ToggleButtons(description='Select: ', options=(('unit step function', 0), ('unit impulse function', 1), ('unit…\n\n\n\n FloatSlider(value=1.0, description='$K_p$', layout=Layout(flex='5 5 auto', width='auto'), max=2.0, readout_for…\n\n\n\n FloatSlider(value=1.0, description='$\\\\tau_p$', layout=Layout(flex='5 5 auto', width='auto'), max=2.0, readout…\n\n\n\n Output()\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "f805bb03380d878fb0732e28860ba177301fc875", "size": 89804, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_en/examples/02/.ipynb_checkpoints/TD-11-Time-response-First-order-system-checkpoint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT/ENG/examples/02/TD-11-Time-response-First-order-system.ipynb", "max_issues_repo_name": "tuxsaurus/ICCT", "max_issues_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT/ENG/examples/02/TD-11-Time-response-First-order-system.ipynb", "max_forks_repo_name": "tuxsaurus/ICCT", "max_forks_repo_head_hexsha": "30d1aea4fb056c9736c9b4c5a0f50fff14fa6382", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 82.3889908257, "max_line_length": 45513, "alphanum_fraction": 0.7283194512, "converted": true, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3176299335587883}} {"text": "# Stoichiometric Structure\nPart I of this book introduced the basics of dynamic simulation. The process for setting up dynamic equations, their simulation, and processing of the output was presented in Chapter 3. Several concepts of dynamic analysis of networks were illustrated through the use of simple examples of chemical reaction mechanisms in Chapters 4 through 6. Most of these examples were conceptual and had limited direct biological relevance. In Chapter 7 we began to estimate the numerical values and ranges for key quantities in dynamic models. With this background, we now begin the process of addressing issues that are important when one builds realistic dynamic models of biological functions. We start by exploring the consequences of reaction bilinearity and that of the stoichiometric structure of a network. In Part III we then extend the material in this chapter to well-known metabolic pathways. \n\n**MASSpy** will be used to demonstrate some of the topics in this chapter. \n\n\n```python\nfrom mass import (\n MassModel, MassMetabolite, MassReaction,\n Simulation, MassSolution, strip_time)\nfrom mass.util.matrix import nullspace, left_nullspace\nfrom mass.visualization import plot_time_profile, plot_phase_portrait\n```\n\nOther useful packages are also imported at this time.\n\n\n```python\nimport numpy as np\nimport pandas as pd\nimport sympy as sym\nimport matplotlib.pyplot as plt\nXL_FONT = {\"size\": \"x-large\"}\n```\n\n## Bilinearity in Biochemical Reactions\n### Bilinear reactions \nThey are of the form:\n\n$$\\begin{equation} x + y \\rightarrow z \\tag{8.1} \\end{equation}$$\n\nTwo molecules come together to form a new molecule through the breaking and forming of covalent bonds, or a complex through the formation of hydrogen bonds. As illustrated with the pool formations in the bilinear examples in Chapter 4, such reactions come with moiety exchanges. \n\n### Enzyme classification \nEnzyme catalyzed reactions are classified in to seven categories by Enzyme Commission (EC) numbers, see Figure 8.1a. These categories are: oxidoreductases, transferases, hydrolases, lyases, isomerases, and ligases. All these chemical transformations are bilinear with the exception of isomerases that simply rearrange a molecule without the participation of other reactants. Thus, the vast majority of biochemical reactions are bilinear. An overall pseudo-elementary representation (i.e., without treating the enzyme itself as a reactant, and just representing the un-catalyzed reaction) is bilinear. \n\n\n\n**Figure 8.1:** The bilinear nature of biochemical reactions. (a) The classification of enzyme catalyzed reactions into seven categories by the enzyme commission (EC) number system. (b) The detailed view of the role of coenzymes and prosthetic groups in enzyme catalyzed reactions. Coenzymes are often referred to as cofactors. Both images from Koolman, 2005 (reprinted with permission).\n\n### Coenzymes and prosthetic groups \nThere are coenzymes and prosthetic groups that are involved in many biochemical reactions. These molecules are involved in group transfer reactions as illustrated in Figure 8.1b. They can transfer various chemical moieties or redox equivalents, see Table 8.1. Coenzymes act like a reactant and product in a reaction. They can work with many enzymes performing reactions that need them. Prosthetic groups associate with a particular enzyme to give it chemical functionalities that the protein itself does not have, Figure 8.1b. The heme group on hemoglobin is perhaps the most familiar example (see Chapter 13) that allows the protein tetramer to acquire a ferrous ion thus enabling the binding of oxygen. This binding allows the red blood cell to perform its oxygen delivery functions. There are many such capabilities 'grafted' onto proteins in the form of prosthetic groups. Many of the vitamins confer functions on protein complexes. \n\n## Bilinearity Leads to a Tangle of Cycles\n### Moiety exchange: \nBiochemical reaction networks are primarily made up of bilinear reactions. A fundamental consequence of this characteristic is a deliberate exchange of chemical moieties and properties between molecules. This exchange is illustrated in Figure 8.2. Here, an incoming molecule, $XA$, puts the moiety, $A$, onto a carrier molecule, $C$. The carrier molecule, now in a 'charged' form $(CA)$, can donate the $A$ moiety to another molecule, $Y$, to form $YA$. The terms _coenzyme,_ _cofactor_ or _carrier_ are used to describe the $C$ molecule.\n\n\n\n**Figure 8.2:** Carrier $(C)$ mediated transfer of chemical moiety $A$ from compound $X$ to compound $Y$.\n\n### Formation of cycles: \nThe ability of bilinear reactions to exchange moieties in this fashion leads to the formation of distribution networks of chemical moieties and other properties of interest through the formation of a deliberate 'supply-chain' network. The structure of such a network must be thermodynamically feasible and conform to environmental constraints. \n\nBilinearization in biochemical reaction networks leads to a 'tangle of cycles,' where different moieties and properties are being moved around the network. While a property of all biochemical networks, this trafficking of chemical and other properties is best known in metabolism. The major chemical properties that are being exchanged in metabolism are summarized in Table 8.1. These properties include energy, redox potential, one-carbon units, two-carbon units, amide groups, amine groups, etc. We now consider some specific cases. \n\n**Table 8.1:** Some activated carriers or coenzymes in metabolism, modified from Kurganov, 1983.\n\n\n\n#### Example: Redox and energy trafficking in the core _E. coli_ metabolic pathways \nEnergy metabolism revolves around the generation of redox potential and chemical energy in the form of high-energy phosphate bonds. The degradation of substrates through a series of chemical reactions culminates in the storage of these properties on key carrier molecules; see Table 8.1. \n\nThe core metabolic pathways in _E. coli_ illustrate this feature, Figure 8.3. The transmission of redox equivalents through this core set of pathways is shown in Figure 8.3a. Each pathway is coupled to a redox carrier in a particular way. This pathway map can be drawn to show the cofactors rather than the primary metabolites and the main pathways (Figure 8.3b). This figure clearly shows how the cofactors interact and how the bilinear property of the stoichiometry of the core set of pathways leads to a tangle of cycles among the redox carriers. \n\n\n\n**Figure 8.3:** The tangle of cycles in trafficking of redox potential (R) in _E. coli_ core metabolic pathways. (a) A map organized around the core pathways. (b) The tangle of cycles seen by viewing the cofactors and how they are coupled. Prepared by Jeff Orth.\n\n#### Example: Protein trafficking in signaling pathways \nAlthough the considerations above are illustrated using well-known metabolic pathways, these same features are also observed in signaling pathways. Incoming molecules (ligands) trigger a well-defined series of charging and discharging of the protein that make up a signaling network, most often with a phosphate group. \n\n## Trafficking of High-Energy Phosphate Bonds\nGiven the bilinear nature of biochemical reaction networks and the key role that cofactors play, we begin the process of building biologically meaningful simulation models by studying the use and formation of high-energy phosphate bonds. Cellular energy is stored in high-energy phosphate bonds in ATP. The dynamic balance of the rates of use and formation of ATP is thus a common denominator in all cellular processes, and thus foundational to the living process. We study the dynamic properties of this system in a bottom-up fashion by starting with its simple elements and making the description progressively more complicated. Throughout the text we make explicit use of the basic methods in **MASSpy**.\n\n\n\n**Figure 8.4:** Representation of the exchange of high energy phosphate bonds among the adenosine phosphates. (a) The chemical reactions. (b) The molecules with open circles showing the \"vacant\" places for high energy bonds. The capacity to carry high-energy phosphate bonds, the occupancy of high-energy bonds, and the energy charge are shown. (c) The reaction schema of (a) in pictorial form. The solid squares represent AMP and the solid circles the high energy phosphate bonds. (d) The same concepts as in (b) represented in pictorial form.\n\n### Distribution of high-energy phosphate groups: adenylate kinase (EC 2.7.4.3)\nThe Adenylate Kinase is an important part in intracellular energy homeostasis. Adenylate Kinase is a phosphotransferase enzyme and it is the enzyme responsible for the redistribution of the phosphate groups among the adenosine phosphates. The redistribution reaction the Adenylate Kinase catalyzes is seen in Figure 8.4a.\n\n#### The mass balance: adenylate kinase\nThe redistribution of the phosphate groups among the adenosine phosphates by the adenylate kinase is given by the following kinetic equations:\n\n$$\\begin{equation} \\frac{d\\text{ATP}}{dt} = v_{\\mathrm{distr}}, \\ \\frac{d\\text{ADP}}{dt} = -2\\ v_{\\mathrm{distr}}, \\ \\frac{d\\text{AMP}}{dt} = v_{\\mathrm{distr}} \\tag{8.2} \\end{equation}$$\n\n#### The reaction rates: adenylate kinase\nThe mass action form of these basic reaction rates are \n\n$$\\begin{equation} v_{\\mathrm{distr}} = k_{\\mathrm{distr}}^\\rightarrow\\text{ADP}^2 - k_{\\mathrm{distr}}^\\leftarrow\\text{ATP}*\\text{AMP} \\tag{8.3} \\end{equation}$$\n\n#### Numerical values: adenylate kinase\nThe approximate numerical values of the parameters in this system can be estimated. In metabolically active tissues, the ATP concentration is about 1.6 mM, the ADP concentration is about 0.4 mM, and the AMP concentration is about 0.1 mM. Total adenosine phosphates are thus about 2.1 mM. Because this reaction is considerably faster compared to other metabolic processes, we set $k_{\\mathrm{distr}}^\\rightarrow$ to 1000/Min. $K_{\\mathrm{distr}}$ for the distribution reaction is approximately unity. We then construct a model of the redistribution of phosphate groups among the adenosine phosphates by adenylate kinase using the above constraints. This is simple reversible reaction that equilibrates quickly.\n\n\n\n**Figure 8.5:** The redistribution of phosphate groups among the adenosine phosphates by adenylate kinase.\n\n\n```python\nphos_traffic = MassModel(\"Phosphate_Trafficking\", array_type=\"DataFrame\",\n dtype=np.int64)\n# Define metabolites\natp = MassMetabolite(\"atp\")\nadp = MassMetabolite(\"adp\")\namp = MassMetabolite(\"amp\")\n# Define reactions\nv_distr = MassReaction(\"distr\")\nv_distr.add_metabolites({adp: -2, amp: 1, atp:1})\n\n# Add reactions to model\nphos_traffic.add_reactions([v_distr])\n\n# Define initial conditions and parameters\natp.ic = 1.6\nadp.ic = 0.4\namp.ic = 0.1\n\nv_distr.kf = 1000\nv_distr.Keq = 1\n```\n\n Set parameter Username\n\n\n#### Null spaces: adenylate kinase\nThe stoichiometric matrix is basically a column vector.\n\n\n```python\nphos_traffic.S\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
distr
adp-2
amp1
atp1
\n
\n\n\n\nIt has an empty null space; i.e. zero dimensional.\n\n\n```python\nnullspace(phos_traffic.S, rtol=1e-1)\n```\n\n\n\n\n array([], shape=(1, 0), dtype=float64)\n\n\n\nHowever, the left null space has two dimensions and it thus has two conservation pools. \n\n\n```python\n# Obtain left nullspace\nlns = left_nullspace(phos_traffic.S, rtol=1e-1)\n# Iterate through left nullspace, \n# dividing by the smallest value in each row. \nfor i, row in enumerate(lns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the left nullspace is composed of only integers\n lns[i] = np.array([round(value) for value in new_row])\n\n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(lns):\n lns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Create a pandas.DataFrame to represent the left nullspace\npd.DataFrame(lns, index=[\"Vacancy\", \"Occupancy\"], \n columns=phos_traffic.metabolites, dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
adpampatp
Vacancy120
Occupancy102
\n
\n\n\n\nThe interpretation of these pools is remarkably interesting: the first one counts the number of high energy phosphate bonds in the system, while the second counts the number of vacant spots where high energy phosphate bonds can be added. The left null space is spanned by these two vectors that we can think of as a conjugate pair. Furthermore, the summation of the two is the total amount of the 'A' nucleotide in the system times two; ie the total number of possible high-energy phosphate bonds that the system can carry. \n\n\n```python\n# Sum the elements of each row to obtain the capacity pool\ncapacity = np.array([np.sum(lns, axis=0)])\npd.DataFrame(capacity, index=[\"Capacity\"],\n columns=phos_traffic.metabolites, dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
adpampatp
Capacity222
\n
\n\n\n\nNote that any activity of this reaction does not change the sizes of these two pools as the left null space is orthogonal to the reaction vector (or the column vector of $(\\textbf{S})$, that represents the direction of motion.\n\n### Using and generating high-energy phosphate groups \nWe now introduce the 'use' and 'formation' reactions for ATP into the above system. These represent aggregate processes in the cell using and forming high energy bonds.\n\n#### The mass balances: trafficking high-energy phosphate bonds\n$$\\begin{align} \\frac{d\\text{ATP}}{dt} &= -v_{\\mathrm{use}} + v_{\\mathrm{form}} + v_{\\mathrm{distr}} \\tag{8.4} \\\\ \\frac{d\\text{ADP}}{dt} &= v_{\\mathrm{use}} - v_{\\mathrm{form}} - 2\\ v_{\\mathrm{distr}} \\tag{8.5} \\\\ \\frac{d\\text{AMP}}{dt} &= v_{\\mathrm{distr}} \\tag{8.6} \\end{align}$$\n\nwhere $v_{\\mathrm{use}}$ is the rate of use of ATP, $v_{\\mathrm{form}}$ is the rate of formation of ATP, and, as above, $v_{\\mathrm{distr}}$ is the redistribution of the phosphate group among the adenosine phosphates by adenylate kinase. \n\n#### The reaction rates: trafficking high-energy phosphate bonds\nElementary mass action form for the two additional rate equations are \n\n$$\\begin{equation} v_{\\mathrm{use}} = k_{\\mathrm{use}}^\\rightarrow \\text{ATP},\\ v_{\\mathrm{form}} = k_{\\mathrm{form}}^\\rightarrow\\text{ADP}\\tag{8.7} \\end{equation}$$ \n\n#### Numerical values: trafficking high-energy phosphate bonds\nWe use the equilibrium concentrations from the distribution model and estimate in the numerical values for the rate constants of ATP use and formation based on the fact that typical use and formation rates of ATP are about 10 mM/min. Using the steady state concentrations, we can calculate $k_{\\mathrm{use}}^\\rightarrow$ and $k_{\\mathrm{form}}^\\rightarrow$, resulting in $k_{\\mathrm{use}}^\\rightarrow=6.25\\ min^{-1}$ and $k_{\\mathrm{form}}^\\rightarrow=25\\ min^{-1}$. These constants are known as Pseudo-Elementary Rate Constants (PERCs). They are a ratio between the flux through a reaction and the concentrations of the involved species, and the simplify the network dynamic analysis. However they are condition dependent and result in a condition dependent kinetic model. What comprises the PERCs is explored further in the later chapters. \n\nWe update the distribution model with the additional reactions and parameters. \n\n\n\n**Figure 8.6:** The trafficking of high-energy phosphate bonds.\n\n\n```python\n# Create utilization reaction\nv_use = MassReaction(\"use\", reversible=False)\nv_use.add_metabolites({atp: -1, adp: 1})\nv_use.kf = 6.25\n\n# Create formation reaction\nv_form = MassReaction(\"form\", reversible=False)\nv_form.add_metabolites({adp: -1, atp: 1})\nv_form.kf = 25\n\n# Add reactions to model\nphos_traffic.add_reactions([v_use, v_form])\n\n# View rate of distribution reaction\nprint(v_distr.rate)\n```\n\n kf_distr*(adp(t)**2 - amp(t)*atp(t)/Keq_distr)\n\n\nFrom the model we also see that the net rate for the redistribution of high-energy bonds is\n\n$$\\begin{align} v_{\\mathrm{distr}} &= k_{\\mathrm{distr}}^\\rightarrow\\ \\text{ADP}^2 - k_{\\mathrm{distr}}^\\leftarrow\\text{ATP}*\\text{AMP} &\\tag{8.8a} \\\\ &= k_{\\mathrm{distr}}^\\rightarrow( \\text{ADP}^2 - \\text{ATP}*\\text{AMP}/K_{\\mathrm{distr}}) &\\tag{8.8b} \\end{align}$$\n\n#### Null spaces: trafficking high-energy phosphate bonds\nNow the stoichiometric matrix three columns. \n\n\n```python\nphos_traffic.S\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
distruseform
adp-21-1
amp100
atp1-11
\n
\n\n\n\nIt has a one-dimensional null space, that represents an internal loop as the use and formation reactions are the exact opposites of each other.\n\n\n```python\n# Obtain nullspace\nns = nullspace(phos_traffic.S, rtol=1e-1)\n# Transpose and iterate through nullspace, \n# dividing by the smallest value in each row.\nns = ns.T\nfor i, row in enumerate(ns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the nullspace is composed of only integers\n ns[i] = np.array([round(value) for value in new_row])\n\n \n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(ns):\n ns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Revert transpose\nns = ns.T\n# Create a pandas.DataFrame to represent the nullspace\npd.DataFrame(ns, index=[rxn.id for rxn in phos_traffic.reactions],\n columns=[\"Path 1\"], dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Path 1
distr0
use1
form1
\n
\n\n\n\nThe left null space is now one-dimensional;\n\n\n```python\n# Obtain left nullspace\nlns = left_nullspace(phos_traffic.S, rtol=1e-1)\n# Iterate through left nullspace, \n# dividing by the smallest value in each row. \nfor i, row in enumerate(lns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the left nullspace is composed of only integers\n lns[i] = np.array([round(value) for value in new_row])\n\n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(lns):\n lns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Create a pandas.DataFrame to represent the left nullspace\npd.DataFrame(lns, index=[\"Total AxP\"], \n columns=phos_traffic.metabolites, dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
adpampatp
Total AxP111
\n
\n\n\n\n#### Dynamic simulations: trafficking high-energy phosphate bonds \nThe system is steady at the initial conditions given\n\n\n```python\nt0, tf = (0, 1e3)\nsim = Simulation(phos_traffic, verbose=True)\nconc_sol, flux_sol = sim.simulate(\n phos_traffic, time=(t0, tf), interpolate=True,\n verbose=True)\n```\n\n \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n Successfully loaded MassModel 'Phosphate_Trafficking' into RoadRunner.\n Getting time points\n Setting output selections\n Setting simulation values for 'Phosphate_Trafficking'\n Simulating 'Phosphate_Trafficking'\n Simulation for 'Phosphate_Trafficking' successful\n Adding 'Phosphate_Trafficking' simulation solutions to output\n Updating stored solutions\n\n\n\n```python\nfig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 4),\n )\n(ax1, ax2) = axes.flatten()\n\nplot_time_profile(\n conc_sol, ax=ax1,\n legend=\"right outside\",plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Concentrations [mM]\", \n title=(\"Concentration Profile\", XL_FONT));\n\nplot_time_profile(\n flux_sol, ax=ax2,\n legend=\"right outside\", plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Fluxes [mM/min]\", \n title=(\"Flux Profile\", XL_FONT));\nfig.tight_layout()\n```\n\nWe can induce motion in the system by taking 0.2 mM of ADP and splitting it into 0.1 mM addition to AMP and ATP, and set the initial conditions as ATP is 1.7 mM, ADP is 0.2 mM, and AMP is 0.2 mM and simulate the dynamic response. We graph the concentration profiles, as well as the two pools and the disequilibrium variable: $\\text{ADP}^2 - \\text{ATP}*\\text{AMP}$ that is zero at the equilibrium\n\n\n```python\n# Define pools and perturbations\npools = {\"Occupancy\": \"adp + 2*atp\", \n \"Vacancy\": \"adp + 2*amp\", \n \"Disequilibrium\": \"adp**2 - atp*amp\"}\n\n# Simulate with disturbance\nconc_sol, flux_sol = sim.simulate(\n phos_traffic, time=(t0, tf),\n perturbations={\"atp\": 1.7, \"adp\": 0.2, \"amp\": 0.2})\n\n# Determine pools\nfor pool_id, equation_str in pools.items():\n conc_sol.make_aggregate_solution(\n pool_id, equation=equation_str, update=True)\n\n# Visualize solutions\nfig_8_7, axes = plt.subplots(nrows=3, ncols=1, figsize=(8, 8),)\n(ax1, ax2, ax3) = axes.flatten()\n\nplot_time_profile(\n conc_sol, ax=ax1, observable=phos_traffic.metabolites,\n legend=\"right outside\", plot_function=\"semilogx\", ylim=(0, 1.8),\n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(a) Concentration Profile\", XL_FONT));\n\nplot_time_profile(\n conc_sol, observable=[\"Occupancy\", \"Vacancy\"], ax=ax2, \n legend=\"right outside\", plot_function=\"semilogx\", ylim=(0., 4.),\n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(b) Occupancy and Vacancy Pools\", XL_FONT));\n\nplot_time_profile(\n conc_sol, observable=[\"Disequilibrium\"], ax=ax3,\n legend=\"right outside\", plot_function=\"semilogx\", ylim=(-.4, 0.1),\n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(c) Disequilibrium Variable\", XL_FONT));\nfig_8_7.tight_layout()\n```\n\n**Figure 8.7:** The time response of the adenylate kinase reaction (\"distr\") and with the addition of ATP use and formation to a change in the initial conditions. (a) The concentrations. (b) The occupancy and capacity pools. (c) The disequilibrium variable.\n\n#### Towards a realistic simulation of a dynamic response\nNext, we simulate the response of this system to a more realistic perturbation: a 50% increase in the rate of ATP use. This would represent a sudden increase in energy use by a cell. At time zero, we have the network in a steady state and we change $k_{\\mathrm{use}}^\\rightarrow$ from $6.25/min$ to $1.5*6.25=9.375/min$, and the rate of ATP use instantly becomes 15 mM/min. \n\nThe response of the system is perhaps best visualized by showing the phase portrait of the rate of ATP use versus ATP formation. Prior to the increased load, the system is on the 45 degree line, where the rate of ATP formation and use balances. Then at time zero it is instantly imbalanced by changing $k_{\\mathrm{use}}^\\rightarrow$ above or below its initial value. If $k_{\\mathrm{use}}^\\rightarrow$ is increased then the initial point moved into the region where more ATP is used than formed. From this initial perturbation the response of the system is to move directly towards the 45 degree line to regain balance between ATP use and formation.\n\n\n```python\nt0, tf = (0, 1e3)\n# Simulate with disturbance\nconc_sol, flux_sol = sim.simulate(\n phos_traffic, time=(t0, tf), \n perturbations={\"kf_use\": \"kf_use * 1.5\"},\n verbose=True)\n\n# Determine pools\nfor pool_id, equation_str in pools.items():\n conc_sol.make_aggregate_solution(\n pool_id, equation=equation_str, update=True)\n```\n\n Getting time points\n Parsing perturbations\n Setting output selections\n Setting simulation values for 'Phosphate_Trafficking'\n Simulating 'Phosphate_Trafficking'\n Simulation for 'Phosphate_Trafficking' successful\n Adding 'Phosphate_Trafficking' simulation solutions to output\n Updating stored solutions\n\n\n\n```python\nfig_8_8 = plt.figure(figsize=(15, 5))\ngs = fig_8_8.add_gridspec(nrows=3, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_8_8.add_subplot(gs[:, 0])\nax2 = fig_8_8.add_subplot(gs[0, 1])\nax3 = fig_8_8.add_subplot(gs[1, 1])\nax4 = fig_8_8.add_subplot(gs[2, 1])\n\nlabel = \"{0} [mM/min]\"\nplot_phase_portrait(\n flux_sol, x=v_use, y=v_form, ax=ax1,\n time_vector=np.linspace(t0, 1, int(1e4)),\n xlabel=label.format(v_use.id), ylabel=label.format(v_form.id), \n xlim=(4, 21), ylim=(4, 21), \n title=(\"(a) Phase Portrait of ATP use vs. formation\", XL_FONT),\n annotate_time_points=\"endpoints\",\n annotate_time_points_labels=True);\n\nline_data = [i for i in range(0, 22)]\nax1.plot(line_data, line_data, ls=\"--\", color=\"black\")\nax1.annotate(\"use < form\", xy=(6, 15))\nax1.annotate(\"use > form\", xy=(15, 6))\nax1.annotate(\"Steady-state line:\\n use=form\", xy=(15, 19))\nax1.annotate(\"initial perturbation\", xy=(9.5, 9), xycoords=\"data\")\nax1.annotate(\"\", xy=(flux_sol[v_use.id][0], flux_sol[v_form.id][0]),\n xytext=(10, 10), textcoords=\"data\",\n arrowprops=dict(arrowstyle=\"->\",connectionstyle=\"arc3\"))\n\nplot_time_profile(\n conc_sol, observable=phos_traffic.metabolites,\n ax=ax2, legend=\"right outside\",\n time_vector=np.linspace(t0, 1, int(1e5)),\n xlim=(t0, 1), ylim=(0, 2),\n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(b) Concentration Profiles\", XL_FONT));\n\nplot_time_profile(\n flux_sol, observable=[v_use],\n ax=ax3, legend=\"right outside\",\n time_vector=np.linspace(t0, 1, int(1e5)),\n xlim=(t0, 1), ylim=(12, 16),\n xlabel=\"Time [min]\", ylabel=\"Flux [mM/min]\",\n title=(\"(c) Net ATP use\", XL_FONT));\n\nplot_time_profile(\n conc_sol, observable=\"Disequilibrium\",\n ax=ax4, legend=\"right outside\",\n time_vector=np.linspace(t0, 1, int(1e5)), plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n xlim=(1e-6, 1), ylim=(-.0001, 0.0015),\n title=(\"(d) Disequilibrium\", XL_FONT));\nfig_8_8.tight_layout()\n```\n\n**Figure 8.8:** Dynamic responses for Eqs (8.4 - 8.8). (a) The phase portrait for the rates of use and formation of ATP. (b) The concentrations of ATP, ADP, and AMP. (c) Net ATP use (d) The disequilibrium variable for Adenylate kinase.\n\n#### Pooling and interpretation: trafficking high-energy phosphate bonds\nSince AMP is not being synthesized and degraded, the sum of $\\text{ATP} + \\text{ADP} +\\text{AMP}$, or the capacity to carry high-energy phosphate bonds, is a constant. The Atkinson's energy charge \n\n$$\\begin{equation} \\text{E.C.} = \\frac{2\\ \\text{ATP} + \\text{ADP}}{2\\ \\text{ATP}+\\text{ADP}+\\text{AMP}} = \\frac{\\text{occupancy}}{\\text{capacity}} \\tag{8.9} \\end{equation}$$\n\nshows a monotonic decay to a lower state in response to the increased load (see Figure 8.9). \n\n\n```python\npools.update({\"EC\": \"(2*atp + adp) / (2*(atp + adp + amp))\"})\n# Determine pools\nfor pool_id, equation_str in pools.items():\n conc_sol.make_aggregate_solution(\n pool_id, equation=equation_str, update=True)\n```\n\n\n```python\nfig_8_9, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 4))\n(ax1, ax2) = axes.flatten()\n\nplot_time_profile(\n conc_sol, observable=[\"EC\"], ax=ax1, legend=\"best\",\n plot_function=\"semilogx\", ylim= (.7, 1),\n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(a) Energy Charge\", XL_FONT));\n\nplot_time_profile(\n conc_sol, observable=[\"Occupancy\", \"Vacancy\"], ax=ax2, \n legend=\"right outside\", plot_function=\"semilogx\",\n ylim=(0., 4.), xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(b) Charge Pools\", XL_FONT));\nfig_8_9.tight_layout()\n```\n\n**Figure 8.9:** (a) The Atkinson's energy charge (Eq. 8.9). (b) The occupancy and vacancy pools move in the opposite directions. Increasing the load drops the occupancy pool and increases the vacancy pool as the system becomes discharged. Reduced loads have the opposite reaction.\n\n\n\n**Figure 8.10:** Graphical representation of the energy charge (x-direction) versus the capacity (y-direction). The drop in the charge is indicated by the arrow. The capacity is a constant in this case.\n\n### Buffering the energy charge \n#### Reaction mechanism: E.C. buffering\nIn many situations, there is a buffering effect on the energy charge by a coupled carrier of high energy bonds. This exchange is: \n\n$$\\begin{equation} \\text{ATP}\\ + \\text{B} \\leftrightharpoons \\text{ADP}\\ + \\text{BP} \\tag{8.10} \\end{equation}$$\n\nwhere the buffering molecule, $\\text{B}$, picks up the high-energy phosphate group through a fast equilibrating reaction. \n\n\n\n**Figure 8.11:** The trafficking of high-energy phosphate bonds with the buffer molecule exchange reaction.\n\n\n```python\n# Copy the model to create a new, yet identical model instance \nphos_buffered = phos_traffic.copy()\nphos_buffered.id += \"_Buffered\"\n\n# Create the buffer metabolites\nb = MassMetabolite(\"b\")\nbp = MassMetabolite(\"bp\")\n\n# Create the buffer reaction and add the metaolites\nv_buff = MassReaction(\"buff\")\nv_buff.add_metabolites({atp:-1, b:-1, adp:1, bp:1})\n\n# Update model\nphos_buffered.add_reactions(v_buff)\n```\n\nThe rate equation of the buffering reaction is:\n\n\n```python\nprint(strip_time(phos_buffered.rates[v_buff]))\n```\n\n kf_buff*(atp*b - adp*bp/Keq_buff)\n\n\n#### Examples of buffer molecules \nIn Eq. (8.10), $\\text{B}$ represents a phosphagen, which is a compound containing a high-energy phosphate bond that is used as energy storage to buffer the ATP/ADP ratio. The most well-known phosphagen is creatine, which is found in the muscles of mammals. Marine organisms have other phosphagens (arginine, taurocyamine, glycocyamine), while earthworms use lombricine (Nguyen, 1960). \n\n#### Buffering: \nWhen the reaction in Eq. 8.10 is at equilibrium we have \n\n$$\\begin{equation} k_{\\mathrm{buff}}^\\rightarrow\\text{ATP}*\\text{B} = k_{\\mathrm{buff}}^\\leftarrow \\text{ADP}*\\text{BP} \\tag{8.11} \\end{equation}$$\n\nThis equation can be rearranged as \n\n$$\\begin{equation} 4 K_{\\mathrm{buff}} = \\text{BP}/\\text{B} \\tag{8.12} \\end{equation}$$\n\nwhere $\\text{ATP}/\\text{ADP}=1.6/0.4=4$ in the steady state, and $K_{\\mathrm{buff}} = k_{\\mathrm{buff}}/k_{-buff}$. If the buffering molecule is present in a constant amount, then \n\n$$\\begin{equation} \\text{B}_{\\mathrm{tot}} = \\text{B} + \\text{BP} \\tag{8.13} \\end{equation}$$\n\nWe can rearrange equations (8.12) and (8.13) as:\n\n$$\\begin{equation} \\frac{\\text{BP}}{\\text{B}_{\\mathrm{tot}}} = \\frac{4 K_{\\mathrm{buff}}}{4 K_{\\mathrm{buff}} + 1} \\tag{8.14} \\end{equation}$$\n\nIn this equation, $\\text{B}_{\\mathrm{tot}}$ is the capacity of the buffer to carry the high energy phosphate bond whereas $\\text{BP}/\\text{B}_{\\mathrm{tot}}$ is the energy charge of the buffer. \n\nWe note that the value of $K_{\\mathrm{buff}}$ is a key variable. If $K_{\\mathrm{buff}} = 1/4$ then the buffer is half charged at equilibrium, whereas if $K_{\\mathrm{buff}}=1$ then the buffer is 80% charged. Thus, this numerical value (a thermodynamic quantity) is key and will specify the relative charge on the buffer and the adenosine phosphates. The effect of $K_{\\mathrm{buff}}$ can be determined through simulation. \n\n#### Updating the model with the buffering reaction\nIt is assumed that the buffering reaction is at equilibrium and that the amount of buffering molecules is constant:\n\n\n```python\n# Use sympy to set up a symbolic equation for the buffer equilibrium\nbuff_equilibrium = sym.Eq(\n sym.S.Zero, strip_time(phos_buffered.rates[v_buff]))\n\n# Set amount of buffer molecules\nbtot = 10\n\n# Use sympy to set up a symbolic equation for the buffer pool\nb_sym = sym.Symbol(b.id)\nbp_sym = sym.Symbol(bp.id)\nbuff_pool = sym.Eq(b_sym + bp_sym, btot)\n\n# Pretty print the equations\nsym.pprint(buff_equilibrium)\nsym.pprint(buff_pool)\n```\n\n ⎛ adp⋅bp ⎞\n 0 = kf_buff⋅⎜atp⋅b - ────────⎟\n ⎝ Keq_buff⎠\n b + bp = 10\n\n\nSolve the equilibrium system:\n\n\n```python\n# Obtain a dict of ic values for substitution into the sympy expressions\nic_dict = {sym.Symbol(met.id): ic \n for met, ic in phos_buffered.initial_conditions.items()}\n# Substitute known concentrations\nbuff_equilibrium = buff_equilibrium.subs(ic_dict)\n\n# Obtain solutions for B and BP\nbuff_sol = sym.solve([buff_equilibrium, buff_pool], [b_sym, bp_sym])\n# Pretty print the equation\nprint(buff_sol)\n```\n\n {b: 10.0/(4.0*Keq_buff + 1.0), bp: 40.0*Keq_buff/(4.0*Keq_buff + 1.0)}\n\n\nSet $K_{\\mathrm{buff}}$ and $k_{\\mathrm{buff}}^\\rightarrow$:\n\n\n```python\nv_buff.kf = 1000\nv_buff.Keq = 1\n\n# Obtain a dict of parameter values for substitution into the sympy expressions\nparam_dict = {\n sym.Symbol(parameter): value \n for parameter, value in v_buff.parameters.items()}\n\nbuffer_ics = {\n phos_buffered.metabolites.get_by_id(str(met)): float(expr.subs(param_dict))\n for met, expr in buff_sol.items()}\n\n# Update initial conditions with buffer molecule concentrations\nphos_buffered.update_initial_conditions(buffer_ics)\nfor met, ic in phos_buffered.initial_conditions.items():\n print(\"{0}: {1} mM\".format(met, ic))\n```\n\n adp: 0.4 mM\n amp: 0.1 mM\n atp: 1.6 mM\n b: 2.0 mM\n bp: 8.0 mM\n\n\n#### Null spaces: E.C. buffering\nWith the addition of the buffer, stoichiometric matrix four columns.\n\n\n```python\nphos_buffered.S\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
distruseformbuff
adp-21-11
amp1000
atp1-11-1
b000-1
bp0001
\n
\n\n\n\nIt has still has a one-dimensional null space, that represents and internal loop as the use and formation reactions are the exact opposites of each other. \n\n\n```python\n# Obtain nullspace\nns = nullspace(phos_buffered.S, rtol=1e-1)\n# Transpose and iterate through nullspace, \n# dividing by the smallest value in each row.\nns = ns.T\nfor i, row in enumerate(ns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the nullspace is composed of only integers\n ns[i] = np.array([round(value) for value in new_row])\n\n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(ns):\n ns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Revert transpose\nns = ns.T\n# Create a pandas.DataFrame to represent the nullspace\npd.DataFrame(ns, index=[rxn.id for rxn in phos_buffered.reactions],\n columns=[\"Path 1\"], dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Path 1
distr0
use1
form1
buff0
\n
\n\n\n\nThe left null space is two-dimensional. It represents conservation of the nucleotide and the buffer molecule. Neither AxP or B is produced or destroyed in the model;\n\n\n```python\n# Obtain left nullspace\nlns = left_nullspace(phos_buffered.S, rtol=1e-1)\n# Iterate through left nullspace, \n# dividing by the smallest value in each row. \nfor i, row in enumerate(lns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the left nullspace is composed of only integers\n lns[i] = np.array([round(value) for value in new_row])\n\n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(lns):\n lns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Create a pandas.DataFrame to represent the left nullspace\npd.DataFrame(lns, index=[\"Total AxP\", \"Total B\"], \n columns=phos_buffered.metabolites, dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
adpampatpbbp
Total AxP11100
Total B00011
\n
\n\n\n\n#### Dynamic simulation: E.C. buffering\nThe model is initially in steady state.\n\n\n```python\nt0, tf = (0, 1e3)\nsim = Simulation(phos_buffered, verbose=True)\nconc_sol, flux_sol = sim.simulate(phos_buffered, time=(t0, tf), verbose=True)\n```\n\n \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n Successfully loaded MassModel 'Phosphate_Trafficking_Buffered' into RoadRunner.\n Getting time points\n Setting output selections\n Setting simulation values for 'Phosphate_Trafficking_Buffered'\n Simulating 'Phosphate_Trafficking_Buffered'\n Simulation for 'Phosphate_Trafficking_Buffered' successful\n Adding 'Phosphate_Trafficking_Buffered' simulation solutions to output\n Updating stored solutions\n\n\n\n```python\nfig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 4),\n )\n(ax1, ax2) = axes.flatten()\n\nplot_time_profile(\n conc_sol, ax=ax1, legend=\"right outside\", \n plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Concentrations [mM]\", \n title=(\"Concentration Profile\", XL_FONT));\n\nplot_time_profile(\n flux_sol, ax=ax2, legend=\"right outside\",\n plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Fluxes [mM/min]\", \n title=(\"Flux Profile\", XL_FONT));\nfig.tight_layout()\n```\n\nWe can compare the flux dynamics of the buffered vs. unbuffered system. The buffered system has a much longer response time. Once again, we consider a simulation where we increase the ATP use rate by a 'multiplier' in this figure:\n\n\n```python\nfig_8_12, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 4),\n )\n\nbuff_strs = [\"unbuffered\", \"buffered\"]\nlinestyles = [\"--\", \"-\"]\n\nt0, tf = (0, 1e3)\n# Simulate both models with the disturbance\nfor i, model in enumerate([phos_traffic, phos_buffered]):\n sim = Simulation(model)\n conc_sol, flux_sol = sim.simulate(\n model, time=(t0, tf),\n perturbations={\"kf_use\": \"kf_use * 1.5\"})\n\n plot_time_profile(\n flux_sol, observable=[\"use\", \"form\"], ax=ax, \n legend=([\"use \" + buff_strs[i], \"form \" + buff_strs[i]],\n \"right outside\"),\n plot_function=\"semilogx\",\n xlabel=\"Time [min]\", ylabel=\"Fluxes [mM/min]\", \n color=[\"red\", \"blue\"], linestyle=linestyles[i])\nfig_8_12.tight_layout()\n```\n\n**Figure 8.12:** The fluxes of ATP use and formation respond more slowly when the ATP buffer is present.\n\nThe response of the adenosine phosphate system can be simulated in the presence of a buffer. We choose the parameters as $\\text{B}_{\\mathrm{tot}}=10\\ mM$, $K_{\\mathrm{buff}}=1$, and $k_{\\mathrm{buff}}=1000/min$ and all other conditions as in Figure 8.8. The results of the simulation are shown in Figure 8.13. The time response of the energy charge is shown, along with the buffer charge $\\text{BP}/\\text{B}_{\\mathrm{tot}}$. We see that the fast response in the energy charge is now slower as the initial reaction is buffered by release of the high energy bonds that are bound to the buffer. The overall change in the energy charge is the same: it goes from 0.86 to 0.78. The charge of the buffer drops from 0.80 to 0.73 at the same time. \n\n\n\n**Figure 8.13:** Pictorial representation of the phosphate exchange among the adenosine phosphates and a buffering molecule. (a) The reaction schema. (b) A pictorial representation of the molecules, their charged states, and the definition of pooled variables*\n\n#### Pooling and interpretation: E.C. buffering\n\nA pictorial representation of the phosphate buffering is given in Figure 8.13. Here, a generalized definition of the overall phosphate charge is: \n\n$$\\begin{equation} \\text{overall charge} = \\frac{\\text{overall occupancy}}{\\text{overall capacity}} = \\frac{2\\ \\text{ATP}+\\text{ADP}+\\text{BP}}{2\\ (\\text{ATP}+\\text{ADP}+\\text{AMP})+\\text{BP} + \\text{B}} \\tag{8.15} \\end{equation}$$\n\nThis combined charge system can be represented similarly to the representation in Figure 8.10. Figure 8.14 shows a stacking of the buffer and adenosine phosphate capacity versus their charge. The total capacity to carry high-energy bonds is now 14.2 mM. The overall charge is 0.82 (or 11.64 mM concentration of high-energy bonds) in the system before the perturbation. The increased load brings the overall charge down to 0.74. \n\n\n\n**Figure 8.14:** The representation of the energy and buffer charge versus the capacity (in mM on y-axis). The lumping of the two quantities into ‘overall’ quantities is illustrated. The case considered corresponds to the simulation in Figure 8.15.\n\nTo understand this effect, we first define more pools:\n\n\n```python\npools.update({\n \"BC\": \"bp / (bp + b)\",\n \"Overall_Charge\": \"(2*atp + adp + bp) / (2*(atp + adp + amp) + bp + b)\"})\n```\n\nand then plot the dynamic responses of the pools:\n\n\n```python\nfig_8_15, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 6),)\n(ax1, ax2) = axes.flatten()\nlegend_labels = [\"E.C. Unbuffered\", \"E.C. Buffered\"]\nfor i, model in enumerate([phos_traffic, phos_buffered]):\n sim = Simulation(model)\n conc_sol, flux_sol = sim.simulate(\n model, time=(t0, tf),\n perturbations={\"kf_use\": \"kf_use * 1.5\"})\n\n # Determine pools\n for pool_id, equation_str in pools.items():\n # Skip buffered charge for model with no buffer\n if i == 0 and pool_id in [\"BC\", \"Overall_Charge\"]:\n continue\n conc_sol.make_aggregate_solution(\n pool_id, equation=equation_str, update=True)\n\n if i == 1:\n # Plot the charge pools for the buffered solution\n plot_time_profile(\n conc_sol, observable=[\"EC\", \"BC\", \"Overall_Charge\"], ax=ax1,\n legend=([\"E.C.\", \"B.C.\", \"Overall Charge\"], \"right outside\"),\n xlabel=\"Time [min]\", ylabel=\"Charge\", \n xlim=(t0, 1), ylim=(.7, .9),\n title=(\"(a) Charge Pools of Buffered Model\", XL_FONT));\n\n # Compare the buffered and unbuffered solutions\n plot_time_profile(\n conc_sol, observable=[\"EC\"], ax=ax2,\n legend=(legend_labels[i], \"right outside\"),\n xlabel=\"Time [min]\", ylabel=\"Charge\", \n xlim=(t0, 1), ylim=(.7, .9),\n title=(\"(b) E.C. Unbuffered Vs Buffered\", XL_FONT));\nfig_8_15.tight_layout()\n```\n\n**Figure 8.15:** Dynamic responses for Eqs.(8.4 - 8.8) with the buffering effect (Eq. (8.10)). (a) The Atkinson's energy charge (Eq. (8.9)) the buffer charge (Eq. (8.14)), and the overall charge (Eq. (8.15) are shown as a function of time. (b) Comparison of the buffered and unbuffered energy charge. $B_{\\mathrm{tot}}=10 mM$, $K_{\\mathrm{buff}}=1$ and $k_{\\mathrm{buff}}=1000$. All other conditions are as in Figure 8.8; i.e., we simulate the response to a 'multiplier' increase in $k_{\\mathrm{use}}$. Note the slower response of the E.C. in panel (b) when the system is buffered.\n\n### Open system: long term adjustment of the capacity \n#### Inputs and outputs: \nAlthough the rates of formation and degradation of AMP are low, their effects can be significant. These fluxes will determine the total amount of the adenosine phosphates and thus their capacity to carry high energy bonds. The additional elementary rate laws needed to account for the rate of AMP formation and drain are: \n\n$$\\begin{equation} v_{\\mathrm{form,\\ AMP}} = b_{1}, \\ v_{\\mathrm{drain}} = k_{\\mathrm{drain}} * \\text{AMP} \\tag{8.16} \\end{equation}$$\n\nwhere $b_1$ is the net synthesis rate of AMP. The numerical values used are $b_{1}=0.03\\ mM/min$ and $k_{\\mathrm{drain}} = (0.03\\ mM/min)/(0.1\\ mM) = 0.3\\ mM/min$. \n\n#### Updating the model for long term capacity adjustment\nDefine the AMP exchange reaction:\n\n\n\n**Figure 8.16:** The trafficking of high-energy phosphate bonds with the buffer molecule and AMP exchange reactions.\n\n\n```python\n# Copy the model to create a new, yet identical model instance \nphos_open = phos_buffered.copy()\nphos_open.id += \"_Open\"\n\n# Get MassMetabolite amp assoicated with the new copied model\namp = phos_open.metabolites.amp\n\n# Define AMP formation\nb1 = MassReaction(\"b1\", reversible=False)\nb1.add_metabolites({amp:1})\nb1.kf = 0.03\n\n# Define AMP drain\ndrain = MassReaction(\"drain\", reversible=False)\ndrain.add_metabolites({amp:-1})\ndrain.kf = 0.3\n# Add reactions to the model\nphos_open.add_reactions([b1, drain])\n# Set custom rate for formation of AMP\nphos_open.add_custom_rate(b1, custom_rate=b1.kf_str)\n\n# Display the net rate for AMP synthesis and draining\nrate = strip_time(phos_open.rates[b1] - phos_open.rates[drain])\nprint(rate)\n# Substitute values to check if steady state\nprint(rate.subs({\n sym.Symbol('amp'): amp.ic, # AMP concentration at steady state\n sym.Symbol('kf_drain'): drain.kf, # forward rate constant for drain reaction\n sym.Symbol('kf_b1'): b1.kf})) # Synthesis rate\n```\n\n -amp*kf_drain + kf_b1\n 0\n\n\nWith the specified parameters and initial conditions, the system is in a steady state, i.e. no net exchange of AMP.\n\n#### Null spaces: long term capacity adjustment\nWith the addition of the AMP exchanges, stoichiometric matrix six columns. \n\n\n```python\nphos_open.S\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
distruseformbuffb1drain
adp-21-1100
amp10001-1
atp1-11-100
b000-100
bp000100
\n
\n\n\n\nIt has still has a two-dimensional null space, that 1) represents and internal loop as the use and formation reactions are the exact opposites of each other, as before, and 2) an exchange pathways of AMP coming into the system and leaving the system. \n\n\n```python\n# Obtain nullspace\nns = nullspace(phos_open.S, rtol=1e-1)\n# Transpose and iterate through nullspace, \n# dividing by the smallest value in each row.\nns = ns.T\nfor i, row in enumerate(ns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the nullspace is composed of only integers\n ns[i] = np.array([round(value) for value in new_row])\n\n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(ns):\n ns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Revert transpose\nns = ns.T\n# Create a pandas.DataFrame to represent the nullspace\npd.DataFrame(ns, index=[r.id for r in phos_open.reactions],\n columns=[\"Path 1\", \"Path 2\"], dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Path 1Path 2
distr00
use10
form10
buff00
b101
drain01
\n
\n\n\n\nThe left null space becomes one-dimensional. The total amount of A is no longer conserved as AMP can now enter or leave the system, i.e. pathway 2) can have a net flux. The buffer molecule, B, on the other hand is always contained within the system\n\n\n```python\n# Obtain left nullspace\nlns = left_nullspace(phos_open.S, rtol=1e-1)\n# Iterate through left nullspace, \n# dividing by the smallest value in each row. \nfor i, row in enumerate(lns):\n minval = np.min(abs(row[np.nonzero(row)]))\n new_row = np.array(row/minval)\n # Round to ensure the left nullspace is composed of only integers\n lns[i] = np.array([round(value) for value in new_row])\n\n# Ensure positive stoichiometric coefficients if all are negative\nfor i, space in enumerate(lns):\n lns[i] = np.negative(space) if all([num <= 0 for num in space]) else space\n\n# Create a pandas.DataFrame to represent the left nullspace\npd.DataFrame(lns, index=[\"Total B\"], \n columns=phos_open.metabolites, dtype=np.int64)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
adpampatpbbp
Total B00011
\n
\n\n\n\n#### Dynamic simulations: long term capacity adjustment\nInitially, the open system is in a steady-state. Once again, we consider a simulation where we increase the ATP use rate by a 'multiplier'. This system has a bi-phasic response for the values of the kinetic constants. We can start the system in a steady state at $t=0^-$ and simulate the response for increasing the ATP load by shifting the value of $k_{\\mathrm{use}}^\\rightarrow$ by a 'multiplier' at $t=0$, as before. The initial rapid response is similar to what is shown in Figure 8.8a, where the concentration of ATP drops in response to the load and the concentrations of ADP and AMP rise. This initial response is followed by a much slower response where all three concentrations drop. \n\n\n```python\nt0, tf = (0, 1e3)\nsim = Simulation(phos_open, verbose=True)\nsim.find_steady_state(models=phos_open, strategy=\"simulate\")\nconc_sol, flux_sol = sim.simulate(\n phos_open, time=(t0, tf), \n perturbations={\"kf_use\": \"kf_use * 1.5\"})\npools.update({\"Capacity\": \"2*(atp + adp + amp)\"})\n# Determine pools\nfor pool_id, equation_str in pools.items():\n # Skip buffered charge for model with no buffer\n conc_sol.make_aggregate_solution(\n pool_id, equation=equation_str, update=True)\n```\n\n \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n\n\n Successfully loaded MassModel 'Phosphate_Trafficking_Buffered_Open' into RoadRunner.\n\n\n\n```python\nfig, axes = plt.subplots(nrows=2, ncols=1, figsize=(8, 6),\n )\n(ax1, ax2) = axes.flatten()\nplot_time_profile(\n conc_sol, ax=ax1, observable=phos_open.metabolites,\n legend=\"right outside\",\n plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Concentrations [mM]\", \n title=(\"Concentration Profile\", XL_FONT));\n\nplot_time_profile(\n flux_sol, ax=ax2, observable=phos_open.reactions,\n legend=\"right outside\",\n plot_function=\"semilogx\", \n xlabel=\"Time [min]\", ylabel=\"Fluxes [mM/min]\", \n title=(\"Flux Profile\", XL_FONT));\nfig.tight_layout()\n```\n\n#### Interpretation of the bi-phasic response\n\nThis bi-phasic response can be examined further by looking at dynamic phase portraits of key fluxes (Figure 8.17) and key pools (Figure 8.18). \n\n\n```python\nfig_8_17, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))\n(ax1, ax2) = axes.flatten()\n\nlabel = \"{0} [mM/min]\"\nplot_phase_portrait(\n flux_sol, x=\"use\", y=\"form\", ax=ax1,\n xlim=(4, 21), ylim=(4, 21), \n xlabel=label.format(\"use\"), ylabel=label.format(\"form\"), \n title=(\"(a) Phase Portrait of ATP use vs. formation\", XL_FONT),\n annotate_time_points=[0, 1e-1, 1e0, 25, 150],\n annotate_time_points_color=[\"red\"],\n annotate_time_points_labels=True);\n\n# Annotate plot\nline_data = [i for i in range(0, 22)]\nax1.plot(line_data, line_data, ls=\"--\", color=\"black\");\nax1.annotate(\"use < form\", xy=(6, 15));\nax1.annotate(\"use > form\", xy=(15, 6));\nax1.annotate(\"Steady-state line:\\n use=form\", xy=(15, 19));\nax1.annotate(\"initial perturbation\", xy=(9.5, 9), xycoords=\"data\");\nax1.annotate(\"\", xy=(flux_sol[\"use\"][0], flux_sol[\"form\"][0]),\n xytext=(10, 10), textcoords=\"data\",\n arrowprops=dict(arrowstyle=\"->\",connectionstyle=\"arc3\"));\n\nplot_phase_portrait(\n flux_sol, x=\"use\", y=\"drain\", ax=ax2,\n xlim=(0, 21), ylim=(0, 0.1), \n xlabel=label.format(\"use\"), ylabel=label.format(\"drain\"),\n title=(\"(b) Phase Portrait of use vs. drain\", XL_FONT),\n annotate_time_points=[0, 1e-1, 1e0, 25, 150],\n annotate_time_points_color=[\"red\"],\n annotate_time_points_labels=True);\n\n# Annotate plot\nax2.plot(line_data, [0.03]*22, ls=\"--\", color=\"black\");\nax2.annotate(\"net AMP\\ngain\", xy=(1.5, 0.02));\nax2.annotate(\"net AMP\\ndrain\", xy=(1.5, 0.04));\nfig_8_17.tight_layout()\n```\n\n**Figure 8.17:** Dynamic phase portraits of fluxes for the simulation of the adenosine phosphate system with formation and drain of AMP (Eq. (8.16)). (a) the ATP use $(v_{\\mathrm{use}})$ versus the ATP formation rate $(v_{\\mathrm{form}})$. (b) the ATP use $(v_{\\mathrm{use}})$ versus the AMP drain $(v_{\\mathrm{drain}})$.\n\n\n```python\nfig_8_18 = plt.figure(figsize=(12, 4))\ngs = fig_8_18.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_8_18.add_subplot(gs[0, 0])\nax2 = fig_8_18.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n conc_sol, x=\"Occupancy\", y=\"Capacity\", ax=ax1,\n time_vector=np.linspace(t0, 10, int(1e6)),\n xlim=(2.7, 4.3), ylim=(2.7, 4.3),\n xlabel=\"Occupancy\", ylabel=\"Capacity\",\n title=(\"(a) Occupancy vs. Capacity\", XL_FONT),\n annotate_time_points=\"endpoints\",\n annotate_time_points_labels=True);\n\nplot_time_profile(\n conc_sol, observable=[\"EC\", \"BC\", \"Overall_Charge\"], ax=ax2,\n legend=([\"E.C.\", \"B.C.\", \"Overall Charge\"], \"right outside\"),\n time_vector=np.linspace(t0, 10, int(1e6)),\n xlabel=\"Time [min]\", ylabel=\"Charge\",\n xlim=(t0, 10), ylim=(0.65, 1),\n title=(\"(b) Charge Responses\", XL_FONT));\nfig_8_18.tight_layout()\n```\n\n**Figure 8.18:** The Energy Charge response. (a) Dynamic phase portrait of 2ATP+ADP versus 2(ATP+ADP+AMP). (b) The response of E.C., B.C., and overall charge.\n\n* First, we examine how the system balances the use of ATP $(v_{\\mathrm{use}})$ with its rate of formation $(v_{\\mathrm{form}})$, see Figure 8.17. At $t=0$ the system is at rest at $v_{\\mathrm{use}}=v_{\\mathrm{form}}=10.0\\ mM/min$. Then the system is perturbed by moving the ATP drain, $v_{\\mathrm{use}}$, to 15.0 mM/min, as before. The initial response is to increase the formation rate of ATP to about 13 mM/min with the simultaneous drop in the use rate to about the same number, due to a net drop in the concentration of ATP during this period. The rate of ATP use and formation is approximately the same at this point in time. Then, during the slower response time, the use and formation rates of ATP are similar and the system moves along the 45 degree line to a new steady state point at 6.67 mM/min. \n\n\n* The slow dynamics are associated with the inventory of the adenosine phosphates (ATP + ADP + AMP). The AMP drain can be graphed versus the ATP use, see Figure 8.17b. Initially, the AMP drain increases rapidly as the increased ATP use leads to ADP buildup that gets converted into AMP by adenylate kinase $(v_{\\mathrm{distr}})$. The AMP drain then drops and sets at the same rate to balance the formation rate, set at 0.03 mM/min. \n\n\n* We can graph the occupancy against the capacity (Figure 8.18a). During the initial response, the occupancy moves while the capacity is a constant. Then, during the slower phase, the two move at a constant ratio. This gives a bi-phasic response of the energy charge (Figure 8.18b). In about a minute, the energy charge changes from 0.86 to about 0.77 and then stays a constant. The energy charge is roughly a constant even though all the other concentrations are changing. \n\n\nThis feature of keeping the energy charge a constant while the capacity is changing has a role in a variety of physiological responses, from blood storage to the ischemic response in the heart. Note that this property is a stoichiometric one; no regulation is required to produce this effect. \n\n## Charging Substrates and Recovery of High-Energy Bonds\n### Reaction mechanism: \nAs discussed in Section 8.2, most catabolic pathways generate energy (and other metabolic resources) in the form of activated (or charged) carrier molecules. Before energy can be extracted from a compound, it is typically activated by the use of metabolic resources (a biological equivalent of \"it takes money to make money\"). This basic structure shown in Figure 2.5 is redrawn in Figure 8.19a where one ATP molecule is used to 'charge' a substrate $(x_1)$ with one high-energy bond to form an intermediate $(x_2)$. This intermediate is then degraded through a process wherein two ATP molecules are synthesized and an inorganic phosphate is incorporated. The net gain of ATP is 1 for every $(x_2)$ metabolized, and this ATP molecule can then be used to drive a process $v_{\\mathrm{load}}$ that uses an ATP molecule. The trafficking of high-energy phosphate bonds is shown pictorially in Figure 8.19b. \n\n\n\n**Figure 8.19:** Coupling of the adenosine phosphates with a skeleton metabolic pathway. (a) The reaction map. (b) A pictorial view of the molecules emphasizing the exchange of the high-energy phosphate group (solid circle). The blue square is AMP. The rate laws used are: $b_1 = 0.03\\ mM/min.$; $b_2 = 5\\ mM/min.$; $k_{\\mathrm{drain}}=b_1/0.1$; $k_{\\mathrm{load}}=5/1.6$; $k_1=5/0.4$. The flux of $b_2$ was set to 5 mM/min, as the ATP production rate is double that number, thus the steady state value for ATP production is 10 mM/min, to match what is discussed in section 8.3.\n\n\n```python\n# Create model\nphos_recovery = MassModel(\"Phosphate_Recovery\", array_type=\"dense\",\n dtype=np.int64)\n# Define metabolites\natp = MassMetabolite(\"atp\")\nadp = MassMetabolite(\"adp\")\namp = MassMetabolite(\"amp\")\npi = MassMetabolite(\"pi\")\nx1 = MassMetabolite(\"x1\")\nx2 = MassMetabolite(\"x2\")\nx3 = MassMetabolite(\"x3\")\n# Define reactions\nb1 = MassReaction(\"b1\", reversible=False)\nb1.add_metabolites({amp:1})\n\ndistr = MassReaction(\"distr\")\ndistr.add_metabolites({adp: -2, amp: 1, atp:1})\n\nload = MassReaction(\"load\", reversible=False)\nload.add_metabolites({atp: -1, adp: 1, pi: 1})\n\ndrain = MassReaction(\"drain\", reversible=False)\ndrain.add_metabolites({amp:-1})\n\nb2 = MassReaction(\"b2\", reversible=False)\nb2.add_metabolites({x1: 1})\n\nv1 = MassReaction(\"v1\", reversible=False)\nv1.add_metabolites({atp: -1, x1: -1, adp: 1, x2: 1})\n\nv2 = MassReaction(\"v2\", reversible=False)\nv2.add_metabolites({adp: -2, pi: -1, x2: -1, atp: 2, x3: 1})\n\nDM_x3 = MassReaction(\"DM_x3\", reversible=False)\nDM_x3.add_metabolites({x3: -1})\n\n# Add reactions to model\nphos_recovery.add_reactions([b1, distr, load, drain, b2, v1, v2, DM_x3])\n\n# Define initial conditions and parameters\natp.ic = 1.6\nadp.ic = 0.4\namp.ic = 0.1\npi.ic = 2.5\nx1.ic = 1\nx2.ic = 1\nx3.ic = 1\n\nb1.kf = 0.03\ndistr.kf = 1000\ndistr.Keq = 1\nload.kf = 5/1.6\ndrain.kf = 0.3\nb2.kf = 5\nv1.kf = 5/1.6\nv2.kf = 5/0.4\nDM_x3.kf = 5\n\n# Set custom rate for source reactions \nphos_recovery.add_custom_rate(b1, custom_rate=b1.kf_str)\nphos_recovery.add_custom_rate(b2, custom_rate=b2.kf_str)\n```\n\n#### The dynamic mass balances: \nThe dynamic mass balance equations that describe this process are: \n\n$$\\begin{align} \\frac{dx_1}{dt} &= b_2 - v_1 &\\tag{8.17a} \\\\ \\frac{dx_2}{dt} &= v_1 - v_2 &\\tag{8.17b} \\\\ \\frac{d\\text{ATP}}{dt} &= -(v_1 + v_{\\mathrm{load}}) + 2v_2 + v_{\\mathrm{distr}} &\\tag{8.17c} \\\\ \\frac{d\\text{ADP}}{dt} &= (v_1 + v_{\\mathrm{load}}) - 2v_2 - 2v_{\\mathrm{distr}} &\\tag{8.17d} \\\\ \\frac{d\\text{AMP}}{dt} &= b_1 - v_{\\mathrm{drain}} + v_{\\mathrm{distr}} &\\tag{8.17e} \\\\ \\end{align}$$\n\nTo integrate the reaction schema in Figure 8.13a with this skeleton pathway, we have replaced the use rate of ATP $(v_{\\mathrm{use}})$ with $v_1 + v_{\\mathrm{load}}$ and the formation rate of ATP $(v_{\\mathrm{form}})$ with $2v_2$. \n\n#### Dynamic simulation: \nThe flow of substrate into the cell, given by $b_2$, will be set to 5 mM/min in the simulation to follow to set the gross ATP production at 10 mM/min. The response of this system can be simulated to a change in the ATP load parameter, as in previous examples. The difference from the previous examples here is that the net ATP production rate is 5 mM/min. \n\nThe time response of the concentrations and fluxes are shown in Figure 8.20, the flux phase portraits in Figure 8.21, and the pools and ratios in Figure 8.22.\n\n\n```python\nt0, tf = (0, 100)\nsim = Simulation(phos_recovery, verbose=True)\nsim.find_steady_state(models=phos_recovery, strategy=\"simulate\",\n update_values=True)\nconc_sol, flux_sol = sim.simulate(\n phos_recovery, time=(t0, tf, tf*1000 + 1), \n perturbations={\"kf_load\": \"kf_load * 1.5\"},\n interpolate=True)\n\npools = {\"Occupancy\": \"adp + 2*atp\", \n \"Capacity\": \"2*(atp + adp + amp)\",\n \"EC\": \"(2*atp + adp) / (2*(atp + adp + amp))\"}\n\nfor pool_id, equation_str in pools.items():\n conc_sol.make_aggregate_solution(\n pool_id, equation=equation_str, update=True)\n\nnetfluxes = {\n \"load_total\": \"v1 + load\", \n \"generation\": \"2*v2\", \n \"drain_total\": \"drain\"}\nfor flux_id, equation_str in netfluxes.items():\n # Skip buffered charge for model with no buffer\n flux_sol.make_aggregate_solution(\n flux_id, equation=equation_str, update=True)\n```\n\n \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n \u001b[93mWARNING:\u001b[0m \u001b[93mNo compartments found in model. Therefore creating compartment 'compartment' for entire model.\u001b[0m\n \u001b[91mERROR:\u001b[0m \u001b[91mSomething unexpected occurred and the model could not be loaded into the current RoadRunner instance. Therefore initializing a new RoadRunner instance for the Simulation.\u001b[0m\n\n\n Successfully loaded MassModel 'Phosphate_Recovery' into RoadRunner.\n\n\n\n```python\nfig_8_20, axes = plt.subplots(nrows=3, ncols=1, figsize=(8, 6))\n(ax1, ax2, ax3) = axes.flatten()\n\nplot_time_profile(\n conc_sol, observable=phos_recovery.metabolites,\n ax=ax1, legend=\"right outside\", \n xlim=(t0, 25), ylim=(0, 2.0),\n xlabel=\"Time [min]\", ylabel=\"Concentration [mM]\",\n title=(\"(a) Concentrations\", XL_FONT));\n\nplot_time_profile(\n flux_sol, observable=[\"v1\", \"v2\", \"load\"], \n ax=ax2, legend=\"right outside\", \n xlim=(t0, 25), ylim=(4, 8),\n xlabel=\"Time [min]\", ylabel=\"Fluxes [mM/min]\",\n title=(\"(b) High-Flux Reactions\", XL_FONT));\n\nplot_time_profile(\n flux_sol, observable=[\"distr\", \"drain\"], \n ax=ax3, legend=\"right outside\", \n xlim=(t0, 25), ylim=(0, .4),\n xlabel=\"Time [min]\", ylabel=\"Fluxes [mM/min]\",\n title=(\"(c) Low-Flux Reactions\", XL_FONT));\nfig_8_20.tight_layout()\n```\n\n**Figure 8.20:** The response of the systems shown in Figure 8.19 to a 50% increase in the ATP load rate constant. (a) Dynamic response of the concentrations on a fast and slow time scale. (b) Dynamic response of the main fluxes on a fast and slow time scale. (c) Dynamic response of the AMP determining fluxes on a fast and slow time scale. Parameter values are the same as in Figure 8.19.\n\n\n```python\nfig_8_21, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))\n(ax1, ax2) = axes.flatten()\n\nplot_phase_portrait(\n flux_sol, x=\"load_total\", y=\"generation\", ax=ax1, \n xlabel=\"ATP load total\", ylabel=\"ATP Synthesis\", \n xlim=(9, 13.5), ylim=(9, 13.5), \n title=(\"(a) ATP Load vs. Synthesis\", XL_FONT),\n annotate_time_points=\"endpoints\",\n annotate_time_points_labels=True);\n\n# Annotate plot\nline_data = [i for i in range(8, 15)]\nax1.plot(line_data, line_data, ls=\"--\", color=\"black\");\nax1.annotate(\n \"\", xy=(flux_sol[\"load_total\"](0), flux_sol[\"generation\"](0)),\n xytext=(10, 10), textcoords=\"data\",\n arrowprops=dict(arrowstyle=\"->\",connectionstyle=\"arc3\"));\nax1.annotate(\"initial perturbation\", xy=(\n flux_sol[\"load_total\"](0) - 1.7, \n flux_sol[\"generation\"](0) - 0.2));\n\nplot_phase_portrait(\n flux_sol, x=\"load_total\", y=\"drain_total\", ax=ax2, \n xlabel=\"ATP load total\", ylabel=\"AMP drain\", \n xlim=(8, 13.5), ylim=(0, 0.125),\n title=(\"(a) ATP Load vs. Drain\", XL_FONT),\n annotate_time_points=\"endpoints\",\n annotate_time_points_labels=True);\n\nax2.plot(line_data, [0.03] * 7, ls=\"--\", color=\"black\");\nfig_8_21.tight_layout()\n```\n\n**Figure 8.21:** The response of the system shown in Figure 8.19 to a change in the ATP load rate constant. (a) ATP load versus ATP synthesis rate. (b) ATP load versus AMP drainage rate. You can compare this response to Figure 8.17.\n\n\n```python\nfig_8_22 = plt.figure(figsize=(10, 4))\ngs = fig_8_22.add_gridspec(nrows=1, ncols=2, width_ratios=[1, 1.5])\n\nax1 = fig_8_22.add_subplot(gs[0, 0])\nax2 = fig_8_22.add_subplot(gs[0, 1])\n\nplot_phase_portrait(\n conc_sol, x=\"Occupancy\", y=\"Capacity\", ax=ax1,\n xlim=(2.3, 4.4), ylim=(2.3, 4.4),\n xlabel=\"Occupancy\", ylabel=\"Capacity\",\n title=(\"(a) Occupancy vs. Capacity\", XL_FONT),\n annotate_time_points=[t0, 1e0, 50],\n annotate_time_points_color=[\"red\"],\n annotate_time_points_labels=True);\n# Annotate plot\nax1.annotate(\" fast\\nmotion\\n\", xy=(conc_sol[\"Occupancy\"](0.3) - .25, \n conc_sol[\"Capacity\"](0.3) - .35))\n\nplot_time_profile(\n conc_sol, observable=[\"EC\"], ax=ax2, legend=\"best\",\n xlim=(t0, 50), ylim=(0.65, 1),\n xlabel=\"Time [min]\", ylabel=\"Energy Charge\",\n title=(\"(b) Stoichiometric Disturbance Rejection Property\", XL_FONT));\nfig_8_22.tight_layout()\n```\n\n**Figure 8.22:** The response of the system shown in Figure 8.19 to a change in the ATP load rate constant. (a) Dynamic phase portrait of the pools 2ATP+ADP versus 2(ATP+ADP+AMP). (b) Energy charge ratio as a function of time. You can compare this response to Figure 8.18.\n\n### Interpretation: \nWe can make the following observations from this dynamic response: \n\n* The concentrations move on two principal time scales (Figure 8.20): a fast time scale that is about three to five minutes, and a slower time scale that is about 50 min. ATP and $x_1$ move primarily on the fast time scale, whereas ADP, AMP, and $x_2$ move on the slower time scale. You can see this clearly by changing time in Figure 8.20.\n\n* Initially $v_{\\mathrm{load}}$ increases sharply, and $v_2$ increases and $v_1$ decreases to meet the increased load. The three high flux reactions $v_1$, $v_2$, and $v_{\\mathrm{load}}$ restabilize at about 5 mM/min after about a three to five minute time frame, after which they are closely, but not fully, balanced (Figure 8.20). \n\n* The dynamic phase portrait, Figure 8.21a, shows that the overall ATP use $(v_1 + v_{\\mathrm{load}})$ quickly moves to about 12.5 mM/min while the production rate $(2v_2)$ is about 10 mM/min. Following this initial response, the ATP use drops and the ATP synthesis rate increases to move towards the 45 degree line. The 45 degree line is not reached. After 0.1 min, $v_2$ starts to drop and the system moves somewhat parallel to the 45 degree line until 1.5 min have passed. At this time the ATP concentration has dropped to about 1.06 mM, which makes the ATP use and production rate approximately balanced. Following this point, both the use and production rate increase slowly and return the system back to the initial point where both have a value of 10 mM/min. Since the input rate of $x_1$ is a constant, the system has to return to the initial state. \n\n* AMP initially increases leading to a net drain of AMP from the system. This drain unfolds on a long time scale leading to a net flux through the adenylate kinase that decays on the slower time scale. The effects of AMP drainage can be seen in the flux phase portrait in Figure 8.21b. Initially the AMP drain increases as the ATP usage drops close to its eventual steady state. Then the vertical motion in the phase portrait shows that there is a slower motion in which the ATP usage does not change much but the AMP drainage rate drops to match its input rate at 0.03 mM/hr. \n\n* The dynamic response of the energy charge (Figure 8.22b) shows that it drops on the faster time scale from an initial value of 0.86 to reach a minimum of about 0.67 at about 1.5 min. This initial response results from the increase in the ATP load parameter of 50%. After this initial response, the energy charge increases on the slower time scale to an eventual value of about 0.82. \n\n* Notice that this secondary response is not a result of a regulatory mechanism, but is a property that is built into the stoichiometric structure and the values of the rate constants that lead to the time scale separation. \n\n## Summary \n\n* Most biochemical reactions are bilinear. Six of the seven categories of enzymes catalyze bilinear reactions. \n\n* The bilinear properties of biochemical reactions lead to complex patterns of exchange of key chemical moieties and properties. Many such simultaneous exchange processes lead to a 'tangle of cycles' in biochemical reaction networks. \n\n* Skeleton (or scaffold) dynamic models of biochemical processes can be carried out using dynamic mass balances based on elementary reaction representations and mass action kinetics. \n\n* Complex kinetic models are built in a bottom-up fashion, adding more details in a step-wise fashion, making sure that every new feature is consistently integrated. This chapter demonstrated a four-step analysis of the ATP cofactor sub-network and then its integration to a skeleton ATP generating pathway. \n\n* Once dynamic network models are formulated, the perturbations to which we simulate their responses are in fluxes, typically the exchange and demand fluxes. \n\n* A recurring theme is the formation of pools and the state of those pools in terms of how their total concentration is distributed among its constituent members. \n\n* Some dynamic properties are a result of the stoichiometric structure and do not result from intricate regulatory mechanisms or complex kinetic expressions. \n\n$\\tiny{\\text{© B. Ø. Palsson 2011;}\\ \\text{This publication is in copyright.}\\\\ \\text{Subject to statutory exception and to the provisions of relevant collective licensing agreements,}\\\\ \\text{no reproduction of any part may take place without the written permission of Cambridge University Press.}}$\n", "meta": {"hexsha": "aa53c30daeb1557b3e2fc4e709f1ebcb1660ac11", "size": 592816, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/education/sb2/chapters/sb2_chapter8.ipynb", "max_stars_repo_name": "z-haiman/MASSpy", "max_stars_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/education/sb2/chapters/sb2_chapter8.ipynb", "max_issues_repo_name": "z-haiman/MASSpy", "max_issues_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/education/sb2/chapters/sb2_chapter8.ipynb", "max_forks_repo_name": "z-haiman/MASSpy", "max_forks_repo_head_hexsha": "aeeed1e3f9d1058e9485247a86f85cb94eeecbc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 188.9754542557, "max_line_length": 63992, "alphanum_fraction": 0.8822197781, "converted": true, "num_tokens": 21231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3171349663348994}} {"text": "\n\n# Tutorial 1: Modeling sequencies and encoding text\n**Week 2, Day 3: Modern RNNs**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Bhargav Srinivasa Desikan, Anis Zahedifard, James Evans\n\n__Content reviewers:__ Lily Cheng, Melvin Selim Atay, Ezekiel Williams\n\n__Content editors:__ Nina Kudryashova, Spiros Chavlis\n\n__Production editors:__ Roberto Guidotti, Spiros Chavlis\n\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n----\n# Tutorial objectives\n\nBefore we begin with exploring how RNNs excel at modelling sequences, we will explore some of the other ways we can model sequences, encode text, and make meaningful measurements using such encodings and embeddings. \n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorial\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/n263c/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n## Setup\n\n\n```python\n# @title Install dependencies\nfrom IPython.display import clear_output\n!pip install torchtext==0.4.0 --quiet\n!pip install --upgrade gensim --quiet\n!pip install unidecode --quiet\n!pip install hmmlearn --quiet\n!pip install fasttext --quiet\n!pip install nltk --quiet\n!pip install pandas --quiet\nclear_output()\n```\n\n\n```python\n# Imports\nimport os\nimport time\nimport nltk\nimport torch\nimport pickle\nimport zipfile\nimport fasttext\nimport requests\nimport urllib.request\n\nimport numpy as np\nimport pandas as pd\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm_notebook as tqdm\n\nfrom hmmlearn import hmm\nfrom gensim.models import Word2Vec\nfrom scipy.sparse import dok_matrix\n\nfrom torchtext import data, datasets\nfrom torchtext.vocab import FastText\n\nfrom nltk import FreqDist\nfrom nltk.corpus import brown\nfrom nltk.tokenize import word_tokenize\n\nfrom sklearn.manifold import TSNE\nfrom sklearn.preprocessing import LabelEncoder\n```\n\n\n```python\n# @title Figure Settings\nimport ipywidgets as widgets\n%config InlineBackend.figure_format = 'retina'\nplt.style.use(\"https://raw.githubusercontent.com/NeuromatchAcademy/content-creation/main/nma.mplstyle\")\n```\n\n\n```python\n# @title Load Dataset from `nltk`\n# no critical warnings, so we supress it\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nnltk.download('punkt')\nnltk.download('averaged_perceptron_tagger')\nnltk.download('brown')\nnltk.download('webtext')\n```\n\n\n```python\n# @title Helper functions\ndef cosine_similarity(vec_a, vec_b):\n \"\"\"Compute cosine similarity between vec_a and vec_b\"\"\"\n return np.dot(vec_a, vec_b) / (np.linalg.norm(vec_a) * np.linalg.norm(vec_b))\n\n\ndef tokenize(sentences):\n #Tokenize the sentence\n #from nltk.tokenize library use word_tokenize\n token = word_tokenize(sentences)\n\n return token\n\n\ndef plot_train_val(x, train, val, train_label, val_label, title, y_label,\n color):\n plt.plot(x, train, label=train_label, color=color)\n plt.plot(x, val, label=val_label, color=color, linestyle='--')\n plt.legend(loc='lower right')\n plt.xlabel('epoch')\n plt.ylabel(y_label)\n plt.title(title)\n\n\ndef load_dataset(emb_vectors, sentence_length=50, seed=522):\n TEXT = data.Field(sequential=True,\n tokenize=tokenize,\n lower=True,\n include_lengths=True,\n batch_first=True,\n fix_length=sentence_length)\n LABEL = data.LabelField(dtype=torch.float)\n\n train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)\n\n TEXT.build_vocab(train_data, vectors=emb_vectors)\n LABEL.build_vocab(train_data)\n\n train_data, valid_data = train_data.split(split_ratio=0.7,\n random_state=random.seed(seed))\n train_iter, valid_iter, test_iter = data.BucketIterator.splits((train_data,\n valid_data,\n test_data),\n batch_size=32,\n sort_key=lambda x: len(x.text),\n repeat=False,\n shuffle=True)\n vocab_size = len(TEXT.vocab)\n\n print(f'Data are loaded. sentence length: {sentence_length} '\n f'seed: {seed}')\n\n return TEXT, vocab_size, train_iter, valid_iter, test_iter\n\n\ndef download_file_from_google_drive(id, destination):\n URL = \"https://docs.google.com/uc?export=download\"\n\n session = requests.Session()\n\n response = session.get(URL, params={ 'id': id }, stream=True)\n token = get_confirm_token(response)\n\n if token:\n params = { 'id': id, 'confirm': token }\n response = session.get(URL, params=params, stream=True)\n\n save_response_content(response, destination)\n\n\ndef get_confirm_token(response):\n for key, value in response.cookies.items():\n if key.startswith('download_warning'):\n return value\n\n return None\n\n\ndef save_response_content(response, destination):\n CHUNK_SIZE = 32768\n\n with open(destination, \"wb\") as f:\n for chunk in response.iter_content(CHUNK_SIZE):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\nimport torch\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nDEVICE = set_device()\nSEED = 2021\nset_seed(seed=SEED)\n```\n\n---\n# Section 1: Sequences, Markov Chains & HMMs\n\n\n```python\n# @title Video 1: Sequences & Markov Processes\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1jg411774B\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"ApkE7UFaJAQ\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n\n\nIn this notebook we will be exploring the world of sequences - thinking of what kind of data can be thought of as sequences, and how these sequences can be represented as Markov Chains and Hidden Markov Models. These ideas and methods were an important part of natural language processing and language modelling, and serve as a useful way to ground ourselves before we dive into neural network methods.\n\n\n## Why is this relevant? How are these sequences related to modern recurrent neural networks?\n\nLike we mentioned before, the notion of modelling sequences of data - in this particular case, **language**, is an ideal place to start. RNNs themselves were constructed keeping in mind sequences, and the ability to temporally model sequences is what inspired RNNs (and the family of LSTM, GRUs - we will see this in the next notebook).\n\nMarkov models and hidden markov models serve as an introduction to these concepts because they were some of the earliest ways to think about sequences. They do not capture a lot of the complexity that RNNs excel at, but are an useful way of thinking of sequences, probabilities, and how we can use these concepts to perform tasks such as text generation, or classification - tasks that RNNs excel at today. \n\nThink of this section as an introduction to thinking with sequences and text data, and as a historical introduction to the world of modelling sequential data. \n\n## Section 1.1: What data are sequences?\n\nNative Sequences:\n\n- Temporally occurring events (e.g., history, stock prices)\n- Temporally processed events (e.g., communication)\n- Topologically connected components (e.g., polymers, peptides)\n\nSynthetic Sequences: \n\n- Anything processed as a sequence (e.g., scanned pixels in an image)\n\nSequences can be represented as a Markov Process - since this notion of sequential data is intrinsically linked to RNNs, it is a good place for us to start, and natural language (text!) will be our sequence of choice. \n\nWe will be using the Brown corpus which comes loaded with NLTK, and using the entire corpus - this requires a lot of RAM for some of the methods, so we recommend using a smaller subset of categories if you do not have enough RAM.\n\nWe will be using some of the code from this [tutorial](https://www.kdnuggets.com/2019/11/markov-chains-train-text-generation.html) and this [Jupyter notebook](https://github.com/StrikingLoo/ASOIAF-Markov/blob/master/ASOIAF.ipynb)\n\nThe first few cells of code all involve set-up; some of this code will be hidden because they are not necessary to understand the ideas of markov models, but the way data is setup can be vital to the way the model performs (something in common with neural network models!).\n\nLet us start with loading our corpus.\n\n\n\n\n```python\ncategory = ['editorial', 'fiction', 'government', 'news', 'religion']\nsentences = brown.sents(categories=category)\n```\n\nNow that we have our sentences, let us look at some statistics to get an idea of what we are dealing with.\n\n\n```python\nlengths = [len(sentence) for sentence in sentences]\nlengths = pd.Series(lengths)\n```\n\nFind the 80-th percentile: the minimal length of such a sentence, which is longer than at least 80% of sentences in the *Brown corpus*.\n\n\n```python\nlengths.quantile(.8)\n```\n\n\n```python\nlengths.describe()\n```\n\n\n```python\nsentences[0:2]\n```\n\nThis gives us an idea of what our dataset looks like, along with some average lengths. This kind of quick data exploration can be very useful - we know how long different sequences are, and how we might want to collect these words.\n\nSince we will be modelling words as sequences in sentences, let us first collect all the words in our corpus.\n\n\n```python\ncorpus_words = []\nfor sentence in sentences:\n for word in sentence:\n if \"''\" not in word and \"``\" not in word:\n corpus_words.append(word)\n```\n\n\n```python\nprint(\"Corpus length: \"+ str(len(corpus_words)))\n```\n\n\n```python\ncorpus_words[0:20]\n```\n\nWe'll now get distinct (unique) words and create a matrix to represent all these words. This is necessary because we will be using this matrix to look at the probability of the words in sequences.\n\n\n```python\n# @title Creating Matrices and Distinct Words\ndistinct_words = list(set(corpus_words))\nword_idx_dict = {word: i for i, word in enumerate(distinct_words)}\ndistinct_words_count = len(list(set(corpus_words)))\nnext_word_matrix = np.zeros([distinct_words_count, distinct_words_count])\n```\n\n\n```python\nprint(\"Number of distinct words: \" + str(distinct_words_count))\n```\n\nIn the following lines of code we are populating the matrix that tracks the next word in a sentence.\n\n\n```python\n# @title Populating Matric that tracks next word\nfor i, word in enumerate(corpus_words[:-1]):\n first_word_idx = word_idx_dict[word]\n next_word_idx = word_idx_dict[corpus_words[i+1]]\n next_word_matrix[first_word_idx][next_word_idx] +=1\n```\n\nNow we have the information ready to construct a markov chain. The next word matrix is crucial in this, as it allows us to go from one word in the sequence to the next. We will soon see how this is used.\n\n## Section 1.2: What is a Markov Chain or Model?\n\nA Markov Chain (or Model) is a:\n- stochastic model describing a sequence of possible events\n- the probability of each event depends only on the state attained in the previous event.\n- a countably infinite sequence, in which the chain moves state at discrete time steps, gives a discrete-time Markov chain (DTMC) [vs. a continuous-time process or CTMC].\n- The classic formal language model is a Markov Model\n\n*Helpful explanations from [eric mjl's tutorial](https://ericmjl.github.io/essays-on-data-science/machine-learning/markov-models/#non-autoregressive-homoskedastic-emissions)*!\n\n\n\nThe simplest Markov models assume that we have a _system_ that contains a finite set of states,\nand that the _system_ transitions between these states with some probability at each time step $t$,\nthus generating a sequence of states over time.\nLet's call these states $S$, where\n\n\\begin{equation}\nS = \\{s_1, s_2, ..., s_n\\}\n\\end{equation}\n\nTo keep things simple, let's start with three states:\n\n\\begin{equation}\nS = \\{s_1, s_2, s_3\\}\n\\end{equation}\n\nA Markov model generates a sequence of states, with one possible realization being:\n\n\\begin{equation}\n\\{s_1, s_1, s_1, s_3, s_3, s_3, s_2, s_2, s_3, s_3, s_3, s_3, s_1, ...\\}\n\\end{equation}\n\nAnd generically, we represent it as a sequence of states $x_t, x_{t+1}... x_{t+n}$. (We have chosen a different symbol to not confuse the \"generic\" state with the specific realization. Graphically, a plain and simple Markov model looks like the following:\n\n
\n\n### Modelling transitions between states\n\nTo know how a system transitions between states, we now need a **transition matrix**.\n\nThe transition matrix describes the probability of transitioning from one state to another (The probability of staying in the same state is semantically equivalent to transitioning to the same state).\n\nBy convention, transition matrix rows correspond to the state at time $t$,\nwhile columns correspond to state at time $t+1$.\nHence, row probabilities sum to one, because the probability of transitioning to the next state depends on only the current state, and all possible states are known and enumerated.\n\nLet's call the transition matrix $P_{transition}$:\n\n\\begin{equation}\nP_{transition} = \n \\begin{pmatrix}\n p_{11} & p_{12} & p_{13} \\\\\n p_{21} & p_{22} & p_{23} \\\\\n p_{31} & p_{32} & p_{33} \\\\\n \\end{pmatrix}\n\\end{equation}\n\nUsing the transition matrix, we can express different behaviors of the system. For example:\n1. by assigning larger probability mass to the diagonals, we can express that the system likes to stay in the current state;\n2. by assigning larger probability mass to the off-diagonal, we can express that the system likes to transition out of its current state.\n\nIn our case, this matrix is created by measuring how often one word appeared after another.\n\n\n```python\n# @title Function for most likely word\ndef most_likely_word_after(word):\n # we check for the word most likely to occur using the matrix\n most_likely = next_word_matrix[word_idx_dict[word]].argmax()\n return distinct_words[most_likely]\n```\n\nUsing our most likely word function, we can begin to create chains of words and create sequences. In the code below we create a naive chain that simply choses the most likely word.\n\n\n```python\n# @title Function for building Naive Chain\ndef naive_chain(word, length=15):\n current_word = word\n sentence = word\n # we now build a naive chain by picking up the most likely word\n for _ in range(length):\n sentence += ' '\n next_word = most_likely_word_after(current_word)\n sentence += next_word\n current_word = next_word\n return sentence\n```\n\nLet us now use this naive chain to see what comes up, using some simple words.\n\n\n```python\nprint(naive_chain('the'))\nprint(naive_chain('I'))\nprint(naive_chain('What'))\nprint(naive_chain('park'))\n```\n\nWe notice that after the word `the`, `United States` comes up each time. All the other sequencies starting from other words also end up at `the` quite often. Since we use a *deterministic* markov chain model, its next state only depends on the previous one. Therefore, once the sequence comes to `the`, it inevitably continues the sequence with the `United States`.\n\nWe can now be a little more sophisticated, and return words in a sequence using a *weighted choice*, which randomly selects the next word from a set of words with some probability (weight).\n\n\n```python\n# @title Function for weighted choice\ndef weighted_choice(objects, weights):\n \"\"\"\n Returns randomly an element from the sequence of 'objects',\n the likelihood of the objects is weighted according\n to the sequence of 'weights', i.e. percentages.\n \"\"\"\n\n weights = np.array(weights, dtype=np.float64)\n sum_of_weights = weights.sum()\n # standardization:\n np.multiply(weights, 1 / sum_of_weights)\n weights = weights.cumsum()\n x = random.random()\n for i in range(len(weights)):\n if x < weights[i]:\n return objects[i]\n```\n\n\n```python\n# @title Function for sampling next word with weights\ndef sample_next_word_after(word, alpha=0):\n next_word_vector = next_word_matrix[word_idx_dict[word]] + alpha\n likelihoods = next_word_vector/next_word_vector.sum()\n return weighted_choice(distinct_words, likelihoods)\n```\n\n\n```python\nsample_next_word_after('The')\n```\n\n\n```python\nsample_next_word_after('The')\n```\n\nThere! We don't see the same word twice, because of the added randomisation (i.e., stochasticity). Our algorithm calculates how likely it is to find a certain word after a given word (`The` in this case) in the corpus, and then generates 1 sample of the next word with a matching probability. \n\nIn this example, we generated only one next word. Now, using this function, we'll build a chain.\n\n\n```python\n# @title Function for a stochastic chain using weighted choice\ndef stochastic_chain(word, length=15):\n current_word = word\n sentence = word\n\n for _ in range(length):\n sentence += ' '\n next_word = sample_next_word_after(current_word)\n sentence += next_word\n current_word = next_word\n\n return sentence\n```\n\n\n```python\nstochastic_chain('Hospital')\n```\n\nNeat - we can create stochastic chains for a single word. For a more effective language model, we would want to model sets of words - in the following cells, we create sets of words to predict a chain after a sequence.\n\n\n```python\nk = 3\n```\n\n\n```python\ndef sequences_matrices(k=3):\n # @title Code to build sets of words for more realistic sequences\n sets_of_k_words = [' '.join(corpus_words[i:i+k]) for i, _ in enumerate(corpus_words[:-k])]\n sets_count = len(list(set(sets_of_k_words)))\n next_after_k_words_matrix = dok_matrix((sets_count, len(distinct_words)))\n distinct_sets_of_k_words = list(set(sets_of_k_words))\n k_words_idx_dict = {word: i for i, word in enumerate(distinct_sets_of_k_words)}\n distinct_k_words_count = len(list(set(sets_of_k_words)))\n for i, word in tqdm(enumerate(sets_of_k_words[:-k])):\n word_sequence_idx = k_words_idx_dict[word]\n next_word_idx = word_idx_dict[corpus_words[i+k]]\n next_after_k_words_matrix[word_sequence_idx, next_word_idx] += 1\n return k_words_idx_dict,distinct_sets_of_k_words,next_after_k_words_matrix\n\nk_words_idx_dict, distinct_sets_of_k_words, next_after_k_words_matrix = sequences_matrices(k=k)\n```\n\nLet's have a look at what that bit of code did.\n\n\n```python\ndistinct_sets_of_k_words[:10]\n```\n\nGreat! Now we are going to create a transition matrix for the sets of words.\n\n\n```python\n# @title Code to populate matrix of sets of words\nfor i, word in tqdm(enumerate(distinct_sets_of_k_words[:-k])):\n word_sequence_idx = k_words_idx_dict[word]\n next_word_idx = word_idx_dict[corpus_words[i+k]]\n next_after_k_words_matrix[word_sequence_idx, next_word_idx] += 1\n```\n\nWe now have what we need to build a stochastic chain over a `K` set of words.\n\n\n```python\n# @title Function for stochastic Chain for sets of words\ndef stochastic_chain_sequence(words, chain_length=15, k=2):\n current_words = words.split(' ')\n if len(current_words) != k:\n raise ValueError(f'wrong number of words, expected {k}')\n sentence = words\n\n # pre-calculate seq embedding + transition matrix for a given k\n matrices = sequences_matrices(k=k)\n\n for _ in range(chain_length):\n sentence += ' '\n next_word = sample_next_word_after_sequence(matrices,' '.join(current_words))\n sentence += next_word\n current_words = current_words[1:]+[next_word]\n return sentence\n```\n\n\n```python\n# @title Function to sample next word after sequence\ndef sample_next_word_after_sequence(matrices, word_sequence, alpha=0):\n # unpack a tuple of matrices\n k_words_idx_dict,distinct_sets_of_k_words, next_after_k_words_matrix = matrices\n\n next_word_vector = next_after_k_words_matrix[k_words_idx_dict[word_sequence]] + alpha\n likelihoods = next_word_vector/next_word_vector.sum()\n return weighted_choice(distinct_words, likelihoods.toarray())\n```\n\n\n```python\nstochastic_chain_sequence('Judges under the', chain_length=3, k=3)\n```\n\nGreat! This sentence was created using two of the techniques we recently saw - creating sets of words, and using a weighted average stochastic chain. Both of these methods contributed in making it a more meaningful sequence of words. Some of these notions are also captured by Recurrent Neural Networks!\n\n### Think! 1.2: How does changing parameters the sentences generated?\n\nTry and use a set of words but using a naive chain, and try a stochastic chain with a low value of k (i.e., 2), and a higher value (i.e., 5). How do these different configurations change the quality of the sequences produced? Below you have sample code to try these out.\n\n```python\nstochastic_chain_sequence(..., chain_length=..., k=...)\n```\n\nYou should be able to use these matrices and the previous functions to be able to create the necessary configurations.\n\n## Section 1.3: What is a Hidden Markov Model?\n\nA 1960s advance (by Leonard Baum and colleagues): Hidden Markov Models are:\n- a Markov model in which the system modeled is assumed to be a Markov process/chain with unobservable (\"hidden\") states. \n- HMM assumes there is another surrogate process whose behavior \"depends\" on the state--you learn about the state by observing the surrogate process. \n- HMMs have successfully been applied in fields where the goal is to recover a data sequence not immediately observable (but other data that depend on the sequence are).\n- The first dominant application: Speech and text processing (1970s)\n\nIn this sub-section we will use the python library [hmmlearn](https://hmmlearn.readthedocs.io/en/latest/tutorial.html#training-hmm-parameters-and-inferring-the-hidden-states), which is part of the *scikit-learn* ecosystem. [nlg-with-hmmlearn](https://github.com/mfilej/nlg-with-hmmlearn) offers useful code snippets to adapt ```hmmlearn``` for text data. Because we are using a package that offers many out of the box implementations for HMMs, we don't have to worry about the states, transition matrices, \n\n\n```python\n# load the data\nsentences = brown.sents(categories=category)\nwords = [word.lower() for sentence in sentences for word in sentence]\nlengths = [len(sentence) for sentence in sentences]\nalphabet = set(words)\n\n# Encode words\nle = LabelEncoder()\n_ = le.fit(list(alphabet))\n\n# Find word freqeuncies\nseq = le.transform(words)\nfeatures = np.fromiter(seq, np.int64)\nfeatures = np.atleast_2d(features).T\nfd = FreqDist(seq)\n```\n\nNow that we have our data setup, we can create our model. We use a multinomial HMM with 8 states, and can either do a random initialisation or use word frequences. We recommend trying both options!\n\n\n```python\n# @title Function to create default Multinomial HMM model\ndef get_model(num_states):\n print(\"Initial parameter estimation using built-in method\")\n model = hmm.MultinomialHMM(n_components=num_states, init_params='ste')\n return model\n```\n\n\n```python\n# @title Function to create default Multinomial HMM model information of relative frequencies of words\ndef frequencies(num_states):\n print(\"Initial parameter estimation using relative frequencies\")\n\n frequencies = np.fromiter((fd.freq(i) for i in range(len(alphabet))),\n dtype=np.float64)\n emission_prob = np.stack([frequencies]*num_states)\n\n model = hmm.MultinomialHMM(n_components=num_states, init_params='st')\n model.emissionprob_ = emission_prob\n return model\n\n\nprint(frequencies(2))\n```\n\n**Note**:\n\nThe following lines of code are commented out because they take a long time (~17 mins for default Brown corpus categories). \n\nIf you do not have that time, you can download the default model to try to generate text. You have to uncomment the appropriate lines.\n\n\n```python\n## Fitting a default multinomial HMM. This is lenghty (~17 mins)\ndef run_model(features, length, num_states):\n model = get_model(num_states)\n model = model.fit(features, lengths)\n\n## Uncomment if you have time!\nnum_states = 8\n# run_model(features, length, num_states)\n## another way to get a model is to use default frequencies when initialising the model\n# model = frequencies(num_states)\n```\n\nAlternatively, you could use a saved model. Here is a [link](https://drive.google.com/file/d/1IymcmcO48V6q3x-6dhf7-OU5NByo5W2F/view?usp=sharing) to the default model, which you can download and then upload into Colab.\n\n\n```python\n## code to load saved model\nurl = \"https://osf.io/5k6cs/download\"\nurllib.request.urlretrieve(url, 'model_w2d3_t1.pkl')\nwith open(\"model_w2d3_t1.pkl\", \"rb\") as file: model = pickle.load(file)\n```\n\n\n```python\n# @title Function to generate words given a hmm model\ndef generate_text(model, num_lines = 5, random_len=15):\n for _i in range(num_lines):\n set_seed(_i)\n symbols, _states = model.sample(random_len)\n\n output = le.inverse_transform(np.squeeze(symbols))\n for word in output:\n print(word, end=\" \")\n print()\n```\n\n\n```python\ngenerate_text(model, num_lines=2, random_len=20)\n```\n\nWe see that a hidden markov model also does well in generating text. We encourage you to try out different initialisations and hyperparameters to see how the model does.\n\n### Exercise 1.3: Transition probabilities \n\n\nWe have seen how we can use sequences of text to form probability chains, as well as how we can use out of the box models to generate text. In this exercise, you will be using your own data to generate sequences using ```hmmlearn``` or any other implementation of a markov model. Explore the transition probabilities in your corpus and generate sentences. For example, one such exploration can be - how does using a model with the word frequencies incorporated in compare to using a default model?\n\nPerform any one such comparison or exploration, and generate 3 sentences or 50 words using your model. You should be able to use all the existing functions defined for this exercise.\n\n\n```python\n# load your own dataset and create a model using the frequencies based HMM model!\n```\n\n### Useful links for Markov Models and HMM:\n\nHere are some useful links if you wish to explore this topic further.\n\n- [Markov Chain Text](https://towardsdatascience.com/simulating-text-with-markov-chains-in-python-1a27e6d13fc6)\n\n- [Python QuantEcon: Finite Markov Chains with Finance](https://python.quantecon.org/finite_markov.html)\n\n- [Markov Models from the ground up, with python](https://ericmjl.github.io/essays-on-data-science/machine-learning/markov-models/)\n\n- [GenTex](https://github.com/nareshkumar66675/GenTex)\n\n- [HMM learn](https://hmmlearn.readthedocs.io/en/latest/tutorial.html)\n\n---\n# Section 2: Word Embeddings\n\n\n\n```python\n# @title Video 2: Textual Dimension Reduction\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1oM4y1P7Mn\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"kweySXAZ1os\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n\nWords or subword units such as morphemes are the basic units that we use to express meaning in language. The technique of mapping words to vectors of real numbers is known as word embedding. \n\nWord2vec is based on theories of distributional semantics - words that appear around each other are more likely to mean similar things than words that do not appear around each other. Keeping this in mind, our job is to create a high dimensional space where these semantic relations are preserved. The innovation in word2vec is the realisation that we can use unlabelled, running text in sentences as inputs for a supervised learning algorithm--as a self-supervision task. It is supervised because we use the words in a sentence to serve as positive and negative examples. Let’s break this down:\n\n... \"use the kitchen knife to chop the vegetables\"…\n\n**C1 C2 C3 T C4 C5 C6 C7**\n\nHere, the target word is knife, and the context words are the ones in its immediate (6-word) window. \nThe first word2vec method we’ll see is called skipgram, where the task is to assign a probability for how likely it is that the context window appears around the target word. In the training process, positive examples are samples of words and their context words, and negative examples are created by sampling from pairs of words that do not appear nearby one another. \n\nThis method of implementing word2vec is called skipgram with negative sampling. So while the algorithm tries to better learn which context words are likely to appear around a target word, it ends up pushing the embedded representations for every word so that they are located optimally (e.g., with minimal semantic distortion). In this process of adjusting embedding values, the algorithm brings semantically similar words close together in the resulting high dimensional space, and dissimilar words far away. \n\nAnother word2vec training method, Continuous Bag of Words (CBOW), works in a similar fashion, and tries to predict the target word, given context. This is converse of skipgram, which tries to predict the context, given the target word. Skip-gram represents rare words and phrases well, often requiring more data for stable representations, while CBOW is several times faster to train than the skip-gram, but with slightly better accuracy for the frequent words in its prediction task. The popular gensim implementation of word2vec has both the methods included. \n\n## Section 2.1: Creating Word Embeddings\n\nWe will create embeddings for a subset of categories in [Brown corpus](https://www1.essex.ac.uk/linguistics/external/clmt/w3c/corpus_ling/content/corpora/list/private/brown/brown.html). In order to achieve this task we will use [gensim](https://radimrehurek.com/gensim/) library to create word2vec embeddings. Gensim’s word2vec expects a sequence of sentences as its input. Each sentence is a list of words.\nCalling `Word2Vec(sentences, iter=1)` will run two passes over the sentences iterator (or, in general iter+1 passes). The first pass collects words and their frequencies to build an internal dictionary tree structure. The second and subsequent passes train the neural model. \n`Word2vec` accepts several parameters that affect both training speed and quality.\n\nOne of them is for pruning the internal dictionary. Words that appear only once or twice in a billion-word corpus are probably uninteresting typos and garbage. In addition, there’s not enough data to make any meaningful training on those words, so it’s best to ignore them:\n\n`model = Word2Vec(sentences, min_count=10) # default value is 5`\n\n\nA reasonable value for min_count is between 0-100, depending on the size of your dataset.\n\nAnother parameter is the size of the NN layers, which correspond to the “degrees” of freedom the training algorithm has:\n\n`model = Word2Vec(sentences, size=200) # default value is 100`\n\n\nBigger size values require more training data, but can lead to better (more accurate) models. Reasonable values are in the tens to hundreds.\n\nThe last of the major parameters (full list [here](https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec)) is for training parallelization, to speed up training:\n\n`model = Word2Vec(sentences, workers=4) # default = 1 worker = no parallelization`\n\n\n```python\ncategory = ['editorial', 'fiction', 'government', 'mystery', 'news', 'religion',\n 'reviews', 'romance', 'science_fiction']\n```\n\n\n```python\ndef create_word2vec_model(category='news', size=50, sg=1, min_count=5):\n try:\n sentences = brown.sents(categories=category)\n model = Word2Vec(sentences, vector_size=size, sg=sg, min_count=min_count)\n\n except (AttributeError, TypeError):\n raise AssertionError('Input variable \"category\" should be a string or list,'\n '\"size\", \"sg\", \"min_count\" should be integers')\n\n return model\n\ndef model_dictionary(model):\n words = list(w2vmodel.wv.key_to_index)\n return words\n\ndef get_embedding(word, model):\n if word in w2vmodel.wv.key_to_index:\n return model.wv[word]\n else:\n return None\n```\n\n\n```python\nall_categories = brown.categories()\n```\n\n\n```python\nall_categories\n```\n\n\n```python\nw2vmodel = create_word2vec_model(all_categories)\n```\n\n\n```python\nprint(model_dictionary(w2vmodel))\n```\n\n\n```python\nprint(get_embedding('weather', w2vmodel))\n```\n\n## Section 2.2: Visualizing Word Embedding\n\nWe can now obtain the word embeddings for any word in the dictionary using word2vec. Let's visualize these embeddings to get an inuition of what these embeddings mean. The word embeddings obtained from word2vec model are in high dimensional space. We will use `PCA` to pick the 2 features that capture the most variance in the embeddings in order to represent them in a 2D space.\n\n\nFor each word in `keys`, we pick the top 10 similar words (using cosine similarity) and plot them. \n\n What should be the arrangement of similar words?\n What should be arrangement of the key clusters with respect to each other?\n \n\n\n```python\nkeys = ['voters', 'magic', 'love', 'God', 'evidence', 'administration', 'governments']\n```\n\n\n```python\ndef get_cluster_embeddings(keys):\n embedding_clusters = []\n word_clusters = []\n\n # find closest words and add them to cluster\n for word in keys:\n embeddings = []\n words = []\n if not word in w2vmodel.wv.key_to_index:\n print('The word ', word, 'is not in the dictionary')\n continue\n\n for similar_word, _ in w2vmodel.wv.most_similar(word, topn=10):\n words.append(similar_word)\n embeddings.append(w2vmodel.wv[similar_word])\n embedding_clusters.append(embeddings)\n word_clusters.append(words)\n\n # get embeddings for the words in clusers\n embedding_clusters = np.array(embedding_clusters)\n n, m, k = embedding_clusters.shape\n tsne_model_en_2d = TSNE(perplexity=10, n_components=2, init='pca', n_iter=3500, random_state=32)\n embeddings_en_2d = np.array(tsne_model_en_2d.fit_transform(embedding_clusters.reshape(n * m, k))).reshape(n, m, 2)\n\n return embeddings_en_2d, word_clusters\n```\n\n\n```python\ndef tsne_plot_similar_words(title, labels, embedding_clusters,\n word_clusters, a, filename=None):\n plt.figure(figsize=(16, 9))\n colors = cm.rainbow(np.linspace(0, 1, len(labels)))\n for label, embeddings, words, color in zip(labels, embedding_clusters, word_clusters, colors):\n x = embeddings[:, 0]\n y = embeddings[:, 1]\n plt.scatter(x, y, color=color, alpha=a, label=label)\n for i, word in enumerate(words):\n plt.annotate(word,\n alpha=0.5,\n xy=(x[i], y[i]),\n xytext=(5, 2),\n textcoords='offset points',\n ha='right',\n va='bottom',\n size=10)\n plt.legend(loc=\"lower left\")\n plt.title(title)\n plt.grid(True)\n if filename:\n plt.savefig(filename, format='png', dpi=150, bbox_inches='tight')\n plt.show()\n```\n\n\n```python\nembeddings_en_2d, word_clusters = get_cluster_embeddings(keys)\ntsne_plot_similar_words('Similar words from Brown Corpus', keys, embeddings_en_2d, word_clusters, 0.7)\n```\n\n## Section 2.3: Exploring meaning with word embeddings\n\nWhile word2vec was the method that started it all, research has since boomed, and we now have more sophisticated ways to represent words. One such method is FastText, developed at Facebook AI research, which breaks words into sub-words: such a technique also allows us to create embedding representations for unseen words. In this section, we will explore how semantics and meaning are captured using embedidngs, after downloading a pre-trained FastText model. Downloading pre-trained models is a way for us to plug in word embeddings and explore them without training them ourselves.\n\n\n```python\n# @title Download FastText English Embeddings of dimension 100\n\n# 1d2fzekxTgDIA9LEYskPXT1sfccgAGmUF\n# file_id = '11qRoFOUiGnvM04ERcN_6Qn6O_dJ2KPLk'\n# destination = 'cc.en.100.bin.zip'\n# download_file_from_google_drive(file_id, destination)\n!wget -O cc.en.100.bin.gz https://osf.io/2frqg/download --quiet\n\nos.listdir('.')\nwith zipfile.ZipFile('cc.en.100.bin.gz', 'r') as zip_ref:\n zip_ref.extractall('.')\n```\n\n\n```python\n# Load 100 dimension FastText Vectors using FastText library\nft_en_vectors = fasttext.load_model('cc.en.100.bin')\n```\n\n\n```python\nprint(\"Length of the embedding is: \", len(ft_en_vectors.get_word_vector('king')))\nprint(\"Embedding for the word King is: \", ft_en_vectors.get_word_vector('king'))\n```\n\nCosine similarity is used for similarities between words. Similarity is a scalar between 0 and 1.\n\nNow find the 10 most similar words to \"King\"\n\n\n```python\nft_en_vectors.get_nearest_neighbors(\"king\", 10) # Most similar by key\n```\n\n### Word Similarity\n\n\n```python\n# @title Video 3: Semantic Measurements\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV15w411R7SW\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"Y45KIAOw4OY\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\nMore on similarity between words. Let's check how similar different pairs of word are. Feel free to play around.\n\n\n\n\n```python\ndef getSimilarity(word1, word2):\n v1 = ft_en_vectors.get_word_vector(word1)\n v2 = ft_en_vectors.get_word_vector(word2)\n return cosine_similarity(v1, v2)\n\nprint(\"Similarity between the words King and Queen: \", getSimilarity(\"king\", \"queen\"))\nprint(\"Similarity between the words King and Knight: \", getSimilarity(\"king\", \"knight\"))\nprint(\"Similarity between the words King and Rock: \", getSimilarity(\"king\", \"rock\"))\nprint(\"Similarity between the words King and Twenty: \", getSimilarity(\"king\", \"twenty\"))\n\n## Try the same for two more pairs\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n```\n\n### Homonym Words$^\\dagger$\n\nFind the similarity for homonym words with their different meanings. The first one has been implemented for you.\n\n\n$^\\dagger$: Two or more words having the same spelling or pronunciation but different meanings and origins are called *homonyms*. E.g., \n\n\n```python\n####################### Words with multiple meanings ##########################\nprint(\"Similarity between the words Cricket and Insect: \", getSimilarity(\"cricket\", \"insect\"))\nprint(\"Similarity between the words Cricket and Sport: \", getSimilarity(\"cricket\", \"sport\"))\n\n## Try the same for two more pairs\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n# print(\"Similarity between the words ___ and ___: \", getSimilarity(...))\n```\n\n### Word Analogies\n\nEmbeddings can be used to find word analogies.\nLet's try it:\n1. Man : Woman :: King : _____\n2. Germany: Berlin :: France : ______\n3. Leaf : Tree :: Petal : _____\n\n\n```python\n## Use get_analogies() funnction. The words have to be in the order Positive, negative, Positve\n\n# Man : Woman :: King : _____\n# Positive=(woman, king), Negative=(man)\nprint(ft_en_vectors.get_analogies(\"woman\", \"man\", \"king\",1))\n\n# Germany: Berlin :: France : ______\n# Positive=(berlin, frannce), Negative=(germany)\nprint(ft_en_vectors.get_analogies(\"berlin\", \"germany\", \"france\",1))\n\n# Leaf : Tree :: Petal : _____\n# Positive=(tree, petal), Negative=(leaf)\nprint(ft_en_vectors.get_analogies(\"tree\", \"leaf\", \"petal\",1))\n\n# Hammer : Nail :: Comb : _____\n# Positive=(nail, comb), Negative=(hammer)\nprint(ft_en_vectors.get_analogies(\"nail\", \"hammer\", \"comb\",1))\n```\n\nBut, does it always work?\n\n\n1. Poverty : Wealth :: Sickness : _____\n2. train : board :: horse : _____\n\n\n```python\n# Poverty : Wealth :: Sickness : _____\nprint(ft_en_vectors.get_analogies(\"wealth\", \"poverty\", \"sickness\",1))\n\n# train : board :: horse : _____\nprint(ft_en_vectors.get_analogies(\"board\", \"train\", \"horse\",1))\n```\n\n---\n# Section 3: Neural Net with word embeddings\n\nLet's use the pretrained FastText embeddings to train a neural network on the IMDB dataset. \n\nTo recap, the data consists of reviews and sentiments attached to it. It is a binary classification task. As a simple preview of the upcoming neural networks, we are going to introduce neural net with word embeddings. We'll see detailed networks in the next tutorial.\n\n\n\n\n## Coding Exercise 3.1: Simple Feed Forward Net\n\nThis will load 300 dim FastText embeddings. It will take around 2-3 minutes.\n\nDefine a vanilla neural network with linear layers. Then average the word embeddings to get an embedding for the entire review.\nThe neural net will have one hidden layer of size 128.\n\n\n```python\n# @title Download embeddings and clear old variables to clean memory.\n# @markdown #### Execute this cell!\nif 'ft_en_vectors' in locals():\n del ft_en_vectors\nif 'w2vmodel' in locals():\n del w2vmodel\n\nembedding_fasttext = FastText('simple')\n```\n\n\n```python\n# @markdown Load the Dataset\nTEXT, vocab_size, train_iter, valid_iter, test_iter = load_dataset(embedding_fasttext, seed=SEED)\n```\n\n\n```python\nclass NeuralNet(nn.Module):\n def __init__(self, batch_size, output_size, hidden_size, vocab_size,\n embedding_length, word_embeddings):\n super(NeuralNet, self).__init__()\n\n self.word_embeddings = nn.Embedding(vocab_size, embedding_length)\n self.word_embeddings.weight = nn.Parameter(word_embeddings,\n requires_grad=False)\n self.fc1 = nn.Linear(embedding_length, hidden_size)\n self.fc2 = nn.Linear(hidden_size, output_size)\n\n\n def forward(self, inputs):\n\n input = self.word_embeddings(inputs) # convert text to embeddings\n ####################################################################\n # Fill in missing code below (...)\n raise NotImplementedError(\"Fill in the Neural Net\")\n ####################################################################\n # Average the word embedddings in a sentence\n # Use torch.nn.functional.avg_pool2d to compute the averages\n pooled = ...\n\n # Pass the embeddings through the neural net\n # A fully-connected layer\n x = ...\n # ReLU activation\n x = ...\n # Another fully-connected layer\n x = ...\n output = F.log_softmax(x, dim=1)\n\n return output\n\n\n# Uncomment to check your code\n# nn_model = NeuralNet(32, 2, 128, 100, 300, TEXT.vocab.vectors)\n# print(nn_model)\n```\n\n\n```python\n# to_remove solution\nclass NeuralNet(nn.Module):\n def __init__(self, batch_size, output_size, hidden_size, vocab_size,\n embedding_length, word_embeddings):\n super(NeuralNet, self).__init__()\n\n self.word_embeddings = nn.Embedding(vocab_size, embedding_length)\n self.word_embeddings.weight = nn.Parameter(word_embeddings,\n requires_grad=False)\n self.fc1 = nn.Linear(embedding_length, hidden_size)\n self.fc2 = nn.Linear(hidden_size, output_size)\n\n\n def forward(self, inputs):\n\n input = self.word_embeddings(inputs) # convert text to embeddings\n # Average the word embedddings in a sentence\n # Use torch.nn.functional.avg_pool2d to compute the averages\n pooled = F.avg_pool2d(input, (input.shape[1], 1)).squeeze(1)\n\n # Pass the embeddings through the neural net\n # A fully-connected layer\n x = self.fc1(pooled)\n\n # ReLU activation\n x = F.relu(x)\n # Another fully-connected layer\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n\n return output\n\n\n# Uncomment to check your code\nnn_model = NeuralNet(32, 2, 128, 100, 300, TEXT.vocab.vectors)\nprint(nn_model)\n```\n\n```\nNeuralNet(\n (word_embeddings): Embedding(100, 300)\n (fc1): Linear(in_features=300, out_features=128, bias=True)\n (fc2): Linear(in_features=128, out_features=2, bias=True)\n)\n```\n\n\n```python\n# @title Training and Testing Functions\n\n# @markdown #### `train(model, device, train_iter, valid_iter, epochs, learning_rate)`\n# @markdown #### `test(model, device, test_iter)`\n\ndef train(model, device, train_iter, valid_iter, epochs, learning_rate):\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n train_loss, validation_loss = [], []\n train_acc, validation_acc = [], []\n\n for epoch in range(epochs):\n # train\n model.train()\n running_loss = 0.\n correct, total = 0, 0\n steps = 0\n\n for idx, batch in enumerate(train_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n # add micro for coding training loop\n optimizer.zero_grad()\n output = model(text)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n steps += 1\n running_loss += loss.item()\n\n # get accuracy\n _, predicted = torch.max(output, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n train_loss.append(running_loss/len(train_iter))\n train_acc.append(correct/total)\n\n print(f'Epoch: {epoch + 1}, '\n f'Training Loss: {running_loss/len(train_iter):.4f}, '\n f'Training Accuracy: {100*correct/total: .2f}%')\n\n # evaluate on validation data\n model.eval()\n running_loss = 0.\n correct, total = 0, 0\n\n with torch.no_grad():\n for idx, batch in enumerate(valid_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n optimizer.zero_grad()\n output = model(text)\n\n loss = criterion(output, target)\n running_loss += loss.item()\n\n # get accuracy\n _, predicted = torch.max(output, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n validation_loss.append(running_loss/len(valid_iter))\n validation_acc.append(correct/total)\n\n print (f'Validation Loss: {running_loss/len(valid_iter):.4f}, '\n f'Validation Accuracy: {100*correct/total: .2f}%')\n\n return train_loss, train_acc, validation_loss, validation_acc\n\n\ndef test(model, device, test_iter):\n model.eval()\n correct = 0\n total = 0\n with torch.no_grad():\n for idx, batch in enumerate(test_iter):\n text = batch.text[0]\n target = batch.label\n target = torch.autograd.Variable(target).long()\n text, target = text.to(device), target.to(device)\n\n outputs = model(text)\n _, predicted = torch.max(outputs, 1)\n total += target.size(0)\n correct += (predicted == target).sum().item()\n\n acc = 100 * correct / total\n return acc\n```\n\n\n```python\n# Model hyperparameters\nlearning_rate = 0.0003\nbatch_size = 32\noutput_size = 2\nhidden_size = 128\nembedding_length = 300\nepochs = 15\nword_embeddings = TEXT.vocab.vectors\nvocab_size = len(TEXT.vocab)\n\n# Model set-up\nnn_model = NeuralNet(batch_size,\n output_size,\n hidden_size,\n vocab_size,\n embedding_length,\n word_embeddings)\nnn_model.to(DEVICE)\nnn_start_time = time.time()\nset_seed(522)\nnn_train_loss, nn_train_acc, nn_validation_loss, nn_validation_acc = train(nn_model,\n DEVICE,\n train_iter,\n valid_iter,\n epochs,\n learning_rate)\nprint(f\"--- Time taken to train = {(time.time() - nn_start_time)} seconds ---\")\ntest_accuracy = test(nn_model, DEVICE, test_iter)\nprint(f'\\n\\nTest Accuracy: {test_accuracy}%')\n```\n\n\n```python\n# Plot accuracy curves\nplt.figure()\nplt.subplot(211)\nplot_train_val(np.arange(0, epochs), nn_train_acc, nn_validation_acc,\n 'train accuracy', 'val accuracy',\n 'Neural Net on IMDB text classification', 'accuracy',\n color='C0')\nplt.legend(loc='upper left')\nplt.subplot(212)\nplot_train_val(np.arange(0, epochs), nn_train_loss,\n nn_validation_loss,\n 'train loss', 'val loss',\n 'Vanilla RNN on IMDB text classification',\n 'loss [a.u.]',\n color='C0')\nplt.legend(loc='upper left')\nplt.show()\n```\n\n---\n# Summary\n\nIn this tutorial, we explored two different concepts linked to sequences, and text in particular, that will be the conceptual foundation for Recurrent Neural Networks.\n\nThe first concept was that of sequences and probabilities. We saw how we can model language as sequences of text, and use this analogy to generate text. Such a setup is also used to classify text or identify parts of speech. We can either build chains manually using simple python and numerical computation, or use a package such as ```hmmlearn``` that allows us to train models a lot easier. These notions of sequences and probabilities (i.e, creating language models!) are key to the internals of a recurrent neural network as well. \n\nThe second concept is that of word embeddings, now a mainstay of natural language processing. By using a neural network to predict context of words, these neural networks learn internal representions of words that are a decent approximation of semantic meaning (i.e embeddings!). We saw how these embeddings can be visualised, as well as how they capture meaning. We finally saw how they can be integrated into neural networks to better classify text documents.\n", "meta": {"hexsha": "b1caa9351aedf5fa7f6fc7e5e24b60854566a387", "size": 79301, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W2D3_ModernRecurrentNeuralNetworks/W2D3_Tutorial1.ipynb", "max_stars_repo_name": "carsen-stringer/course-content-dl", "max_stars_repo_head_hexsha": "27749aec56a3d2a43b3890483675ad0338a2680f", "max_stars_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorials/W2D3_ModernRecurrentNeuralNetworks/W2D3_Tutorial1.ipynb", "max_issues_repo_name": "carsen-stringer/course-content-dl", "max_issues_repo_head_hexsha": "27749aec56a3d2a43b3890483675ad0338a2680f", "max_issues_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorials/W2D3_ModernRecurrentNeuralNetworks/W2D3_Tutorial1.ipynb", "max_forks_repo_name": "carsen-stringer/course-content-dl", "max_forks_repo_head_hexsha": "27749aec56a3d2a43b3890483675ad0338a2680f", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6734607219, "max_line_length": 604, "alphanum_fraction": 0.5859068612, "converted": true, "num_tokens": 12733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3171349663348993}} {"text": "\n\n# Digital agro \n\n# Sensitivity analysis of models\n\n# Seminar - 24.04.2020\n\n## Mikhail Gasanov \n\n\n\n\n\n### The scheme and main blocks of the plant growth model\n\n\n\n\n## git clone \n\n\n```python\n!git clone https://github.com/mishagrol/Seminar_Sobol.git\n!cp -r ./Seminar_Sobol/* .\n```\n\n Cloning into 'Seminar_Sobol'...\n remote: Enumerating objects: 213, done.\u001b[K\n remote: Counting objects: 100% (213/213), done.\u001b[K\n remote: Compressing objects: 100% (163/163), done.\u001b[K\n remote: Total 213 (delta 72), reused 184 (delta 47), pack-reused 0\u001b[K\n Receiving objects: 100% (213/213), 33.39 MiB | 27.20 MiB/s, done.\n Resolving deltas: 100% (72/72), done.\n\n\n# Running PCSE/WOFOST with custom input datф\n\nThis Jupyter notebook will show you how to read inputs from files for running PCSE/WOFOST.\n\nthanks to **Allard de Wit**\n\n**Prerequisites for running this notebook**\n\nSeveral packages need to be installed for running PCSE/WOFOST:\n\n 1. `PCSE` and its dependencies. See the [PCSE user guide](http://pcse.readthedocs.io/en/stable/installing.html) for more information;\n 2. The `pandas` module for processing and storing WOFOST output;\n 3. The `matplotlib` module for generating charts\n\n\n\n\n\n## Introduction\n\nFor running PCSE/WOFOST (and PCSE models in general) with your own data sources you need three different types of inputs:\n\n 1. Model parameters that parameterize the different model components. These parameters usually consist of a set of crop parameters (or multiple sets in case of crop rotations), a set of soil parameters and a set of site parameters. The latter provide ancillary parameters that are specific for a location, for example the initial amount of moisture in the soil.\n 2. Driving variables represented by weather data which can be derived from various sources.\n 3. Agromanagement actions which specify the farm activities that will take place on the field that is simulated by PCSE.\n\nFor this example we will run a simulation for sugar beet in Wageningen (Netherlands) and we will read the input data step by step from several different sources instead of using the pre-configured start_wofost() script. For the example we will assume that data files are in the `data` directory within the directory where this notebook is located. This will be the case if you downloaded the notebooks from github.\n\n## Importing the relevant modules\n\n\n\n```python\n!pip install pcse\n```\n\n Requirement already satisfied: pcse in /usr/local/lib/python3.6/dist-packages (5.4.2)\n Requirement already satisfied: SQLAlchemy>=0.8.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.3.19)\n Requirement already satisfied: traitlets-pcse==5.0.0.dev in /usr/local/lib/python3.6/dist-packages (from pcse) (5.0.0.dev0)\n Requirement already satisfied: numpy>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.18.5)\n Requirement already satisfied: PyYAML>=3.11 in /usr/local/lib/python3.6/dist-packages (from pcse) (3.13)\n Requirement already satisfied: xlrd>=0.9.3 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.1.0)\n Requirement already satisfied: pandas>=0.20 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.0.5)\n Requirement already satisfied: requests>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (2.23.0)\n Requirement already satisfied: xlwt>=1.0.0 in /usr/local/lib/python3.6/dist-packages (from pcse) (1.3.0)\n Requirement already satisfied: decorator in /usr/local/lib/python3.6/dist-packages (from traitlets-pcse==5.0.0.dev->pcse) (4.4.2)\n Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.6/dist-packages (from traitlets-pcse==5.0.0.dev->pcse) (0.2.0)\n Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from traitlets-pcse==5.0.0.dev->pcse) (1.15.0)\n Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.20->pcse) (2018.9)\n Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.20->pcse) (2.8.1)\n Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (2.10)\n Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (2020.6.20)\n Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (1.24.3)\n Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.0.0->pcse) (3.0.4)\n\n\n\n```python\n%matplotlib inline\nimport sys, os\nimport matplotlib\nmatplotlib.style.use(\"ggplot\")\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport yaml\nimport numpy as np\n\ndata_dir = os.path.join(os.getcwd(), \"data\")\nimport pcse\nprint(\"This notebook was built with:\")\nprint(\"python version: %s \" % sys.version)\nprint(\"PCSE version: %s\" % pcse.__version__)\n```\n\n This notebook was built with:\n python version: 3.6.9 (default, Jul 17 2020, 12:50:27) \n [GCC 8.4.0] \n PCSE version: 5.4.2\n\n\n## Reading model parameters\n### Crop parameters\n\nThe crop parameters consist of parameter names and the corresponding parameter values that are needed to parameterize the components of the crop simulation model. These are crop-specific values regarding phenology, assimilation, respiration, biomass partitioning, etc. The parameter file for sugar beet is taken from the crop files in the WOFOST Control Centre.\n\nAs many crop models in Wageningen were written in FORTRAN, the crop parameters for many models in Wageningen are often provided in the CABO format that could be read with the TTUTIL FORTRAN library. This CABO format will be gradually phased out and PCSE will move to a new format based on YAML, see [here for an example](https://github.com/ajwdewit/WOFOST_crop_parameters/blob/master/wheat.yaml). However, PCSE tries to be backward compatible as much as possible and provides the `CABOFileReader` for reading parameter files in CABO format. The `CABOFileReader` returns a dictionary with the parameter name/value pairs:\n\n\n```python\nfrom pcse.fileinput import CABOFileReader\ncropfile = os.path.join(data_dir, 'crop', 'SUG0601.crop')\ncropdata = CABOFileReader(cropfile)\n```\n\n\n```python\n#potato\nfrom pcse.fileinput import CABOFileReader\ncropfile_potato = os.path.join(data_dir, 'crop', 'POT701.CAB')\ncropdata_potato = CABOFileReader(cropfile_potato)\n```\n\n\n```python\n# Number of parameters for our crop \nlen(cropdata_potato)\n```\n\n\n\n\n 63\n\n\n\n### Soil parameters\nThe soildata dictionary provides the parameter name/value pairs related to the soil type and soil physical properties. The number of parameters is variable depending on the soil water balance type that is used for the simulation. For this example, we will use the water balance for freely draining soils and use the soil file for medium fine sand: `ec3.soil`. This file is also taken from the soil files in the [WOFOST Control Centre](http://www.wageningenur.nl/wofost).\n\n\n```python\nsoilfile = os.path.join(data_dir, 'soil', 'ec3.soil')\nsoildata = CABOFileReader(soilfile)\nprint(soildata)\n```\n\n ** $Id: ec3.new 1.2 1997/09/18 17:33:54 LEM release $\n **\n ** SOIL DATA FILE for use with WOFOST Version 5.0, June 1990\n **\n ** EC3-medium fine\n ------------------------------------\n SMW: 0.104 \n SMFCF: 0.3 \n SM0: 0.41 \n CRAIRC: 0.06 \n K0: 25.586 \n SOPE: 1.47 \n KSUB: 1.47 \n SPADS: 0.1 \n SPODS: 0.03 \n SPASS: 0.2 \n SPOSS: 0.05 \n DEFLIM: -0.3 \n RDMSOL: 120 \n SOLNAM: EC3-medium fine \n SMTAB: [-1.0, 0.41, 1.0, 0.398, 1.3, 0.389, 1.491, 0.38, 2.0, 0.34, 2.4, 0.287, 2.7, 0.241, 3.4, 0.148, 4.204, 0.104, 6.0, 0.09] \n CONTAB: [0.0, 1.408, 1.0, 0.167, 1.3, -0.215, 1.491, -0.638, 1.7, -0.854, 2.0, -1.155, 2.4, -1.796, 2.7, -2.26, 3.0, -2.745, 3.4, -3.357, 3.7, -3.824, 4.0, -4.276, 4.204, -4.678] \n \n\n\n### Site parameters\n\nThe site parameters provide ancillary parameters that are not related to the crop or the soil. Examples are the initial conditions of the water balance such as the initial soil moisture content (WAV) and the initial and maximum surface storage (SSI, SSMAX). Also the atmospheric $CO_{2}$ \nconcentration is a typical site parameter. For the moment, we can define these parameters directly on the Python commandline as a simple python dictionary. However, it is more convenient to use the `WOFOST71SiteDataProvider` that documents the site parameters and provides sensible defaults:\n\n\n```python\nfrom pcse.util import WOFOST71SiteDataProvider\nsitedata = WOFOST71SiteDataProvider(WAV=100, CO2=360)\nprint(sitedata)\n```\n\n {'IFUNRN': 0, 'NOTINF': 0, 'SSI': 0.0, 'SSMAX': 0.0, 'WAV': 100.0, 'SMLIM': 0.4, 'CO2': 360.0}\n\n\n### Packaging all parameters\nFinally, we need to pack the different sets of parameters into one variable using the `ParameterProvider`. This is needed because PCSE expects one variable that contains all parameter values. Using this approach has the additional advantage that parameter value can be easily overridden in case of running multiple simulations with slightly different parameter values:\n\n\n```python\nfrom pcse.base import ParameterProvider\nparameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata)\n```\n\n## Agromanagement\nThe agromanagement inputs provide the start date of the agricultural campaign, the start_date/start_type of the crop simulation, the end_date/end_type of the crop simulation and the maximum duration of the crop simulation. The latter is included to avoid unrealistically long simulations for example as a results of a too high temperature sum requirement.\n\nThe agromanagement inputs are defined with a special syntax called [YAML](http://yaml.org/) which allows to easily create more complex structures which is needed for defining the agromanagement. The agromanagement file for sugar beet in Wageningen `sugarbeet_calendar.agro` can be read with the `YAMLAgroManagementReader`:\n\n\n```python\nfrom pcse.fileinput import YAMLAgroManagementReader\n#crop rotation for Moscow region\nagromanagement_file = os.path.join(data_dir, 'agro', 'sugarbeet_calendar_Moscow_short.agro')\n#agromanagement_file = os.path.join(data_dir, 'agro', 'sugarbeet_calendar.agro')\nagromanagement = YAMLAgroManagementReader(agromanagement_file)\nprint(agromanagement)\n```\n\n !!python/object/new:pcse.fileinput.yaml_agro_loader.YAMLAgroManagementReader\n listitems:\n - 2019-06-01:\n CropCalendar:\n crop_end_date: 2019-10-15\n crop_end_type: harvest\n crop_name: sugar-beet\n crop_start_date: 2019-06-02\n crop_start_type: emergence\n max_duration: 300\n variety_name: sugar-beet-601\n StateEvents: null\n TimedEvents:\n - comment: All fertilizer amounts in kg/ha\n event_signal: apply_npk\n events_table:\n - 2019-06-22:\n K_amount: 122\n N_amount: 128\n P_amount: 25\n name: Timed N/P/K application table\n \n\n\nWe can create a crop rotation in the model\n\n\n\n```python\n\"\"\"\n- 2001-03-01:\n CropCalendar:\n crop_name: maize\n variety_name: fodder-maize\n crop_start_date: 2001-04-15\n crop_start_type: sowing\n crop_end_date:\n crop_end_type: maturity\n max_duration: 200\n TimedEvents:\n - event_signal: irrigate\n name: Timed irrigation events\n comment: All irrigation amounts in cm\n events_table:\n - 2001-06-01: {irrigation_amount: 2.0}\n - 2001-07-21: {irrigation_amount: 5.0}\n - 2001-08-18: {irrigation_amount: 3.0}\n - 2001-09-19: {irrigation_amount: 2.5}\n - event_signal: apply_npk\n name: Timed N/P/K application table\n comment: All fertilizer amounts in kg/ha\n events_table:\n - 2001-05-25: {N_amount : 50, P_amount: 25, K_amount: 22}\n - 2001-07-05: {N_amount : 70, P_amount: 35, K_amount: 32}\n StateEvents:null\n \"\"\"\n```\n\n\n```python\nK_kg = 60\nP_kg = 60\nN_kg = 120\nyear_date_1 = 2000\nyear_date=2017\nyaml_agro = f\"\"\"\n- {year_date}-05-01:\n CropCalendar:\n crop_name: 'sugar-beet'\n variety_name: 'sugar-beet-601'\n crop_start_date: {year_date}-05-20\n crop_start_type: sowing\n crop_end_date: \n crop_end_type: maturity\n max_duration: 250\n TimedEvents:\n - event_signal: apply_npk\n name: Timed N/P/K application table\n comment: All fertilizer amounts in kg/ha\n events_table:\n - {year_date}-06-22: {{N_amount : {N_kg}, P_amount: {P_kg}, K_amount: {K_kg}}}\n StateEvents: null\n\"\"\"\nagromanagement = yaml.safe_load(yaml_agro)\nprint(yaml_agro)\n#crop_end_date: {year_date_1}-11-15\n```\n\n \n - 2017-05-01:\n CropCalendar:\n crop_name: 'sugar-beet'\n variety_name: 'sugar-beet-601'\n crop_start_date: 2017-05-20\n crop_start_type: sowing\n crop_end_date: \n crop_end_type: maturity\n max_duration: 250\n TimedEvents:\n - event_signal: apply_npk\n name: Timed N/P/K application table\n comment: All fertilizer amounts in kg/ha\n events_table:\n - 2017-06-22: {N_amount : 120, P_amount: 60, K_amount: 60}\n StateEvents: null\n \n\n\n## Daily weather observations\nDaily weather variables are needed for running the simulation. There are several data providers in PCSE for reading weather data, see the section on [weather data providers](http://pcse.readthedocs.io/en/stable/reference_guide.html#weather-data-providers) to get an overview.\n\nFor this example we will use weather data from an excel file which provides daily weather data for Wageningen for the period 2004 to 2008. We will read the data from the file using the ExcelWeatherDataProvider:\n\n### NASA Weather Data Provider from NASA [DataBase](https://power.larc.nasa.gov/)\n\n\n```python\n#NASA Weather system\n\n#Sometimes it doesnot work, upload excel file\nfrom pcse.db import NASAPowerWeatherDataProvider\n```\n\n\n```python\n#export weather to list\n\nweather = NASAPowerWeatherDataProvider(51, 5, force_update=True)\n\n```\n\n## Importing, initializing and running a PCSE model\n\nInternally, PCSE uses a simulation engine to run a crop simulation. This engine takes a configuration file that specifies the components for the crop, the soil and the agromanagement that need to be used for the simulation. So any PCSE model can be started by importing the engine and initializing it with a given configuration file and the corresponding parameters, weather data and agromanagement.\n\nHowever, as many users of PCSE only need a particular configuration (for example the WOFOST model for potential production), preconfigured Engines are provided in `pcse.models`. For the sugarbeet example we will import the WOFOST model for water-limited simulation under freely draining soil conditions:\n\n\n```python\nfrom pcse.models import Wofost71_WLP_FD\nwofsim = Wofost71_WLP_FD(parameters, weather, agromanagement)\nwofsim.run_till_terminate()\ndf_results = pd.DataFrame(wofsim.get_output())\ndf_results = df_results.set_index(\"day\")\ndf_results.tail()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DVSLAITAGPTWSOTWLVTWSTTWRTTRARDSMWWLOW
day
2017-10-181.9740141.83503215026.92903111425.2363241576.8673082024.8253991510.6376320.077443120.00.28525734.230800
2017-10-191.9821861.76782715124.26388111512.8376891581.7340502029.6921421512.2959440.113898120.00.28464534.157386
2017-10-201.9912711.70613215205.83337611586.2502341585.8125252033.7706161513.7719290.071547120.00.28374134.048913
2017-10-211.9985361.64223215243.79972711620.4199511587.7108432035.6689341514.5036680.126996120.00.28468434.162043
2017-10-222.0000001.57917915324.91749911693.4259451591.7667312039.7248231516.1436760.071848120.00.28402934.083500
\n
\n\n\n\nWe can then run the simulation and retrieve the time series of daily simulation output using the get_output() method on the WOFOST object. Finally, we convert the simulation results to a pandas dataframe:\n\n\n```python\nsummary_output = wofsim.get_summary_output()\n```\n\n\n```python\nwofsim.get_summary_output()\n```\n\n\n\n\n [{'CTRAT': 17.589144084399933,\n 'DOA': datetime.date(2017, 7, 8),\n 'DOE': datetime.date(2017, 5, 27),\n 'DOH': None,\n 'DOM': datetime.date(2017, 10, 22),\n 'DOS': datetime.date(2017, 5, 20),\n 'DOV': None,\n 'DVS': 2.0,\n 'LAIMAX': 2.621559537235757,\n 'RD': 120.0,\n 'TAGP': 15324.917498780354,\n 'TWLV': 1591.7667312492454,\n 'TWRT': 1516.143676336077,\n 'TWSO': 11693.425944916902,\n 'TWST': 2039.7248226142065}]\n\n\n\n\n```python\nmsg = \"Reached maturity at {DOM} with total biomass {TAGP} kg/ha \"\\\n\"and a yield of {TWSO} kg/ha.\"\nprint(msg.format(**summary_output[0]))\n```\n\n Reached maturity at 2017-10-22 with total biomass 15324.917498780354 kg/ha and a yield of 11693.425944916902 kg/ha.\n\n\n# Sensitivity analysis\n\n\n```python\n!pip install SALib\n```\n\n Collecting SALib\n \u001b[?25l Downloading https://files.pythonhosted.org/packages/f7/33/cee4d64f7c40f33c08cf5ef5c9b1fb5e51f194b5deceefb5567112800b70/SALib-1.3.11.tar.gz (856kB)\n \u001b[K |████████████████████████████████| 860kB 3.3MB/s \n \u001b[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from SALib) (1.18.5)\n Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from SALib) (1.4.1)\n Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from SALib) (3.2.2)\n Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from SALib) (1.0.5)\n Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (2.8.1)\n Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (2.4.7)\n Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (0.10.0)\n Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->SALib) (1.2.0)\n Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->SALib) (2018.9)\n Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.1->matplotlib->SALib) (1.15.0)\n Building wheels for collected packages: SALib\n Building wheel for SALib (setup.py) ... \u001b[?25l\u001b[?25hdone\n Created wheel for SALib: filename=SALib-1.3.11-py2.py3-none-any.whl size=729665 sha256=93e720543725a20b1f31d6b4dcd5681574a59bb5c49e364a65b935ee9a92a0b0\n Stored in directory: /root/.cache/pip/wheels/62/ed/f9/a0b98754ffb2191b98324b96cbbeb1bd5d9598b39ab996b429\n Successfully built SALib\n Installing collected packages: SALib\n Successfully installed SALib-1.3.11\n\n\n\n```python\nfrom SALib.sample import saltelli\nfrom SALib.analyze import sobol\nfrom SALib.test_functions import Ishigami\nimport numpy as np\n```\n\n__Docs [SALib](https://salib.readthedocs.io/en/latest/#)__\n\nIn this example, we will perform a Sobol’ sensitivity analysis of the _Ishigami_ function, shown below. The _Ishigami_ function is commonly used to test uncertainty and sensitivity analysis methods because it exhibits strong nonlinearity and nonmonotonicity.\n\n$f(x)=\\sin \\left(x_{1}\\right)+ \\text{a}\\, \\operatorname{sin}^{2}\\left(x_{2}\\right)+ \\text{b}\\, x_{3}^{4} \\sin \\left(x_{1}\\right)$\n\n\n```python\nproblem = {\n 'num_vars': 3,\n 'names': ['x1', 'x2', 'x3'],\n 'bounds': [[-np.pi, np.pi]]*3\n}\n```\n\n\n```python\n# Generate samples\nparam_values = saltelli.sample(problem, 10, calc_second_order=True)\nparam_values.shape\n```\n\n\n\n\n (80, 3)\n\n\n\nHere, `param_values` is a NumPy matrix. If we run `param_values.shape`, we see that the matrix is **8000 by 3**. The Saltelli sampler generated 8000 samples. The Saltelli sampler generates $N∗(2D+2)$ samples, where in this example $N$ is 1000 (the argument we supplied) and $D$ is 3 (the number of model inputs). The keyword argument `calc_second_order=False` will exclude second-order indices, resulting in a smaller sample matrix with $N∗(D+2)$ rows instead.\n\n\n\n```python\n# Run model (example)\nY = Ishigami.evaluate(param_values)\n\n# Perform analysis\nSi = sobol.analyze(problem, Y, print_to_console=True)\n# Returns a dictionary with keys 'S1', 'S1_conf', 'ST', and 'ST_conf'\n# (first and total-order indices with bootstrap confidence intervals)\nT_Si, first_Si, (idx, second_Si) = sobol.Si_to_pandas_dict(Si)\n```\n\n Parameter S1 S1_conf ST ST_conf\n x1 -0.203434 0.660158 1.345837 2.206907\n x2 0.838328 0.650453 0.716922 0.567090\n x3 -0.592087 0.390549 0.459872 0.420236\n \n Parameter_1 Parameter_2 S2 S2_conf\n x1 x2 0.208665 1.159449\n x1 x3 1.165212 0.917190\n x2 x3 0.268558 0.759311\n\n\nConsider the model output as\n\\begin{eqnarray*}\nY=f(X)=f\\left(X_{1}, \\ldots, X_{p}\\right),\n\\end{eqnarray*}\nwhere $f$ in our case part of agro-model simulator, $X$ are $p$ varied input parameters and $Y$ is the predicted output. Following the techniques by Sobol we represent the multi-variate random function $f$ using Hoeffding decomposition:\n\\begin{equation}\nf(X_1,\\dots,X_p) = f_0 + \\sum_i^p f_i + \\sum_i^p\\sum_{j>i}^p f_{ij} + \\dots + f_{1\\dots p},\n\\end{equation}\nwhere $f_0$ is a constant term, $f_i = f_i(X_i)$ denotes main effects, $f_{ij} = f_{ij}(X_i, X_j)$ and others describe higher-order interactions. These terms can be written as\n\\begin{equation*}\n\\begin{split}\nf_0 &= E(Y),\\\\\nf_i &= E_{X_{\\sim i}}(Y | X_i) - E(Y),\\\\\nf_{ij} &= E_{X_{\\sim ij}}(Y | X_i, X_j) - f_i - f_j - f_0,\\\\\n\\dots\n\\end{split}\n\\end{equation*}\nwhere $E$ is mathematical expectation and $X_{\\sim i}$ denotes all parameters except $i^\\text{th}$. Under the assumption that the input parameters are independent, total variance $V(Y)$ of the crop yield can be decomposed as follows:\n\\begin{equation*}\nV(Y) = \\sum_i^p V_i + \\sum_i^p\\sum_{j>i}^p V_{ij} + \\dots + V_{12\\dots p},\n\\end{equation*}\nwhere partial variances are\n\\begin{equation*}\n\\begin{split}\nV_i &= V[f_i(X_i)] = V_{X_i}\\left[E_{X_{\\sim i}}(Y | X_i)\\right],\\\\\nV_{ij} &= V[f_{ij}(X_i,X_j)] = V_{X_iX_j}\\left[E_{X_{\\sim ij}}(Y | X_i, X_j)\\right] - V_i - V_j,\\\\\n\\dots\n\\end{split}\n\\end{equation*}\n\n## Sobol index (first order, second order, total index)\n\nThis way, sensitivity indices (SI) can be introduced as \n\\begin{equation}\n\\Large\nS_i = \\frac{V_i}{V(Y)},~S_{ij} = \\frac{V_{ij}}{V(Y)},~\\dots\n\\end{equation}\nIn order to incorporate all of the interactions for a particular parameter, one can compute the total effect index:\n\\begin{equation}\nS_{T_i} = \\frac{E_{X_{\\sim i}}\\left[V_{X_i}(Y|X_{\\sim i})\\right]}{V(Y)} = 1 - \\frac{V_{X_{\\sim i}}\\left[E_{X_i}(Y | X_{\\sim i})\\right]}{V(Y)}\n\\end{equation}\n\n\nFrom this assumption we can conclude:\n\\begin{equation}\n\\Large\n0 \\leq S_i \\leq S_{T_i} \\leq 1\n\\end{equation}\n\n## Sobol’ Sequences versus Random numbers and regular grid\n\n\n\n\n## Modern Quasi-Random Sequences\n\n\n\n\n\nMore -\n* [Wiki](https://en.wikipedia.org/wiki/Sobol_sequence)\n* [Habr](https://habr.com/ru/post/440892/)\n* Feature selection [Skoltech ML 2020](https://github.com/adasegroup/ML2020_lectures/blob/master/lecture9/Lecture_9_Model_Feature_Selection_Sensitivity.pdf)\n\n# Sensitivity analysis of WOFOST model \n\n\n\n## Install modules \n\n\n```python\n from SALib.sample import saltelli\n from SALib.analyze import sobol\n from SALib.test_functions import Ishigami\n import numpy as np\n import pandas as pd\n```\n\n## Parameters\n\n\n```python\nNPK = {\n 'num_vars':3,\n 'names':['N_kg', 'P_kg', 'K_kg'],\n 'bounds':[[30., 60.],\n [60., 90.],\n [100., 130.]]\n}\n```\n\n\n```python\nSoil_parameters = {\n 'num_vars':5,\n 'names':['SMV', 'SMFCF', 'SM0', 'CRAIRC', 'K0'],\n 'bounds':[[0.7, 1.3],\n [0.1, 0.5],\n [0.2, 0.6],\n [0.04, 0.08],\n [22.5, 27.5]]}\n```\n\n## Generate input parameters\n\n\n\n\n\n```python\nparam_values = saltelli.sample(Soil_parameters, 10)\n```\n\n$n = N \\times (D \\times 2 +2)$\n\n\n```python\nparam_values.shape\n```\n\n\n\n\n (120, 5)\n\n\n\n## Loop for yield prediction\n\n\n```python\nfrom pcse.fileinput import YAMLAgroManagementReader\nagromanagement_file = os.path.join(data_dir, 'agro', './sugarbeet_calendar.agro')\nagromanagement = YAMLAgroManagementReader(agromanagement_file)\n#print(agromanagement)\nSoil_parameters = {\n 'num_vars':5,\n 'names':['SMV', 'SMFCF', 'SM0', 'CRAIRC', 'K0'],\n 'bounds':[[0.7, 1.3],\n [0.1, 0.5],\n [0.2, 0.6],\n [0.04, 0.08],\n [22.5, 27.5]]}\nparam_values = saltelli.sample(Soil_parameters, N=10, calc_second_order=True)\n```\n\nSoil parameters in [PCSE model](https://pcse.readthedocs.io/en/stable/code.html?highlight=K0#pcse.soil.WaterbalanceFD) \n\n\n```python\ndef sensitivity_soil(soil_parameters):\n SMV, SMFCF, SM0, CRAIRC, K0 = soil_parameters \n soildata['SMV'] = SMV\n soildata['SMFCF'] = SMFCF\n soildata['SM0'] = SM0\n soildata['CRAIRC'] = CRAIRC\n soildata['K0'] = K0\n parameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata)\n wofsim = Wofost71_WLP_FD(parameters, wdp, agromanagement)\n wofsim.run_till_terminate()\n #df_results = pd.DataFrame(wofsim.get_output())\n #df_results = df_results.set_index(\"day\")\n #df_results.tail()\n summary_output = wofsim.get_summary_output()\n yield_list.append(summary_output[0]['TWSO'])\n```\n\n\n```python\n%%time\nyield_list = []\nparam_values = saltelli.sample(Soil_parameters, 10, calc_second_order=True)\nfor step in range(len(param_values)):\n sensitivity_soil(param_values[step])\n print(param_values[step])\n```\n\n [ 0.83183594 0.13867188 0.40742187 0.06707031 23.90136719]\n [ 1.24433594 0.13867188 0.40742187 0.06707031 23.90136719]\n [ 0.83183594 0.11835938 0.40742187 0.06707031 23.90136719]\n [ 0.83183594 0.13867188 0.55976563 0.06707031 23.90136719]\n [ 0.83183594 0.13867188 0.40742187 0.06003906 23.90136719]\n [ 0.83183594 0.13867188 0.40742187 0.06707031 22.84667969]\n [ 0.83183594 0.11835938 0.55976563 0.06003906 22.84667969]\n [ 1.24433594 0.13867188 0.55976563 0.06003906 22.84667969]\n [ 1.24433594 0.11835938 0.40742187 0.06003906 22.84667969]\n [ 1.24433594 0.11835938 0.55976563 0.06707031 22.84667969]\n [ 1.24433594 0.11835938 0.55976563 0.06003906 23.90136719]\n [ 1.24433594 0.11835938 0.55976563 0.06003906 22.84667969]\n [ 1.13183594 0.33867188 0.20742188 0.04707031 26.40136719]\n [ 0.94433594 0.33867188 0.20742188 0.04707031 26.40136719]\n [ 1.13183594 0.31835938 0.20742188 0.04707031 26.40136719]\n [ 1.13183594 0.33867188 0.35976562 0.04707031 26.40136719]\n [ 1.13183594 0.33867188 0.20742188 0.04003906 26.40136719]\n [ 1.13183594 0.33867188 0.20742188 0.04707031 25.34667969]\n [ 1.13183594 0.31835938 0.35976562 0.04003906 25.34667969]\n [ 0.94433594 0.33867188 0.35976562 0.04003906 25.34667969]\n [ 0.94433594 0.31835938 0.20742188 0.04003906 25.34667969]\n [ 0.94433594 0.31835938 0.35976562 0.04707031 25.34667969]\n [ 0.94433594 0.31835938 0.35976562 0.04003906 26.40136719]\n [ 0.94433594 0.31835938 0.35976562 0.04003906 25.34667969]\n [ 1.28183594 0.23867188 0.50742187 0.07707031 25.15136719]\n [ 0.79433594 0.23867188 0.50742187 0.07707031 25.15136719]\n [ 1.28183594 0.21835938 0.50742187 0.07707031 25.15136719]\n [ 1.28183594 0.23867188 0.25976562 0.07707031 25.15136719]\n [ 1.28183594 0.23867188 0.50742187 0.05003906 25.15136719]\n [ 1.28183594 0.23867188 0.50742187 0.07707031 26.59667969]\n [ 1.28183594 0.21835938 0.25976562 0.05003906 26.59667969]\n [ 0.79433594 0.23867188 0.25976562 0.05003906 26.59667969]\n [ 0.79433594 0.21835938 0.50742187 0.05003906 26.59667969]\n [ 0.79433594 0.21835938 0.25976562 0.07707031 26.59667969]\n [ 0.79433594 0.21835938 0.25976562 0.05003906 25.15136719]\n [ 0.79433594 0.21835938 0.25976562 0.05003906 26.59667969]\n [ 0.98183594 0.43867188 0.30742188 0.05707031 22.65136719]\n [ 1.09433594 0.43867188 0.30742188 0.05707031 22.65136719]\n [ 0.98183594 0.41835937 0.30742188 0.05707031 22.65136719]\n [ 0.98183594 0.43867188 0.45976563 0.05707031 22.65136719]\n [ 0.98183594 0.43867188 0.30742188 0.07003906 22.65136719]\n [ 0.98183594 0.43867188 0.30742188 0.05707031 24.09667969]\n [ 0.98183594 0.41835937 0.45976563 0.07003906 24.09667969]\n [ 1.09433594 0.43867188 0.45976563 0.07003906 24.09667969]\n [ 1.09433594 0.41835937 0.30742188 0.07003906 24.09667969]\n [ 1.09433594 0.41835937 0.45976563 0.05707031 24.09667969]\n [ 1.09433594 0.41835937 0.45976563 0.07003906 22.65136719]\n [ 1.09433594 0.41835937 0.45976563 0.07003906 24.09667969]\n [ 0.90683594 0.28867188 0.25742188 0.05207031 23.27636719]\n [ 1.16933594 0.28867188 0.25742188 0.05207031 23.27636719]\n [ 0.90683594 0.26835938 0.25742188 0.05207031 23.27636719]\n [ 0.90683594 0.28867188 0.20976563 0.05207031 23.27636719]\n [ 0.90683594 0.28867188 0.25742188 0.05503906 23.27636719]\n [ 0.90683594 0.28867188 0.25742188 0.05207031 25.97167969]\n [ 0.90683594 0.26835938 0.20976563 0.05503906 25.97167969]\n [ 1.16933594 0.28867188 0.20976563 0.05503906 25.97167969]\n [ 1.16933594 0.26835938 0.25742188 0.05503906 25.97167969]\n [ 1.16933594 0.26835938 0.20976563 0.05207031 25.97167969]\n [ 1.16933594 0.26835938 0.20976563 0.05503906 23.27636719]\n [ 1.16933594 0.26835938 0.20976563 0.05503906 25.97167969]\n [ 1.20683594 0.48867187 0.45742187 0.07207031 25.77636719]\n [ 0.86933594 0.48867187 0.45742187 0.07207031 25.77636719]\n [ 1.20683594 0.46835938 0.45742187 0.07207031 25.77636719]\n [ 1.20683594 0.48867187 0.40976563 0.07207031 25.77636719]\n [ 1.20683594 0.48867187 0.45742187 0.07503906 25.77636719]\n [ 1.20683594 0.48867187 0.45742187 0.07207031 23.47167969]\n [ 1.20683594 0.46835938 0.40976563 0.07503906 23.47167969]\n [ 0.86933594 0.48867187 0.40976563 0.07503906 23.47167969]\n [ 0.86933594 0.46835938 0.45742187 0.07503906 23.47167969]\n [ 0.86933594 0.46835938 0.40976563 0.07207031 23.47167969]\n [ 0.86933594 0.46835938 0.40976563 0.07503906 25.77636719]\n [ 0.86933594 0.46835938 0.40976563 0.07503906 23.47167969]\n [ 1.05683594 0.18867188 0.35742188 0.04207031 27.02636719]\n [ 0.71933594 0.18867188 0.35742188 0.04207031 27.02636719]\n [ 1.05683594 0.16835938 0.35742188 0.04207031 27.02636719]\n [ 1.05683594 0.18867188 0.50976562 0.04207031 27.02636719]\n [ 1.05683594 0.18867188 0.35742188 0.06503906 27.02636719]\n [ 1.05683594 0.18867188 0.35742188 0.04207031 24.72167969]\n [ 1.05683594 0.16835938 0.50976562 0.06503906 24.72167969]\n [ 0.71933594 0.18867188 0.50976562 0.06503906 24.72167969]\n [ 0.71933594 0.16835938 0.35742188 0.06503906 24.72167969]\n [ 0.71933594 0.16835938 0.50976562 0.04207031 24.72167969]\n [ 0.71933594 0.16835938 0.50976562 0.06503906 27.02636719]\n [ 0.71933594 0.16835938 0.50976562 0.06503906 24.72167969]\n [ 0.75683594 0.38867188 0.55742187 0.06207031 24.52636719]\n [ 1.01933594 0.38867188 0.55742187 0.06207031 24.52636719]\n [ 0.75683594 0.36835938 0.55742187 0.06207031 24.52636719]\n [ 0.75683594 0.38867188 0.30976562 0.06207031 24.52636719]\n [ 0.75683594 0.38867188 0.55742187 0.04503906 24.52636719]\n [ 0.75683594 0.38867188 0.55742187 0.06207031 27.22167969]\n [ 0.75683594 0.36835938 0.30976562 0.04503906 27.22167969]\n [ 1.01933594 0.38867188 0.30976562 0.04503906 27.22167969]\n [ 1.01933594 0.36835938 0.55742187 0.04503906 27.22167969]\n [ 1.01933594 0.36835938 0.30976562 0.06207031 27.22167969]\n [ 1.01933594 0.36835938 0.30976562 0.04503906 24.52636719]\n [ 1.01933594 0.36835938 0.30976562 0.04503906 27.22167969]\n [ 0.73808594 0.17617188 0.21992188 0.05832031 25.62011719]\n [ 0.85058594 0.17617188 0.21992188 0.05832031 25.62011719]\n [ 0.73808594 0.48085937 0.21992188 0.05832031 25.62011719]\n [ 0.73808594 0.17617188 0.52226562 0.05832031 25.62011719]\n [ 0.73808594 0.17617188 0.21992188 0.04128906 25.62011719]\n [ 0.73808594 0.17617188 0.21992188 0.05832031 24.56542969]\n [ 0.73808594 0.48085937 0.52226562 0.04128906 24.56542969]\n [ 0.85058594 0.17617188 0.52226562 0.04128906 24.56542969]\n [ 0.85058594 0.48085937 0.21992188 0.04128906 24.56542969]\n [ 0.85058594 0.48085937 0.52226562 0.05832031 24.56542969]\n [ 0.85058594 0.48085937 0.52226562 0.04128906 25.62011719]\n [ 0.85058594 0.48085937 0.52226562 0.04128906 24.56542969]\n [ 1.03808594 0.37617188 0.41992188 0.07832031 23.12011719]\n [ 1.15058594 0.37617188 0.41992188 0.07832031 23.12011719]\n [ 1.03808594 0.28085938 0.41992188 0.07832031 23.12011719]\n [ 1.03808594 0.37617188 0.32226562 0.07832031 23.12011719]\n [ 1.03808594 0.37617188 0.41992188 0.06128906 23.12011719]\n [ 1.03808594 0.37617188 0.41992188 0.07832031 27.06542969]\n [ 1.03808594 0.28085938 0.32226562 0.06128906 27.06542969]\n [ 1.15058594 0.37617188 0.32226562 0.06128906 27.06542969]\n [ 1.15058594 0.28085938 0.41992188 0.06128906 27.06542969]\n [ 1.15058594 0.28085938 0.32226562 0.07832031 27.06542969]\n [ 1.15058594 0.28085938 0.32226562 0.06128906 23.12011719]\n [ 1.15058594 0.28085938 0.32226562 0.06128906 27.06542969]\n CPU times: user 1min 21s, sys: 229 ms, total: 1min 21s\n Wall time: 1min 21s\n\n\n\n```python\nnp_yield = np.array(yield_list)\nSi = sobol.analyze(Soil_parameters, np_yield, print_to_console=False)\n```\n\n\n```python\nSi_dict = dict(Si) \nSi_df = pd.DataFrame()\nSi_df = Si_df.append(pd.Series(Si_dict['S1']), ignore_index=True)\nSi_df = Si_df.append(pd.Series(Si_dict['ST']), ignore_index=True)\nSi_df = Si_df.append(pd.Series(Si_dict['S1_conf']), ignore_index=True)\nSi_df = Si_df.append(pd.Series(Si_dict['ST_conf']), ignore_index=True)\nSi_df = Si_df.T\nSi_df.columns = ['Si', 'ST', 'Si_conf', 'ST_conf']\nSi_df.rename(index={0:'SMV',1:'SMFCF', 2:'SM0', 3:'CRAIRC', 4:'K0'}, inplace=True)\nSi_df\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
SiSTSi_confST_conf
SMV0.0000000.0000000.0000000.000000
SMFCF-0.0774170.2848780.8394560.638290
SM00.2675040.3814370.6934090.688329
CRAIRC0.0000000.0000000.0000000.000000
K00.0000000.0000000.0000000.000000
\n
\n\n\n\nIs it ok?\n\n\n\\begin{equation}\n\\Large\n0 \\leq S_i \\leq S_{T_i} \\leq 1\n\\end{equation}\n\n### For 5 years\n\n\n```python\ndef sensitivity_weather(year):\n K_kg = 60\n P_kg = 60\n N_kg = 120\n year_date=year\n print(year)\n print(year_date)\n yaml_agro = f\"\"\"\n - {year_date}-06-01:\n CropCalendar:\n crop_name: 'sugar-beet'\n variety_name: 'sugar-beet-601'\n crop_start_date: {year_date}-06-02\n crop_start_type: emergence\n crop_end_date: {year_date}-10-15\n crop_end_type: harvest\n max_duration: 300\n TimedEvents:\n - event_signal: apply_npk\n name: Timed N/P/K application table\n comment: All fertilizer amounts in kg/ha\n events_table:\n - {year_date}-06-22: {{N_amount : {N_kg}, P_amount: {P_kg}, K_amount: {K_kg}}}\n StateEvents: null\n \"\"\"\n agromanagement = yaml.safe_load(yaml_agro)\n parameters = ParameterProvider(cropdata=cropdata, soildata=soildata, sitedata=sitedata)\n wofsim = Wofost71_WLP_FD(parameters, moscow_weather, agromanagement)\n wofsim.run_till_terminate()\n summary_output = wofsim.get_summary_output()\n yield_list_weather.append(summary_output[0]['TWSO'])\n```\n\n## Visualizing simulation results\n\nFinally, we can generate some figures of WOFOST variables such as the development (DVS), total biomass (TAGP), leaf area index (LAI) and root-zone soil moisture (SM) using the MatPlotLib plotting package:\n\n\n```python\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,10))\nfor var, ax in zip([\"DVS\", \"TWSO\", \"LAI\", \"SM\"], axes.flatten()):\n ax.plot_date(df_results.index, df_results[var], 'b-')\n ax.set_title(var)\nfig.autofmt_xdate()\n```\n\n# Visualization for sensitivity analysis\n\nPlots by [Water programming group](https://waterprogramming.wordpress.com/2019/08/27/a-python-implementation-of-grouped-radial-convergence-plots-to-visualize-sobol-sensitivity-analysis-results/)\n\nHow to repeat: [Repo of SampleVIS](https://github.com/charlesrouge/SampleVis)\n\n\n```python\nimport numpy as np\nfrom SALib.analyze import sobol\nfrom SALib.sample import saltelli\nfrom fishery import fish_game\nimport matplotlib.pyplot as plt\nimport itertools\nimport math\n```\n\n### Why number of samples is important?\n\n\n```python\n# Set up dictionary with system parameters\nproblem = {\n 'num_vars': 6,\n 'names': ['a', 'b', 'c','h',\n 'K','m'],\n 'bounds': [[ 0.002, 2],\n [0.005, 1],\n [0.2, 1],\n [0.001, 1],\n [100, 5000],\n [0.1, 1.5]]\n}\n\n# Array with n's to use\nnsamples = np.arange(50, 500, 50)\n\n# Arrays to store the index estimates\nS1_estimates = np.zeros([problem['num_vars'],len(nsamples)])\nST_estimates = np.zeros([problem['num_vars'],len(nsamples)])\n\n# Loop through all n values, create sample, evaluate model and estimate S1 & ST\nfor i in range(len(nsamples)):\n print('n= '+ str(nsamples[i]))\n # Generate samples\n sampleset = saltelli.sample(problem, nsamples[i],calc_second_order=False)\n # Run model for all samples\n output = [fish_game(*sampleset[j,:]) for j in range(len(sampleset))]\n # Perform analysis\n results = sobol.analyze(problem, np.asarray(output), calc_second_order=False,print_to_console=False)\n # Store estimates\n ST_estimates[:,i]=results['ST']\n S1_estimates[:,i]=results['S1']\n\nnp.save('ST_estimates.npy', ST_estimates)\nnp.save('S1_estimates.npy', S1_estimates)\n\nS1_estimates = np.load('S1_estimates.npy')\nST_estimates = np.load('ST_estimates.npy')\n\n# Generate figure showing evolution of indices\nfig = plt.figure(figsize=(18,9))\nax1 = fig.add_subplot(1,2,1)\nhandles = []\nfor j in range(problem['num_vars']):\n handles += ax1.plot(nsamples, S1_estimates[j,:], linewidth=5)\nax1.set_title('Evolution of S1 index estimates', fontsize=20)\nax1.set_ylabel('S1', fontsize=18)\nax1.set_xlabel('Number of samples (n)', fontsize=18)\nax1.tick_params(axis='both', which='major', labelsize=14)\nax2 = fig.add_subplot(1,2,2)\nfor j in range(problem['num_vars']):\n ax2.plot(nsamples, ST_estimates[j,:], linewidth=5)\nax2.set_title('Evolution of ST index estimates', fontsize=20)\nax2.set_ylabel('ST', fontsize=18)\nax2.tick_params(axis='both', which='major', labelsize=14)\nax2.set_xlabel('Number of samples (n)', fontsize=18)\nfig.legend(handles, problem['names'], loc = 'right', fontsize=11)\nplt.show()\n#plt.savefig('indexevolution.png')\n\n# Calculate parameter rankings\nS1_ranks = np.zeros_like(S1_estimates)\nST_ranks = np.zeros_like(ST_estimates)\nfor i in range(len(nsamples)):\n orderS1 = np.argsort(S1_estimates[:,i])\n orderST = np.argsort(ST_estimates[:,i])\n S1_ranks[:,i] = orderS1.argsort()\n ST_ranks[:,i] = orderST.argsort()\n \n# Generate figure showing evolution of ranks\nfig = plt.figure(figsize=(18,9))\nax1 = fig.add_subplot(1,2,1)\nhandles = []\nfor j in range(problem['num_vars']):\n handles += ax1.plot(nsamples, S1_ranks[j,:], linewidth=3)\nax1.set_title('Parameter ranking based on S1', fontsize=20)\nax1.set_ylabel('S1', fontsize=18)\nax1.set_xlabel('Number of samples (n)', fontsize=18)\nax1.set_yticklabels(np.arange(problem['num_vars']+1, 0, -1))\nax1.tick_params(axis='both', which='major', labelsize=14)\nax2 = fig.add_subplot(1,2,2)\nfor j in range(problem['num_vars']):\n ax2.plot(nsamples, ST_ranks[j,:], linewidth=3)\nax2.set_title('Parameter ranking based on ST', fontsize=20)\nax2.set_ylabel('ST', fontsize=18)\nax2.set_yticklabels(np.arange(problem['num_vars']+1, 0, -1))\nax2.tick_params(axis='both', which='major', labelsize=14)\nax2.set_xlabel('Number of samples (n)', fontsize=18)\nfig.legend(handles, problem['names'], loc = 'right', fontsize=14)\n#plt.show()\n#plt.savefig('rankingevolution.png')\n```\n\n## Radial plot for SA\n\n\n```python\nimport numpy as np\nimport itertools\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport math\nfrom numpy import genfromtxt\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nsns.set_style('whitegrid', {'axes_linewidth': 0, 'axes.edgecolor': 'white'})\n```\n\n## Plot function\n\n\n```python\ndef is_significant(value, confidence_interval, threshold=\"conf\"):\n if threshold == \"conf\":\n return value - abs(confidence_interval) > 0\n else:\n return value - abs(float(threshold)) > 0\n \ndef grouped_radial(SAresults, parameters, radSc=2.0, scaling=1, widthSc=0.5, STthick=1, varNameMult=1.3, colors=None, groups=None, gpNameMult=1.5, threshold=\"conf\"):\n # Derived from https://github.com/calvinwhealton/SensitivityAnalysisPlots\n fig, ax = plt.subplots(1, 1)\n color_map = {}\n \n # initialize parameters and colors\n if groups is None:\n \n if colors is None:\n colors = [\"k\"]\n \n for i, parameter in enumerate(parameters):\n color_map[parameter] = colors[i % len(colors)]\n else: \n if colors is None:\n colors = sns.color_palette(\"deep\", max(3, len(groups)))\n \n for i, key in enumerate(groups.keys()):\n #parameters.extend(groups[key])\n \n for parameter in groups[key]:\n color_map[parameter] = colors[i % len(colors)]\n \n n = len(parameters)\n angles = radSc*math.pi*np.arange(0, n)/n\n x = radSc*np.cos(angles)\n y = radSc*np.sin(angles)\n \n # plot second-order indices\n for i, j in itertools.combinations(range(n), 2):\n #key1 = parameters[i]\n #key2 = parameters[j]\n \n if is_significant(SAresults[\"S2\"][i][j], SAresults[\"S2_conf\"][i][j], threshold):\n angle = math.atan((y[j]-y[i])/(x[j]-x[i]))\n \n if y[j]-y[i] < 0:\n angle += math.pi\n \n line_hw = scaling*(max(0, SAresults[\"S2\"][i][j])**widthSc)/2\n \n coords = np.empty((4, 2))\n coords[0, 0] = x[i] - line_hw*math.sin(angle)\n coords[1, 0] = x[i] + line_hw*math.sin(angle)\n coords[2, 0] = x[j] + line_hw*math.sin(angle)\n coords[3, 0] = x[j] - line_hw*math.sin(angle)\n coords[0, 1] = y[i] + line_hw*math.cos(angle)\n coords[1, 1] = y[i] - line_hw*math.cos(angle)\n coords[2, 1] = y[j] - line_hw*math.cos(angle)\n coords[3, 1] = y[j] + line_hw*math.cos(angle)\n \n ax.add_artist(plt.Polygon(coords, color=\"0.75\"))\n \n # plot total order indices\n for i, key in enumerate(parameters):\n if is_significant(SAresults[\"ST\"][i], SAresults[\"ST_conf\"][i], threshold):\n ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults[\"ST\"][i]**widthSc)/2, color='w'))\n ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults[\"ST\"][i]**widthSc)/2, lw=STthick, color='0.4', fill=False))\n \n # plot first-order indices\n for i, key in enumerate(parameters):\n if is_significant(SAresults[\"S1\"][i], SAresults[\"S1_conf\"][i], threshold):\n ax.add_artist(plt.Circle((x[i], y[i]), scaling*(SAresults[\"S1\"][i]**widthSc)/2, color='0.4'))\n \n # add labels\n for i, key in enumerate(parameters): \n ax.text(varNameMult*x[i], varNameMult*y[i], key, ha='center', va='center',\n rotation=angles[i]*360/(2*math.pi) - 90,\n color=color_map[key])\n \n if groups is not None:\n for i, group in enumerate(groups.keys()):\n print(group)\n group_angle = np.mean([angles[j] for j in range(n) if parameters[j] in groups[group]])\n \n ax.text(gpNameMult*radSc*math.cos(group_angle), gpNameMult*radSc*math.sin(group_angle), group, ha='center', va='center',\n rotation=group_angle*360/(2*math.pi) - 90,\n color=colors[i % len(colors)])\n \n ax.set_facecolor('white')\n ax.set_xticks([])\n ax.set_yticks([])\n# ax.\n plt.axis('equal')\n plt.axis([-2*radSc, 2*radSc, -2*radSc, 2*radSc])\n #plt.show()\n \n \n return fig\n```\n\n## Range of soil parameters\n\n\n```python\nproblem = {\n 'num_vars':6,\n 'names':['SOC', 'Sand', 'Clay', 'pH', 'CN', 'BD'],\n 'bounds':[[2.58, 6.20],\n [0.01, 0.30],\n [0.01, 0.30],\n [4.6, 6.9],\n [10.9, 12.4],\n [900, 1350]]\n}\n```\n\n\n```python\n#names for csv files\nlist_of_csv=['soybean-000-2015.csv', 'sugar-beet-2011.csv', 'sugar-beet-2017.csv',\n'spring-barley-2012.csv', 'sugar-beet-2014.csv']\nlist_of_names=['soybean-000-2015', 'sugar-beat-2011', 'sugar-beat-2017',\n'spring-barley-2012', 'sugar-beat-2014']\nlist_of_totals=['total_SI_'+x for x in list_of_names]\nlist_of_first=['fisrt_SI_'+x for x in list_of_names]\nlist_of_second=['second_SI_'+x for x in list_of_names]\nlist_of_SI=['SI_'+x for x in list_of_names]\n```\n\n\n```python\nfor j, i in enumerate(list_of_csv):\n all_data_csv = genfromtxt('./'+str(i), delimiter=',')\n output = all_data_csv[:,2]\n print(i)\n list_of_SI[j] = sobol.analyze(problem, output, calc_second_order=True, conf_level=0.95, print_to_console=False)\n```\n\n soybean-000-2015.csv\n sugar-beet-2011.csv\n sugar-beet-2017.csv\n spring-barley-2012.csv\n sugar-beet-2014.csv\n\n\n\n```python\ngroups={\"Soil physics\" : [\"Sand\", \"Clay\", \"BD\"],\n \"Soil chemistry\" : [\"pH\", \"SOC\", \"CN\"]}\n \nfig = grouped_radial(list_of_SI[4], ['BD', 'Sand', 'Clay', 'pH', 'CN', 'SOC'], groups=groups, threshold=0.001)\nred_patch = mpatches.Patch(color='red', label='The red data')\nplt.title(list_of_names[4], loc='left')\n\nplt.show()\n```\n\n\n\n\n## Homework\n\n__[Tasks](https://skoltech-my.sharepoint.com/:w:/g/personal/mikhail_gasanov_skoltech_ru/EeTPQxbrzVdPqnSENKYyoTUBay1RDYgMMW3GO3qFT2ge5g?e=4hk45V)__\n\nUsefull\n\n__SA and UQ__\n\n\n1) [Rhodium project](https://github.com/Project-Platypus/Rhodium.git)\n\n\n2) [SALib](https://github.com/SALib/SALib)\n\n__Model__\n\n3) [PCSE](https://pcse.readthedocs.io/en/stable/index.html)\n\n4) How to install PCSE at local machine\n `conda env create -f` [py3_pcse.yml](https://github.com/mishagrol/Seminar_Sobol/blob/master/py3_pcse.yml)\n\nАny questions - \n\nTelegram - `@misha_grol`\n\nPart 1 – Crop Yield Prediction (PCSE, MONICA) \n\nYou can use the seminars’ colab: \n\n“https://colab.research.google.com/drive/1j4AHD8KkTRThPuNsQzQFWYSJtptQ6bUA” \n\n1) Assess the yield of one of the crops for the Moscow region over several years (potatoes, sugar beets for 2-3 years) \n\n Crop - (https://github.com/mishagrol/Seminar_Sobol/tree/master/data/crop) \n\n Soil - (https://github.com/mishagrol/Seminar_Sobol/tree/master/data/soil) \n\n Weather - NASAdataprovider in PCSE (https://pcse.readthedocs.io/en/stable/code.html?highlight=NASA#pcse.db.NASAPowerWeatherDataProvider) \n\n Agromanagement - (https://github.com/mishagrol/Seminar_Sobol/blob/master/data/agro/sugarbeet_calendar_Moscow_short.agro) \n\nPart 2 – Sensitivity Analysis (SALib) \n\n1) Perform sensitivity analysis of one of the model blocks (crop, soil, agromanagement *) with SALib. You can choose one of the methods that you consider necessary (Sobol, FAST, ...). \n\n Generate samples – In report provide the size of the resulting matrix and the sample size (N) \n\n Conduct parameter sensitivity analysis - In report provide S1 and ST indices. \n\n2) Generate plots (Hist, Radial convergence plot, etc.) \n\n*3) Estimate the required number of simulations to obtain reliable values of the sensitivity indices. Try to estimate the sample size at the confidence interval of the sensitivity indices. \n\n* Please note that working with discrete data can cause certain difficulties. \n\n#Agro Hack https://agro-code.ru/\n\n### bonus\n\n__Morris method__\n\n\nGenerate a sample using the Method of Morris\n\nThree variants of Morris' sampling for elementary effects is supported:\n\n- Vanilla Morris\n- Optimised trajectories when ``optimal_trajectories=True`` (using\n Campolongo's enhancements from 2007 and optionally Ruano's enhancement\n from 2012; ``local_optimization=True``)\n- Groups with optimised trajectories when ``optimal_trajectories=True`` and\n the problem definition specifies groups (note that ``local_optimization``\n must be ``False``)\n\nAt present, optimised trajectories is implemented using either a brute-force\napproach, which can be very slow, especially if you require more than four\ntrajectories, or a local method based which is much faster. Both methods now\nimplement working with groups of factors.\n\nNote that the number of factors makes little difference,\nbut the ratio between number of optimal trajectories and the sample size\nresults in an exponentially increasing number of scores that must be\ncomputed to find the optimal combination of trajectories. We suggest going\nno higher than 4 from a pool of 100 samples with the brute force approach.\nWith local_optimization = True (which is default),\nit is possible to go higher than the previously suggested 4 from 100.\n\n\n\n\n```python\nimport sys\n\nfrom SALib.analyze import morris\nfrom SALib.sample.morris import sample\nfrom SALib.test_functions import Sobol_G\nfrom SALib.util import read_param_file\nfrom SALib.plotting.morris import horizontal_bar_plot, covariance_plot, \\\n sample_histograms\nimport matplotlib.pyplot as plt\n\n#sys.path.append('../..')\n\n# Read the parameter range file and generate samples\n#problem = read_param_file('/Users/mikhailgasanov/Documents/GIT/SALib/src/SALib/test_functions/params/Sobol_G.txt')\n# or define manually without a parameter file:\nproblem = {\n 'num_vars': 8,\n 'names': ['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8'],\n 'groups': None,\n 'bounds': [[0.0, 1.0],\n [0.0, 1.0],\n [0.0, 1.0],\n [0.0, 1.0],\n [0.0, 1.0],\n [0.0, 1.0],\n [0.0, 1.0],\n [0.0, 1.0]]\n}\n# Files with a 4th column for \"group name\" will be detected automatically, e.g.\n# param_file = '../../src/SALib/test_functions/params/Ishigami_groups.txt'\n\n# Generate samples\nparam_values = sample(problem, N=1000, num_levels=4,\n optimal_trajectories=None)\n\n# To use optimized trajectories (brute force method),\n# give an integer value for optimal_trajectories\n\n# Run the \"model\" -- this will happen offline for external models\nY = Sobol_G.evaluate(param_values)\n\n# Perform the sensitivity analysis using the model output\n# Specify which column of the output file to analyze (zero-indexed)\nSi = morris.analyze(problem, param_values, Y, conf_level=0.95,\n print_to_console=True,\n num_levels=4, num_resamples=100)\n# Returns a dictionary with keys 'mu', 'mu_star', 'sigma', and 'mu_star_conf'\n# e.g. Si['mu_star'] contains the mu* value for each parameter, in the\n# same order as the parameter file\n\nfig, (ax1, ax2) = plt.subplots(1, 2)\nhorizontal_bar_plot(ax1, Si, {}, sortby='mu_star', unit=r\"tCO$_2$/year\")\ncovariance_plot(ax2, Si, {}, unit=r\"tCO$_2$/year\")\n\nfig2 = plt.figure()\nsample_histograms(fig2, param_values, problem, {'color': 'y'})\nplt.show()\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "a073f7e913b3c0db485d86d397d9c3791e915423", "size": 348718, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "How_to_start.ipynb", "max_stars_repo_name": "mishagrol/Seminar_Sobol", "max_stars_repo_head_hexsha": "c0500d625fc256cbe821f698feb8ee7983f7ae39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "How_to_start.ipynb", "max_issues_repo_name": "mishagrol/Seminar_Sobol", "max_issues_repo_head_hexsha": "c0500d625fc256cbe821f698feb8ee7983f7ae39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "How_to_start.ipynb", "max_forks_repo_name": "mishagrol/Seminar_Sobol", "max_forks_repo_head_hexsha": "c0500d625fc256cbe821f698feb8ee7983f7ae39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 129.2026676547, "max_line_length": 110166, "alphanum_fraction": 0.8285405399, "converted": true, "num_tokens": 18445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.511716619597144, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.31664023182825746}} {"text": "```python\n%matplotlib inline\n```\n\n\n```python\n!ls \\content\n```\n\n ls: cannot access 'content': No such file or directory\n\n\n\nAdversarial Example Generation\n==============================\n\n**Author:** `Nathan Inkawhich `__\n\nIf you are reading this, hopefully you can appreciate how effective some\nmachine learning models are. Research is constantly pushing ML models to\nbe faster, more accurate, and more efficient. However, an often\noverlooked aspect of designing and training models is security and\nrobustness, especially in the face of an adversary who wishes to fool\nthe model.\n\nThis tutorial will raise your awareness to the security vulnerabilities\nof ML models, and will give insight into the hot topic of adversarial\nmachine learning. You may be surprised to find that adding imperceptible\nperturbations to an image *can* cause drastically different model\nperformance. Given that this is a tutorial, we will explore the topic\nvia example on an image classifier. Specifically we will use one of the\nfirst and most popular attack methods, the Fast Gradient Sign Attack\n(FGSM), to fool an MNIST classifier.\n\n\n\n\nThreat Model\n------------\n\nFor context, there are many categories of adversarial attacks, each with\na different goal and assumption of the attacker’s knowledge. However, in\ngeneral the overarching goal is to add the least amount of perturbation\nto the input data to cause the desired misclassification. There are\nseveral kinds of assumptions of the attacker’s knowledge, two of which\nare: **white-box** and **black-box**. A *white-box* attack assumes the\nattacker has full knowledge and access to the model, including\narchitecture, inputs, outputs, and weights. A *black-box* attack assumes\nthe attacker only has access to the inputs and outputs of the model, and\nknows nothing about the underlying architecture or weights. There are\nalso several types of goals, including **misclassification** and\n**source/target misclassification**. A goal of *misclassification* means\nthe adversary only wants the output classification to be wrong but does\nnot care what the new classification is. A *source/target\nmisclassification* means the adversary wants to alter an image that is\noriginally of a specific source class so that it is classified as a\nspecific target class.\n\nIn this case, the FGSM attack is a *white-box* attack with the goal of\n*misclassification*. With this background information, we can now\ndiscuss the attack in detail.\n\nFast Gradient Sign Attack\n-------------------------\n\nOne of the first and most popular adversarial attacks to date is\nreferred to as the *Fast Gradient Sign Attack (FGSM)* and is described\nby Goodfellow et. al. in `Explaining and Harnessing Adversarial\nExamples `__. The attack is remarkably\npowerful, and yet intuitive. It is designed to attack neural networks by\nleveraging the way they learn, *gradients*. The idea is simple, rather\nthan working to minimize the loss by adjusting the weights based on the\nbackpropagated gradients, the attack *adjusts the input data to maximize\nthe loss* based on the same backpropagated gradients. In other words,\nthe attack uses the gradient of the loss w.r.t the input data, then\nadjusts the input data to maximize the loss.\n\nBefore we jump into the code, let’s look at the famous\n`FGSM `__ panda example and extract\nsome notation.\n\n.. figure:: /_static/img/fgsm_panda_image.png\n :alt: fgsm_panda_image\n\nFrom the figure, $\\mathbf{x}$ is the original input image\ncorrectly classified as a “panda”, $y$ is the ground truth label\nfor $\\mathbf{x}$, $\\mathbf{\\theta}$ represents the model\nparameters, and $J(\\mathbf{\\theta}, \\mathbf{x}, y)$ is the loss\nthat is used to train the network. The attack backpropagates the\ngradient back to the input data to calculate\n$\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y)$. Then, it adjusts\nthe input data by a small step ($\\epsilon$ or $0.007$ in the\npicture) in the direction (i.e.\n$sign(\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y))$) that will\nmaximize the loss. The resulting perturbed image, $x'$, is then\n*misclassified* by the target network as a “gibbon” when it is still\nclearly a “panda”.\n\nHopefully now the motivation for this tutorial is clear, so lets jump\ninto the implementation.\n\n\n\n\n\n```python\nfrom __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\n```\n\nImplementation\n--------------\n\nIn this section, we will discuss the input parameters for the tutorial,\ndefine the model under attack, then code the attack and run some tests.\n\nInputs\n~~~~~~\n\nThere are only three inputs for this tutorial, and are defined as\nfollows:\n\n- **epsilons** - List of epsilon values to use for the run. It is\n important to keep 0 in the list because it represents the model\n performance on the original test set. Also, intuitively we would\n expect the larger the epsilon, the more noticeable the perturbations\n but the more effective the attack in terms of degrading model\n accuracy. Since the data range here is $[0,1]$, no epsilon\n value should exceed 1.\n\n- **pretrained_model** - path to the pretrained MNIST model which was\n trained with\n `pytorch/examples/mnist `__.\n For simplicity, download the pretrained model `here `__.\n\n- **use_cuda** - boolean flag to use CUDA if desired and available.\n Note, a GPU with CUDA is not critical for this tutorial as a CPU will\n not take much time.\n\n\n\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/gdrive')\n\n```\n\n Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly\n \n Enter your authorization code:\n ··········\n Mounted at /gdrive\n\n\n\n```python\nepsilons = [0, .05, .1, .15, .2, .25, .3]\npretrained_model = '/gdrive/My Drive/Tmp/lenet_mnist_model.pth' #pretrained_model = \"lenet_mnist_model.pth\"\nuse_cuda=True\n```\n\nModel Under Attack\n~~~~~~~~~~~~~~~~~~\n\nAs mentioned, the model under attack is the same MNIST model from\n`pytorch/examples/mnist `__.\nYou may train and save your own MNIST model or you can download and use\nthe provided model. The *Net* definition and test dataloader here have\nbeen copied from the MNIST example. The purpose of this section is to\ndefine the model and dataloader, then initialize the model and load the\npretrained weights.\n\n\n\n\n\n```python\n# LeNet Model definition\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv2_drop = nn.Dropout2d()\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, 10)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n x = self.fc2(x)\n return F.log_softmax(x, dim=1)\n\n# MNIST Test dataset and dataloader declaration\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, download=True, transform=transforms.Compose([\n transforms.ToTensor(),\n ])), \n batch_size=1, shuffle=True)\n\n# Define what device we are using\nprint(\"CUDA Available: \",torch.cuda.is_available())\ndevice = torch.device(\"cuda\" if (use_cuda and torch.cuda.is_available()) else \"cpu\")\n\n# Initialize the network\nmodel = Net().to(device)\n\n# Load the pretrained model\nmodel.load_state_dict(torch.load(pretrained_model, map_location='cpu'))\n\n# Set the model in evaluation mode. In this case this is for the Dropout layers\nmodel.eval()\n```\n\n Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ../data/MNIST/raw/train-images-idx3-ubyte.gz\n\n\n\n HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))\n\n\n Extracting ../data/MNIST/raw/train-images-idx3-ubyte.gz to ../data/MNIST/raw\n Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz to ../data/MNIST/raw/train-labels-idx1-ubyte.gz\n\n\n\n HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))\n\n\n Extracting ../data/MNIST/raw/train-labels-idx1-ubyte.gz to ../data/MNIST/raw\n Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz to ../data/MNIST/raw/t10k-images-idx3-ubyte.gz\n\n\n\n HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))\n\n\n Extracting ../data/MNIST/raw/t10k-images-idx3-ubyte.gz to ../data/MNIST/raw\n Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz to ../data/MNIST/raw/t10k-labels-idx1-ubyte.gz\n\n\n\n HBox(children=(IntProgress(value=1, bar_style='info', max=1), HTML(value='')))\n\n\n Extracting ../data/MNIST/raw/t10k-labels-idx1-ubyte.gz to ../data/MNIST/raw\n Processing...\n Done!\n CUDA Available: True\n \n \n\n\n\n\n\n Net(\n (conv1): Conv2d(1, 10, kernel_size=(5, 5), stride=(1, 1))\n (conv2): Conv2d(10, 20, kernel_size=(5, 5), stride=(1, 1))\n (conv2_drop): Dropout2d(p=0.5, inplace=False)\n (fc1): Linear(in_features=320, out_features=50, bias=True)\n (fc2): Linear(in_features=50, out_features=10, bias=True)\n )\n\n\n\nFGSM Attack\n~~~~~~~~~~~\n\nNow, we can define the function that creates the adversarial examples by\nperturbing the original inputs. The ``fgsm_attack`` function takes three\ninputs, *image* is the original clean image ($x$), *epsilon* is\nthe pixel-wise perturbation amount ($\\epsilon$), and *data_grad*\nis gradient of the loss w.r.t the input image\n($\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y)$). The function\nthen creates perturbed image as\n\n\\begin{align}perturbed\\_image = image + epsilon*sign(data\\_grad) = x + \\epsilon * sign(\\nabla_{x} J(\\mathbf{\\theta}, \\mathbf{x}, y))\\end{align}\n\nFinally, in order to maintain the original range of the data, the\nperturbed image is clipped to range $[0,1]$.\n\n\n\n\n\n```python\n# FGSM attack code\ndef fgsm_attack(image, epsilon, data_grad):\n # Collect the element-wise sign of the data gradient\n sign_data_grad = data_grad.sign()\n # Create the perturbed image by adjusting each pixel of the input image\n perturbed_image = image + epsilon*sign_data_grad\n # Adding clipping to maintain [0,1] range\n perturbed_image = torch.clamp(perturbed_image, 0, 1)\n # Return the perturbed image\n return perturbed_image\n```\n\nTesting Function\n~~~~~~~~~~~~~~~~\n\nFinally, the central result of this tutorial comes from the ``test``\nfunction. Each call to this test function performs a full test step on\nthe MNIST test set and reports a final accuracy. However, notice that\nthis function also takes an *epsilon* input. This is because the\n``test`` function reports the accuracy of a model that is under attack\nfrom an adversary with strength $\\epsilon$. More specifically, for\neach sample in the test set, the function computes the gradient of the\nloss w.r.t the input data ($data\\_grad$), creates a perturbed\nimage with ``fgsm_attack`` ($perturbed\\_data$), then checks to see\nif the perturbed example is adversarial. In addition to testing the\naccuracy of the model, the function also saves and returns some\nsuccessful adversarial examples to be visualized later.\n\n\n\n\n\n```python\ndef test( model, device, test_loader, epsilon, scale=1 ):\n\n # Accuracy counter\n correct = 0\n adv_examples = []\n\n # Loop over all examples in test set\n for data, target in test_loader:\n\n # scaling the inout\n data = scale * data\n # data = torch.clamp(data, 0, 1)\n \n # Send the data and label to the device\n data, target = data.to(device), target.to(device)\n\n # Set requires_grad attribute of tensor. Important for Attack\n data.requires_grad = True\n\n # Forward pass the data through the model\n output = model(data)\n init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n\n # If the initial prediction is wrong, dont bother attacking, just move on\n if init_pred.item() != target.item():\n continue\n\n # Calculate the loss\n loss = F.nll_loss(output, target)\n\n # Zero all existing gradients\n model.zero_grad()\n\n # Calculate gradients of model in backward pass\n loss.backward()\n\n # Collect datagrad\n data_grad = data.grad.data\n\n # Call FGSM Attack\n perturbed_data = fgsm_attack(data, epsilon, data_grad)\n\n # Re-classify the perturbed image\n output = model(perturbed_data)\n\n # Check for success\n final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability\n if final_pred.item() == target.item():\n correct += 1\n # Special case for saving 0 epsilon examples\n if (epsilon == 0) and (len(adv_examples) < 5):\n adv_ex = perturbed_data.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )\n else:\n # Save some adv examples for visualization later\n if len(adv_examples) < 5:\n adv_ex = perturbed_data.squeeze().detach().cpu().numpy()\n adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) )\n\n # Calculate final accuracy for this epsilon\n final_acc = correct/float(len(test_loader))\n print(\"Epsilon: {}\\tTest Accuracy = {} / {} = {}\".format(epsilon, correct, len(test_loader), final_acc))\n\n # Return the accuracy and an adversarial example\n return final_acc, adv_examples\n```\n\nRun Attack\n~~~~~~~~~~\n\nThe last part of the implementation is to actually run the attack. Here,\nwe run a full test step for each epsilon value in the *epsilons* input.\nFor each epsilon we also save the final accuracy and some successful\nadversarial examples to be plotted in the coming sections. Notice how\nthe printed accuracies decrease as the epsilon value increases. Also,\nnote the $\\epsilon=0$ case represents the original test accuracy,\nwith no attack.\n\n\n\n\n\n```python\nscales = [.5, 1, 2, 5, 10, 100]\nexamples = []\n\nall_res = []\n# Run test for each epsilon\nfor s in scales:\n print(f'sclae={s}')\n accuracies = []\n for eps in epsilons:\n acc, ex = test(model, device, test_loader, eps, s)\n accuracies.append(acc)\n# examples.append(ex)\n all_res.append(accuracies)\n```\n\n sclae=0.5\n Epsilon: 0\tTest Accuracy = 9744 / 10000 = 0.9744\n Epsilon: 0.05\tTest Accuracy = 7925 / 10000 = 0.7925\n Epsilon: 0.1\tTest Accuracy = 3031 / 10000 = 0.3031\n Epsilon: 0.15\tTest Accuracy = 674 / 10000 = 0.0674\n Epsilon: 0.2\tTest Accuracy = 192 / 10000 = 0.0192\n Epsilon: 0.25\tTest Accuracy = 92 / 10000 = 0.0092\n Epsilon: 0.3\tTest Accuracy = 63 / 10000 = 0.0063\n sclae=1\n Epsilon: 0\tTest Accuracy = 9810 / 10000 = 0.981\n Epsilon: 0.05\tTest Accuracy = 9426 / 10000 = 0.9426\n Epsilon: 0.1\tTest Accuracy = 8510 / 10000 = 0.851\n Epsilon: 0.15\tTest Accuracy = 6826 / 10000 = 0.6826\n Epsilon: 0.2\tTest Accuracy = 4301 / 10000 = 0.4301\n Epsilon: 0.25\tTest Accuracy = 2082 / 10000 = 0.2082\n Epsilon: 0.3\tTest Accuracy = 869 / 10000 = 0.0869\n sclae=2\n Epsilon: 0\tTest Accuracy = 9777 / 10000 = 0.9777\n Epsilon: 0.05\tTest Accuracy = 9448 / 10000 = 0.9448\n Epsilon: 0.1\tTest Accuracy = 8742 / 10000 = 0.8742\n Epsilon: 0.15\tTest Accuracy = 7423 / 10000 = 0.7423\n Epsilon: 0.2\tTest Accuracy = 5305 / 10000 = 0.5305\n Epsilon: 0.25\tTest Accuracy = 2938 / 10000 = 0.2938\n Epsilon: 0.3\tTest Accuracy = 1355 / 10000 = 0.1355\n sclae=5\n Epsilon: 0\tTest Accuracy = 9725 / 10000 = 0.9725\n Epsilon: 0.05\tTest Accuracy = 9335 / 10000 = 0.9335\n Epsilon: 0.1\tTest Accuracy = 8596 / 10000 = 0.8596\n Epsilon: 0.15\tTest Accuracy = 7289 / 10000 = 0.7289\n Epsilon: 0.2\tTest Accuracy = 5206 / 10000 = 0.5206\n Epsilon: 0.25\tTest Accuracy = 2961 / 10000 = 0.2961\n Epsilon: 0.3\tTest Accuracy = 1388 / 10000 = 0.1388\n sclae=10\n Epsilon: 0\tTest Accuracy = 9689 / 10000 = 0.9689\n Epsilon: 0.05\tTest Accuracy = 9267 / 10000 = 0.9267\n Epsilon: 0.1\tTest Accuracy = 8491 / 10000 = 0.8491\n Epsilon: 0.15\tTest Accuracy = 7121 / 10000 = 0.7121\n Epsilon: 0.2\tTest Accuracy = 5114 / 10000 = 0.5114\n Epsilon: 0.25\tTest Accuracy = 2994 / 10000 = 0.2994\n Epsilon: 0.3\tTest Accuracy = 1404 / 10000 = 0.1404\n sclae=100\n Epsilon: 0\tTest Accuracy = 9641 / 10000 = 0.9641\n Epsilon: 0.05\tTest Accuracy = 9174 / 10000 = 0.9174\n Epsilon: 0.1\tTest Accuracy = 8308 / 10000 = 0.8308\n Epsilon: 0.15\tTest Accuracy = 6929 / 10000 = 0.6929\n Epsilon: 0.2\tTest Accuracy = 4941 / 10000 = 0.4941\n Epsilon: 0.25\tTest Accuracy = 2867 / 10000 = 0.2867\n Epsilon: 0.3\tTest Accuracy = 1379 / 10000 = 0.1379\n\n\n\n```python\nscales = [.5, 1, 2, 5, 10, 100]\nexamples = []\n\nall_res = []\n# Run test for each epsilon\nfor s in scales:\n print(f'sclae={s}')\n accuracies = []\n for eps in epsilons:\n acc, ex = test(model, device, test_loader, eps, s)\n accuracies.append(acc)\n# examples.append(ex)\n all_res.append(accuracies)\n```\n\nResults\n-------\n\nAccuracy vs Epsilon\n~~~~~~~~~~~~~~~~~~~\n\nThe first result is the accuracy versus epsilon plot. As alluded to\nearlier, as epsilon increases we expect the test accuracy to decrease.\nThis is because larger epsilons mean we take a larger step in the\ndirection that will maximize the loss. Notice the trend in the curve is\nnot linear even though the epsilon values are linearly spaced. For\nexample, the accuracy at $\\epsilon=0.05$ is only about 4% lower\nthan $\\epsilon=0$, but the accuracy at $\\epsilon=0.2$ is 25%\nlower than $\\epsilon=0.15$. Also, notice the accuracy of the model\nhits random accuracy for a 10-class classifier between\n$\\epsilon=0.25$ and $\\epsilon=0.3$.\n\n\n\n\n\n```python\nsymbs = ['*-', 'o-', 's-', 'd-', '+-', 'x-', '^-', '<-']\nplt.figure(figsize=(5,5))\n\nfor idx, accuracies in enumerate(all_res):\n plt.plot(epsilons, accuracies, symbs[idx])\nplt.yticks(np.arange(0, 1.1, step=0.1))\nplt.xticks(np.arange(0, .35, step=0.05))\nplt.title(\"Accuracy vs Epsilon\")\nplt.xlabel(\"Epsilon\")\nplt.ylabel(\"Accuracy\")\nplt.legend(scales)\nplt.show()\n```\n\nSample Adversarial Examples\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nRemember the idea of no free lunch? In this case, as epsilon increases\nthe test accuracy decreases **BUT** the perturbations become more easily\nperceptible. In reality, there is a tradeoff between accuracy\ndegredation and perceptibility that an attacker must consider. Here, we\nshow some examples of successful adversarial examples at each epsilon\nvalue. Each row of the plot shows a different epsilon value. The first\nrow is the $\\epsilon=0$ examples which represent the original\n“clean” images with no perturbation. The title of each image shows the\n“original classification -> adversarial classification.” Notice, the\nperturbations start to become evident at $\\epsilon=0.15$ and are\nquite evident at $\\epsilon=0.3$. However, in all cases humans are\nstill capable of identifying the correct class despite the added noise.\n\n\n\n\n\n```python\n# Plot several examples of adversarial samples at each epsilon\ncnt = 0\nplt.figure(figsize=(8,10))\nfor i in range(len(epsilons)):\n for j in range(len(examples[i])):\n cnt += 1\n plt.subplot(len(epsilons),len(examples[0]),cnt)\n plt.xticks([], [])\n plt.yticks([], [])\n if j == 0:\n plt.ylabel(\"Eps: {}\".format(epsilons[i]), fontsize=14)\n orig,adv,ex = examples[i][j]\n plt.title(\"{} -> {}\".format(orig, adv))\n plt.imshow(ex, cmap=\"gray\")\nplt.tight_layout()\nplt.show()\n```\n\nWhere to go next?\n-----------------\n\nHopefully this tutorial gives some insight into the topic of adversarial\nmachine learning. There are many potential directions to go from here.\nThis attack represents the very beginning of adversarial attack research\nand since there have been many subsequent ideas for how to attack and\ndefend ML models from an adversary. In fact, at NIPS 2017 there was an\nadversarial attack and defense competition and many of the methods used\nin the competition are described in this paper: `Adversarial Attacks and\nDefences Competition `__. The work\non defense also leads into the idea of making machine learning models\nmore *robust* in general, to both naturally perturbed and adversarially\ncrafted inputs.\n\nAnother direction to go is adversarial attacks and defense in different\ndomains. Adversarial research is not limited to the image domain, check\nout `this `__ attack on\nspeech-to-text models. But perhaps the best way to learn more about\nadversarial machine learning is to get your hands dirty. Try to\nimplement a different attack from the NIPS 2017 competition, and see how\nit differs from FGSM. Then, try to defend the model from your own\nattacks.\n\n\n\n", "meta": {"hexsha": "95dd928f4399b1d7edc225ae137efff9106159a9", "size": 108985, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "fgsm_tutorial_scale.ipynb", "max_stars_repo_name": "aliborji/ReLU_defense", "max_stars_repo_head_hexsha": "22ea90e7a9e91a1c54c96d7bbbb6020a3495f580", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-06-30T13:14:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T19:11:54.000Z", "max_issues_repo_path": "fgsm_tutorial_scale.ipynb", "max_issues_repo_name": "aliborji/ReLU_defense", "max_issues_repo_head_hexsha": "22ea90e7a9e91a1c54c96d7bbbb6020a3495f580", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fgsm_tutorial_scale.ipynb", "max_forks_repo_name": "aliborji/ReLU_defense", "max_forks_repo_head_hexsha": "22ea90e7a9e91a1c54c96d7bbbb6020a3495f580", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2020-04-29T11:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-12T18:15:02.000Z", "avg_line_length": 54.6838936277, "max_line_length": 37456, "alphanum_fraction": 0.7212919209, "converted": true, "num_tokens": 5998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.31609223341560055}} {"text": "```python\nimport numpy as np\nimport sympy as sp\nimport compiler\nclass Primiaries:\n def __init__(self, x):\n self.data_type = type(x).__name__\n self.data = x\n \n def get_mean(self):\n if self.data_type == \"dict\":\n x = self.data[\"x\"]\n f = self.data[\"f\"]\n if len(x) != len(f): raise Exception(\"The length of `x` and `f` should be same\")\n n = 0\n sum_xf = 0\n for i in range(len(x)):\n n += f[i]\n sum_xf += f[i] * x[i]\n return sum_xf/n\n def get_median(self):\n if self.data_type == \"dict\":\n x = self.data[\"x\"]\n f = self.data[\"f\"]\n if len(x) != len(f): raise Exception(\"The length of `x` and `f` should be same\")\n cumulative = 0\n cumulative_list = []\n for frequency in f:\n cumulative += frequency\n cumulative_list.append(cumulative)\n to_minus = (cumulative+1)/2\n distance_list = []\n for value in f:\n distance = abs(value-to_minus)\n distance_list.append(distance)\n minimum_inices = [i for i, e in enumerate(distance_list) if e == min(distance_list)]\n return to_minus\n\n\ndata = {\"x\":[4,8,12,16,20,24,28],\n \"f\":[7,18,25,18,15,10,7]\n}\nmy_class = Primiaries(data)\n# my_class.get_median()\neq = \"x^2+2x\"\ncompiler\n```\n\n\n\n\n \n\n\n\n\n```python\n!pip3 install compiler\n```\n\n Collecting compiler\n Downloading compiler-0.2.0-py3-none-any.whl (5.6 kB)\n Installing collected packages: compiler\n Successfully installed compiler-0.2.0\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "bc2cbad3e737e24b819dc820b282917b287b4542", "size": 3273, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "primiaries/Python/primiaries.ipynb", "max_stars_repo_name": "amirhkiani77/Risk-Management", "max_stars_repo_head_hexsha": "f6a868200fb90bdae21c14381084f8f01f6faf6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "primiaries/Python/primiaries.ipynb", "max_issues_repo_name": "amirhkiani77/Risk-Management", "max_issues_repo_head_hexsha": "f6a868200fb90bdae21c14381084f8f01f6faf6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "primiaries/Python/primiaries.ipynb", "max_forks_repo_name": "amirhkiani77/Risk-Management", "max_forks_repo_head_hexsha": "f6a868200fb90bdae21c14381084f8f01f6faf6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9646017699, "max_line_length": 165, "alphanum_fraction": 0.4754048274, "converted": true, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499941, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.31545897320365507}} {"text": "##### Copyright 2020 The Cirq Developers\n\n\n```\n#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n```\n\n# Shor's algorithm\n\n\n \n \n \n \n
\n View on QuantumAI\n \n Run in Google Colab\n \n View source on GitHub\n \n Download notebook\n
\n\nThis tutorial presents a pedagogical demonstration of Shor's algorithm. It is a modified and expanded version of [this Cirq example](https://github.com/quantumlib/Cirq/blob/master/examples/shor.py).\n\n\n```\n\"\"\"Install Cirq.\"\"\"\ntry:\n import cirq\nexcept ImportError:\n print(\"installing cirq...\")\n !pip install --quiet cirq\n print(\"installed cirq.\")\n```\n\n\n```\n\"\"\"Imports for the notebook.\"\"\"\nimport fractions\nimport math\nimport random\n\nimport numpy as np\nimport sympy\nfrom typing import Callable, List, Optional, Sequence, Union\n\nimport cirq\n```\n\n# Order finding\n\nFactoring an integer $n$ can be reduced to finding the period of the modular exponential function (to be defined). Finding this period can be accomplished (with high probability) by finding the order of a randomly chosen element of the multiplicative group modulo $n$.\n\nLet $n$ be a positive integer and \n\n$$ \\mathbb{Z}_n := \\{x \\in \\mathbb{Z}_+ : x < n \\text{ and } \\text{gcd}(x, n) = 1\\} $$\n\nbe the multiplicative group modulo $n$.\nGiven $x \\in \\mathbb{Z}_n$, compute the smallest positive integer $r$ such that $x^r \\text{ mod } n = 1$.\n\nIt can be shown from group/number theory that:\n\n(1) Such an integer $r$ exists. (Note that $g^{|G|} = 1_G$ for any group $G$ with cardinality $|G|$ and element $g \\in G$, but it's possible that $r < |G|$.)\n\n(2) If $n = pq$ for primes $p$ and $q$, then $|\\mathbb{Z}_n| = \\phi(n) = (p - 1) (q - 1)$. (The function $\\phi$ is called [Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function).)\n\n(3) The modular exponential function\n\n$$ f_x(z) := x^z \\mod n $$\n\nis periodic with period $r$ (the order of the element $x \\in \\mathbb{Z}_n$). That is, $f_x(z + r) = f_x(z)$. \n\n(4) If we know the period of the modular exponential function, we can (with high probability) figure out $p$ and $q$ -- that is, factor $n$.\n\nAs a refresher, we can visualize the elements of some multiplicative groups $\\mathbb{Z}_n$ for integers $n$ via the following simple function.\n\n\n```\n\"\"\"Function to compute the elements of Z_n.\"\"\"\ndef multiplicative_group(n: int) -> List[int]:\n \"\"\"Returns the multiplicative group modulo n.\n \n Args:\n n: Modulus of the multiplicative group.\n \"\"\"\n assert n > 1\n group = [1]\n for x in range(2, n):\n if math.gcd(x, n) == 1:\n group.append(x)\n return group\n```\n\nFor example, the multiplicative group modulo $n = 15$ is shown below.\n\n\n```\n\"\"\"Example of a multiplicative group.\"\"\"\nn = 15\nprint(f\"The multiplicative group modulo n = {n} is:\")\nprint(multiplicative_group(n))\n```\n\nOne can check that this set of elements indeed forms a group (under ordinary multiplication).\n\n## Classical order finding\n\nA function for classically computing the order $r$ of an element $x \\in \\mathbb{Z}_n$ is provided below. This function simply computes the sequence \n\n$$ x^2 \\text{ mod } n $$\n$$ x^3 \\text{ mod } n $$\n$$ x^4 \\text{ mod } n $$\n$$ \\vdots $$\n\nuntil an integer $r$ is found such that $x^r = 1 \\text{ mod } n$. Since $|\\mathbb{Z}_n| = \\phi(n)$, this algorithm for order finding has time complexity $O(\\phi(n))$ which is inefficient. (Roughly $O(2^{L / 2})$ where $L$ is the number of bits in $n$.)\n\n\n```\n\"\"\"Function for classically computing the order of an element of Z_n.\"\"\"\ndef classical_order_finder(x: int, n: int) -> Optional[int]:\n \"\"\"Computes smallest positive r such that x**r mod n == 1.\n\n Args:\n x: Integer whose order is to be computed, must be greater than one\n and belong to the multiplicative group of integers modulo n (which\n consists of positive integers relatively prime to n),\n n: Modulus of the multiplicative group.\n\n Returns:\n Smallest positive integer r such that x**r == 1 mod n.\n Always succeeds (and hence never returns None).\n\n Raises:\n ValueError when x is 1 or not an element of the multiplicative\n group of integers modulo n.\n \"\"\"\n # Make sure x is both valid and in Z_n.\n if x < 2 or x >= n or math.gcd(x, n) > 1:\n raise ValueError(f\"Invalid x={x} for modulus n={n}.\")\n \n # Determine the order.\n r, y = 1, x\n while y != 1:\n y = (x * y) % n\n r += 1\n return r\n```\n\nAn example of computing $r$ for a given $x \\in \\mathbb{Z}_n$ and given $n$ is shown in the code block below.\n\n\n```\n\"\"\"Example of (classically) computing the order of an element.\"\"\"\nn = 15 # The multiplicative group is [1, 2, 4, 7, 8, 11, 13, 14].\nx = 8\nr = classical_order_finder(x, n)\n\n# Check that the order is indeed correct.\nprint(f\"x^r mod n = {x}^{r} mod {n} = {x**r % n}\")\n```\n\nThe quantum part of Shor's algorithm is order finding, but done via a quantum circuit, which we'll discuss below.\n\n## Quantum order finding\n\nQuantum order finding is essentially quantum phase estimation with unitary $U$ that computes the modular exponential function $f_x(z)$ for some randomly chosen $x \\in \\mathbb{Z}_n$. The full details of how $U$ is computed in terms of elementary gates can be complex to unravel, especially on a first reading. In this tutorial, we'll use arithmetic operations in Cirq which can implement such a unitary $U$ without fully delving into the details of elementary gates.\n\nBelow we first show an example of a simple arithmetic operation in Cirq (addition) then discuss the operation we care about (modular exponentiation).\n\n### Quantum arithmetic operations in Cirq\n\nHere we discuss an example of defining an arithmetic operation in Cirq, namely modular addition. This operation adds the value of the input register into the target register. More specifically, this operation acts on two qubit registers as\n\n$$ |a\\rangle_i |b\\rangle_t \\mapsto |a\\rangle_i |a + b \\text{ mod } N_t \\rangle_t . $$\n\nHere, the subscripts $i$ and $t$ denote input and target register, respectively, and $N_t$ is the dimension of the target register.\n\nTo define this operation, called `Adder`, we inherit from `cirq.ArithmeticOperation` and override the four methods shown below. The main method is the `apply` method which defines the arithmetic. Here, we simply state the expression as $a + b$ instead of the more accurate $a + b \\text{ mod } N_t$ above -- the `cirq.ArithmeticOperation` class is able to deduce what we mean by simply $a + b$ since the operation must be reversible. \n\n\n```\n\"\"\"Example of defining an arithmetic (quantum) operation in Cirq.\"\"\"\nclass Adder(cirq.ArithmeticOperation):\n \"\"\"Quantum addition.\"\"\"\n def __init__(self, target_register, input_register):\n self.input_register = input_register\n self.target_register = target_register\n \n def registers(self):\n return self.target_register, self.input_register\n \n def with_registers(self, *new_registers):\n return Adder(*new_registers)\n \n def apply(self, target_value, input_value):\n return target_value + input_value\n```\n\nNow that we have the operation defined, we can use it in a circuit. The cell below creates two qubit registers, then sets the first register to be $|10\\rangle$ (in binary) and the second register to be $|01\\rangle$ (in binary) via $X$ gates. Then, we use the `Adder` operation, then measure all the qubits.\n\nSince $10 + 01 = 11$ (in binary), we expect to measure $|11\\rangle$ in the target register every time. Additionally, since we do not alter the input register, we expect to measure $|10\\rangle$ in the input register every time. In short, the only bitstring we expect to measure is $1011$. \n\n\n```\n\"\"\"Example of using an Adder in a circuit.\"\"\"\n# Two qubit registers.\nqreg1 = cirq.LineQubit.range(2)\nqreg2 = cirq.LineQubit.range(2, 4)\n\n# Define the circuit.\ncirc = cirq.Circuit(\n cirq.ops.X.on(qreg1[0]),\n cirq.ops.X.on(qreg2[1]),\n Adder(input_register=qreg1, target_register=qreg2),\n cirq.measure_each(*qreg1),\n cirq.measure_each(*qreg2)\n)\n\n# Display it.\nprint(\"Circuit:\\n\")\nprint(circ)\n\n# Print the measurement outcomes.\nprint(\"\\n\\nMeasurement outcomes:\\n\")\nprint(cirq.sample(circ, repetitions=5).data)\n```\n\nIn the output of this code block, we first see the circuit which shows the initial $X$ gates, the `Adder` operation, then the final measurements. Next, we see the measurement outcomes which are all the bitstring $1011$ as expected.\n\nIt is also possible to see the unitary of the adder operation, which we do below. Here, we set the target register to be two qubits in the zero state, i.e. $|00\\rangle$. We specify the input register as the integer one which corresponds to the qubit register $|01\\rangle$. \n\n\n```\n\"\"\"Example of the unitary of an Adder operation.\"\"\"\ncirq.unitary(\n Adder(target_register=cirq.LineQubit.range(2),\n input_register=1)\n).real\n```\n\nWe can understand this unitary as follows. The $i$th column of the unitary is the state $|i + 1 \\text{ mod } 4\\rangle$. For example, if we look at the $0$th column of the unitary, we see the state $|i + 1 \\text{ mod } 4\\rangle = |0 + 1 \\text{ mod } 4\\rangle = |1\\rangle$. If we look at the $1$st column of the unitary, we see the state $|i + 1 \\text{ mod } 4\\rangle = |1 + 1 \\text{ mod } 4\\rangle = |2\\rangle$. Similarly for the last two columns.\n\n### Modular exponential arithmetic operation\n\nWe can define the modular exponential arithmetic operation in a similar way to the simple addition arithmetic operation, shown below. For the purposes of understanding Shor's algorithm, the most important part of the following code block is the `apply` method which defines the arithmetic operation.\n\n\n```\n\"\"\"Defines the modular exponential operation used in Shor's algorithm.\"\"\"\nclass ModularExp(cirq.ArithmeticOperation):\n \"\"\"Quantum modular exponentiation.\n\n This class represents the unitary which multiplies base raised to exponent\n into the target modulo the given modulus. More precisely, it represents the\n unitary V which computes modular exponentiation x**e mod n:\n\n V|y⟩|e⟩ = |y * x**e mod n⟩ |e⟩ 0 <= y < n\n V|y⟩|e⟩ = |y⟩ |e⟩ n <= y\n\n where y is the target register, e is the exponent register, x is the base\n and n is the modulus. Consequently,\n\n V|y⟩|e⟩ = (U**e|y)|e⟩\n\n where U is the unitary defined as\n\n U|y⟩ = |y * x mod n⟩ 0 <= y < n\n U|y⟩ = |y⟩ n <= y\n \"\"\"\n def __init__(\n self, \n target: Sequence[cirq.Qid],\n exponent: Union[int, Sequence[cirq.Qid]], \n base: int,\n modulus: int\n ) -> None:\n if len(target) < modulus.bit_length():\n raise ValueError(f'Register with {len(target)} qubits is too small '\n f'for modulus {modulus}')\n self.target = target\n self.exponent = exponent\n self.base = base\n self.modulus = modulus\n\n def registers(self) -> Sequence[Union[int, Sequence[cirq.Qid]]]:\n return self.target, self.exponent, self.base, self.modulus\n\n def with_registers(\n self,\n *new_registers: Union[int, Sequence['cirq.Qid']],\n ) -> cirq.ArithmeticOperation:\n if len(new_registers) != 4:\n raise ValueError(f'Expected 4 registers (target, exponent, base, '\n f'modulus), but got {len(new_registers)}')\n target, exponent, base, modulus = new_registers\n if not isinstance(target, Sequence):\n raise ValueError(\n f'Target must be a qubit register, got {type(target)}')\n if not isinstance(base, int):\n raise ValueError(\n f'Base must be a classical constant, got {type(base)}')\n if not isinstance(modulus, int):\n raise ValueError(\n f'Modulus must be a classical constant, got {type(modulus)}')\n return ModularExp(target, exponent, base, modulus)\n\n def apply(self, *register_values: int) -> int:\n assert len(register_values) == 4\n target, exponent, base, modulus = register_values\n if target >= modulus:\n return target\n return (target * base**exponent) % modulus\n\n def _circuit_diagram_info_(\n self,\n args: cirq.CircuitDiagramInfoArgs,\n ) -> cirq.CircuitDiagramInfo:\n assert args.known_qubits is not None\n wire_symbols: List[str] = []\n t, e = 0, 0\n for qubit in args.known_qubits:\n if qubit in self.target:\n if t == 0:\n if isinstance(self.exponent, Sequence):\n e_str = 'e'\n else:\n e_str = str(self.exponent)\n wire_symbols.append(\n f'ModularExp(t*{self.base}**{e_str} % {self.modulus})')\n else:\n wire_symbols.append('t' + str(t))\n t += 1\n if isinstance(self.exponent, Sequence) and qubit in self.exponent:\n wire_symbols.append('e' + str(e))\n e += 1\n return cirq.CircuitDiagramInfo(wire_symbols=tuple(wire_symbols))\n```\n\nIn the `apply` method, we see that we evaluate `(target * base**exponent) % modulus`. The `target` and the `exponent` depend on the values of the respective qubit registers, and the `base` and `modulus` are constant -- namely, the `modulus` is $n$ and the `base` is some $x \\in \\mathbb{Z}_n$. \n\nThe total number of qubits we will use is $3 (L + 1)$ where $L$ is the number of bits needed to store the integer $n$ to factor. The size of the unitary which implements the modular exponential is thus $4^{3(L + 1)}$. For a modest $n = 15$, the unitary requires storing $2^{30}$ floating point numbers in memory which is out of reach of most current standard laptops.\n\n\n```\n\"\"\"Create the target and exponent registers for phase estimation,\nand see the number of qubits needed for Shor's algorithm.\n\"\"\"\nn = 15\nL = n.bit_length()\n\n# The target register has L qubits.\ntarget = cirq.LineQubit.range(L)\n\n# The exponent register has 2L + 3 qubits.\nexponent = cirq.LineQubit.range(L, 3 * L + 3)\n\n# Display the total number of qubits to factor this n.\nprint(f\"To factor n = {n} which has L = {L} bits, we need 3L + 3 = {3 * L + 3} qubits.\")\n```\n\nAs with the simple adder operation, this modular exponential operation has a unitary which we can display (memory permitting) as follows.\n\n\n```\n\"\"\"See (part of) the unitary for a modular exponential operation.\"\"\"\n# Pick some element of the multiplicative group modulo n.\nx = 5\n\n# Display (part of) the unitary. Uncomment if n is small enough.\n# cirq.unitary(ModularExp(target, exponent, x, n))\n```\n\n## Using the modular exponentional operation in a circuit\n\nThe quantum part of Shor's algorithm is just phase estimation with the unitary $U$ corresponding to the modular exponential operation. The following cell defines a function which creates the circuit for Shor's algorithm using the `ModularExp` operation we defined above.\n\n\n```\n\"\"\"Function to make the quantum circuit for order finding.\"\"\"\ndef make_order_finding_circuit(x: int, n: int) -> cirq.Circuit:\n \"\"\"Returns quantum circuit which computes the order of x modulo n.\n\n The circuit uses Quantum Phase Estimation to compute an eigenvalue of\n the unitary\n\n U|y⟩ = |y * x mod n⟩ 0 <= y < n\n U|y⟩ = |y⟩ n <= y\n\n Args:\n x: positive integer whose order modulo n is to be found\n n: modulus relative to which the order of x is to be found\n\n Returns:\n Quantum circuit for finding the order of x modulo n\n \"\"\"\n L = n.bit_length()\n target = cirq.LineQubit.range(L)\n exponent = cirq.LineQubit.range(L, 3 * L + 3)\n return cirq.Circuit(\n cirq.X(target[L - 1]),\n cirq.H.on_each(*exponent),\n ModularExp(target, exponent, x, n),\n cirq.qft(*exponent, inverse=True),\n cirq.measure(*exponent, key='exponent'),\n )\n```\n\nUsing this function, we can visualize the circuit for a given $x$ and $n$ as follows.\n\n\n```\n\"\"\"Example of the quantum circuit for period finding.\"\"\"\nn = 15\nx = 7\ncircuit = make_order_finding_circuit(x, n)\nprint(circuit)\n```\n\nAs previously described, we put the exponent register into an equal superposition via Hadamard gates. The $X$ gate on the last qubit in the target register is used for phase kickback. The modular exponential operation performs the sequence of controlled unitaries in phase estimation, then we apply the inverse quantum Fourier transform to the exponent register and measure to read out the result.\n\nTo illustrate the measurement results, we can sample from a smaller circuit. (Note that in practice we would never run Shor's algorithm with $n = 6$ because it is even. This is just an example to illustrate the measurement outcomes.)\n\n\n```\n\"\"\"Measuring Shor's period finding circuit.\"\"\"\ncircuit = make_order_finding_circuit(x=5, n=6)\nres = cirq.sample(circuit, repetitions=8)\n\nprint(\"Raw measurements:\")\nprint(res)\n\nprint(\"\\nInteger in exponent register:\")\nprint(res.data)\n```\n\nWe interpret each measured bitstring as an integer, but what do these integers tell us? In the next section we look at how to classically post-process to interpret them.\n\n## Classical post-processing\n\nThe integer we measure is close to $s / r$ where $r$ is the order of $x \\in \\mathbb{Z}_n$ and $0 \\le s < r$ is an integer. We use the continued fractions algorithm to determine $r$ from $s / r$ then return it if the order finding circuit succeeded, else we return `None`.\n\n\n```\ndef process_measurement(result: cirq.TrialResult, x: int, n: int) -> Optional[int]:\n \"\"\"Interprets the output of the order finding circuit.\n\n Specifically, it determines s/r such that exp(2πis/r) is an eigenvalue\n of the unitary\n\n U|y⟩ = |xy mod n⟩ 0 <= y < n\n U|y⟩ = |y⟩ n <= y\n \n then computes r (by continued fractions) if possible, and returns it.\n\n Args:\n result: trial result obtained by sampling the output of the\n circuit built by make_order_finding_circuit\n\n Returns:\n r, the order of x modulo n or None.\n \"\"\"\n # Read the output integer of the exponent register.\n exponent_as_integer = result.data[\"exponent\"][0]\n exponent_num_bits = result.measurements[\"exponent\"].shape[1]\n eigenphase = float(exponent_as_integer / 2**exponent_num_bits)\n\n # Run the continued fractions algorithm to determine f = s / r.\n f = fractions.Fraction.from_float(eigenphase).limit_denominator(n)\n \n # If the numerator is zero, the order finder failed.\n if f.numerator == 0:\n return None\n \n # Else, return the denominator if it is valid.\n r = f.denominator\n if x**r % n != 1:\n return None\n return r\n```\n\nThe next code block shows an example of creating an order finding circuit, executing it, then using the classical postprocessing function to determine the order. Recall that the quantum part of the algorithm succeeds with some probability. If the order is `None`, try re-running the cell a few times. \n\n\n```\n\"\"\"Example of the classical post-processing.\"\"\"\n# Set n and x here\nn = 6\nx = 5\n\nprint(f\"Finding the order of x = {x} modulo n = {n}\\n\")\nmeasurement = cirq.sample(circuit, repetitions=1)\nprint(\"Raw measurements:\")\nprint(measurement)\n\nprint(\"\\nInteger in exponent register:\")\nprint(measurement.data)\n\nr = process_measurement(measurement, x, n)\nprint(\"\\nOrder r =\", r)\nif r is not None:\n print(f\"x^r mod n = {x}^{r} mod {n} = {x**r % n}\")\n```\n\nYou should see that the order of $x = 5$ in $\\mathbb{Z}_6$ is $r = 2$. Indeed, $5^2 \\text{ mod } 6 = 25 \\text{ mod } 6 = 1$. \n\n## Quantum order finder\n\nWe can now define a streamlined function for the quantum version of order finding using the functions we have previously written. The quantum order finder below creates the circuit, executes it, and processes the measurement result.\n\n\n```\ndef quantum_order_finder(x: int, n: int) -> Optional[int]:\n \"\"\"Computes smallest positive r such that x**r mod n == 1.\n \n Args:\n x: integer whose order is to be computed, must be greater than one\n and belong to the multiplicative group of integers modulo n (which\n consists of positive integers relatively prime to n),\n n: modulus of the multiplicative group.\n \"\"\"\n # Check that the integer x is a valid element of the multiplicative group\n # modulo n.\n if x < 2 or n <= x or math.gcd(x, n) > 1:\n raise ValueError(f'Invalid x={x} for modulus n={n}.')\n\n # Create the order finding circuit.\n circuit = make_order_finding_circuit(x, n)\n \n # Sample from the order finding circuit.\n measurement = cirq.sample(circuit)\n \n # Return the processed measurement result.\n return process_measurement(measurement, x, n)\n```\n\nThis completes our quantum implementation of an order finder, and the quantum part of Shor's algorithm.\n\n# The complete factoring algorithm\n\nWe can use this quantum order finder (or the classical order finder) to complete Shor's algorithm. In the following code block, we add a few pre-processing steps which:\n\n(1) Check if $n$ is even,\n\n(2) Check if $n$ is prime,\n\n(3) Check if $n$ is a prime power,\n\nall of which can be done efficiently with a classical computer. Additionally, we add the last necessary post-processing step which uses the order $r$ to compute a non-trivial factor $p$ of $n$. This is achieved by computing $y = x^{r / 2} \\text{ mod } n$ (assuming $r$ is even), then computing $p = \\text{gcd}(y - 1, n)$.\n\n\n```\n\"\"\"Functions for factoring from start to finish.\"\"\"\ndef find_factor_of_prime_power(n: int) -> Optional[int]:\n \"\"\"Returns non-trivial factor of n if n is a prime power, else None.\"\"\"\n for k in range(2, math.floor(math.log2(n)) + 1):\n c = math.pow(n, 1 / k)\n c1 = math.floor(c)\n if c1**k == n:\n return c1\n c2 = math.ceil(c)\n if c2**k == n:\n return c2\n return None\n\n\ndef find_factor(\n n: int,\n order_finder: Callable[[int, int], Optional[int]] = quantum_order_finder,\n max_attempts: int = 30\n) -> Optional[int]:\n \"\"\"Returns a non-trivial factor of composite integer n.\n\n Args:\n n: Integer to factor.\n order_finder: Function for finding the order of elements of the\n multiplicative group of integers modulo n.\n max_attempts: number of random x's to try, also an upper limit\n on the number of order_finder invocations.\n\n Returns:\n Non-trivial factor of n or None if no such factor was found.\n Factor k of n is trivial if it is 1 or n.\n \"\"\"\n # If the number is prime, there are no non-trivial factors.\n if sympy.isprime(n):\n print(\"n is prime!\")\n return None\n \n # If the number is even, two is a non-trivial factor.\n if n % 2 == 0:\n return 2\n \n # If n is a prime power, we can find a non-trivial factor efficiently.\n c = find_factor_of_prime_power(n)\n if c is not None:\n return c\n \n for _ in range(max_attempts):\n # Choose a random number between 2 and n - 1.\n x = random.randint(2, n - 1)\n \n # Most likely x and n will be relatively prime.\n c = math.gcd(x, n)\n \n # If x and n are not relatively prime, we got lucky and found\n # a non-trivial factor.\n if 1 < c < n:\n return c\n \n # Compute the order r of x modulo n using the order finder.\n r = order_finder(x, n)\n \n # If the order finder failed, try again.\n if r is None:\n continue\n \n # If the order r is even, try again.\n if r % 2 != 0:\n continue\n \n # Compute the non-trivial factor.\n y = x**(r // 2) % n\n assert 1 < y < n\n c = math.gcd(y - 1, n)\n if 1 < c < n:\n return c\n\n print(f\"Failed to find a non-trivial factor in {max_attempts} attempts.\")\n return None\n```\n\nThe function `find_factor` uses the `quantum_order_finder` by default, in which case it is executing Shor's algorithm. As previously mentioned, due to the large memory requirements for classically simulating this circuit, we cannot run Shor's algorithm for $n \\ge 15$. However, we can use the classical order finder as a substitute.\n\n\n```\n\"\"\"Example of factoring via Shor's algorithm (order finding).\"\"\"\n# Number to factor\nn = 184573\n\n# Attempt to find a factor\np = find_factor(n, order_finder=classical_order_finder)\nq = n // p\n\nprint(\"Factoring n = pq =\", n)\nprint(\"p =\", p)\nprint(\"q =\", q)\n```\n\n\n```\n\"\"\"Check the answer is correct.\"\"\"\np * q == n\n```\n", "meta": {"hexsha": "99e344ea6f268f05da1fb56fb5443fdd2d83828c", "size": 38564, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/tutorials/shor.ipynb", "max_stars_repo_name": "albertonavaa/Cirq", "max_stars_repo_head_hexsha": "76352585b9667873e60d51ee8cf7e6549c9d9a5e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-10-15T19:02:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-15T19:02:39.000Z", "max_issues_repo_path": "docs/tutorials/shor.ipynb", "max_issues_repo_name": "albertonavaa/Cirq", "max_issues_repo_head_hexsha": "76352585b9667873e60d51ee8cf7e6549c9d9a5e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-08-20T01:03:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-13T00:26:48.000Z", "max_forks_repo_path": "docs/tutorials/shor.ipynb", "max_forks_repo_name": "albertonavaa/Cirq", "max_forks_repo_head_hexsha": "76352585b9667873e60d51ee8cf7e6549c9d9a5e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-06-17T11:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-17T11:21:53.000Z", "avg_line_length": 34.7423423423, "max_line_length": 476, "alphanum_fraction": 0.552536044, "converted": true, "num_tokens": 6654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3153597131862265}} {"text": "# Data Analyst's Toolbox: R and Python\n\n> Institute of Political Science, NSYSU, 2020-12-25\n\nKuo, Yao-Jen from [DATAINPOINT](https://www.datainpoint.com)\n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n```\n\n## TL; DR\n\n\n\nSource: \n\n## About me\n\n## Teaching practical data science online/offline, for individuals\n\n- [如何成為資料分析師:從問題解決到行動方案,Hahow 好學校](https://hahow.in/cr/dajourney)\n- Visualization and modern data science, Adjunct Instructor, National Taiwan University\n- Programming and business analytics, Adjunct Instructor, National Taiwan Normal University\n- Python for data analysis, Instructor, Chunghwa Telecom Academy\n- Python for data science, Machine learning from scratch, Senior Instructor, CSIE Training Program, National Taiwan University\n\n## Also for commercial banking clients\n\n- 2020 DBS Training Program\n- 2019 HNCB Training Program\n- 2017 ESUN Training Program\n\n## Writing books\n\n- [新手村逃脫!初心者的 Python 機器學習攻略](https://www.books.com.tw/products/0010867390)\n- [進擊的資料科學](https://www.books.com.tw/products/0010827812)\n- [輕鬆學習 R 語言](https://www.books.com.tw/products/0010835361)\n\n## Writing blogs\n\n- [Medium](https://medium.com/@tonykuoyj)\n- [Substack](https://datainpoint.substack.com/about)\n- [方格子](https://vocus.cc/user/@yaojenkuo)\n\n## Before being a instructor\n\n- Working experience\n - Senior Data Analyst, Coupang Shanghai\n - Analytical Consultant, SAS Taiwan\n - Management Associate, Chinatrust Banking Corporation Taiwan\n - Research Assistant, McKinsey & Company Taiwan\n- Education\n - MBA, National Taiwan University\n - BA, National Taiwan University\n\n## Loves running with a marathon PR of 2:43:12 at 2019 Seoul Marathon\n\n\n\nSource: \n\n## What is data analysis\n\n## The definition\n\n> We generate questions about a specific topic, we search for answers by exploring, transforming, and modelling data referring to our topic. And then use what we've learned to refine questions or generate new questions.\n\nSource: [R for Data Science](https://r4ds.had.co.nz/)\n\n## Why data analysis\n\n> It is now an era of data-driven strategic thinking, and is probably never coming back.\n\n## The three means of persuasion that an orator must rely on\n\n- Ethos\n- Pathos\n- Logos\n\nSource: [Aristotle, Rhetoric](https://en.wikipedia.org/wiki/Rhetoric)\n\n## It is a lot easier to persuade via ethos or pathos, but it takes time\n\nHowever, logos can be easily acquired once it is a fact and can be proven. Hence, data analysis is often the express way to logos.\n\n## Modern data analysis can be illustrated as the flow of data\n\n\n\nSource: [R for Data Science](https://r4ds.had.co.nz/)\n\n## The funny definitions\n\n\n\nSource: \n\n\n\nSource: \n\n\n\nSource: \n\n## The serious definition\n\n> Modern data analysis invovles applications and tools like importing, tidying, transformation, visualization, modeling, and communication. Surrounding all these is programming.\n\n\n```python\ndef get_value_ratios(df, col_name):\n return df[col_name].value_counts() / df[col_name].value_counts().sum()\ndef get_checkbox_ratios(df, col_pattern):\n channel_names = []\n channel_checks = []\n for col_name in df.columns:\n if (col_pattern in col_name) and ('OTHER_TEXT' not in col_name):\n channel_name = df[col_name].value_counts().index\n channel_check = df[col_name].value_counts().values\n if channel_name.size != 0:\n channel_names.append(channel_name[0])\n channel_checks.append(channel_check[0])\n channel_counts = pd.Series(channel_checks, index=channel_names)\n channel_ratios = channel_counts / channel_counts.sum()\n channel_ratios_sorted = channel_ratios.sort_values(ascending=False)\n return channel_ratios_sorted\ndef plot_ans_38(ans_38_ser):\n fig = plt.figure()\n ax = plt.axes()\n ans_38_ser = ans_38_ser[::-1]\n ax.barh(ans_38_ser.index, ans_38_ser.values, color=['c', 'c', 'c', 'c', 'c', 'r'])\n ax.set_title(\"What is the primary tool that you use at work or school to analyze data?\")\n ax.set_xticks([0, 0.1, 0.2, 0.3, 0.4, 0.5])\n ax.set_xticklabels(['0%', '10%', '20%', '30%', '40%', '50%'])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n plt.show()\ndef get_ax(ans_ser, plot_title, ax):\n ax = ax\n ans_ser = ans_ser[:10][::-1]\n ax.barh(ans_ser.index, ans_ser.values, color=['c', 'c', 'c', 'c', 'c', 'c', 'c', 'r', 'r', 'r'])\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.set_title(plot_title)\ndef plot_ans(ans_ser, question_str):\n fig, axes = plt.subplots()\n get_ax(ans_ser, question_str, axes)\n plt.show()\nsurvey = pd.read_csv(\"https://kaggle-ml-ds-survey.s3-ap-northeast-1.amazonaws.com/kaggle-survey-2020/kaggle_survey_2020_responses.csv\", skiprows=[1])\nans_7 = get_checkbox_ratios(survey, 'Q7')\nans_8 = get_value_ratios(survey, 'Q8')\nans_38 = get_value_ratios(survey, 'Q38')\n```\n\n## Use programming language to analyze data\n\nLet's review a question from [2020 Kaggle ML & DS Survey](https://www.kaggle.com/c/kaggle-survey-2020):\n\n> What is the primary tool that you use at work or school to analyze data?\n\n\n```python\nplot_ans_38(ans_38)\n```\n\n## It seems inevitable to write codes in modern data analysis\n\n\n\nSource: \n\n## Simply put, we can choose any programming language as long as it is capable of\n\n- Importing data\n- Tidying data\n- Transforming data\n- Visualizing data\n- Modeling data\n- Communicating data\n\n## Well, actually a lot of programming languages are capable of doing these\n\n- Python\n- R\n- Julia\n- Scala\n- Matlab\n- SAS\n- ...etc.\n\n## How to choose among so many alternatives?\n\n- The philosophy of \"Eating a water mellon\".\n- The full support of scientific computing.\n- Our objectivity.\n\n## The philosophy of \"Eating a water mellon\"\n\nLet's review another 2 questions from [2020 Kaggle ML & DS Survey](https://www.kaggle.com/c/kaggle-survey-2020):\n\n- What programming languages do you use on a regular basis?\n- What programming language would you recommend an aspiring data scientist to learn first?\n\n\n```python\nplot_ans(ans_7, \"What programming languages do you use on a regular basis?\")\n```\n\n\n```python\nplot_ans(ans_8, \"What programming language would you recommend \\n an aspiring data scientist to learn first?\")\n```\n\n## R and Python in Stack Overflow Trends\n\n\n\n## The full support of scientific computing\n\n- Does the language support vectorization?\n- Does the language support various data format?\n- Does the language support visualization?\n\n## Both R and Python support vectorization\n\n- R uses built-in `vector` and `matrix`.\n- Python uses a third-party `ndarray`.\n\n## Both R and Python support various data format\n\n- R uses\n - built-in named `list` to support key-value storage\n - built-in `data.frame` to support tabular data\n- Python uses\n - built-in `dict` to support key-value storage\n - third-party `DataFrame` to support tabular data\n\n## Both R and Python support visualization\n\n- R uses\n - built-in basic plotting system to support static plotting\n - third-party `ggplot2` to support high-end static plotting\n - third-party `shiny` to support dynamic plotting\n- Python uses\n - third-party `matplotlib` to support static plotting\n - third-party `seaborn` to support high-end static plotting\n - third-party `plotly` to support dynamic plotting\n\n## Last but not least, it depends on our objectivity\n\n- Specific or general-purposed?\n- Functional or object-oriented?\n- ...etc.\n\n## We will generate our own objectivity once we start coding\n\n\n\nSource: \n\n## Let's write some codes to analyze data\n\n## Bringing up a topic\n\n> 大選開票看哪個里最準? 「章魚里」神預測告訴你。每次到了選舉,總是會有幾個里開票與大選結果相似,因此被各界視為重點關注的開票區域。\n\nSource: \n\n## We can generate some questions regarding this topic\n\n- How to define 「章魚里」?\n- Can we find out 「章魚里」 based on 2020 presidential data?\n- Can we find the similarity of our own village?\n\n## How to define 「章魚里」?\n\nBasically, after a few literature search, you may find the definition of 「章魚里」 is quite ambigious. So we are using a much fancier metric: **cosine similarity**.\n\n## What is cosine similarity\n\n> Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space. It is defined to equal the cosine of the angle between them, which is also the same as the inner product of the same vectors normalized to both have length 1.\n\n\\begin{equation}\na = (a_1, a_2, a_3) \\\\\nb = (b_1, b_2, b_3)\n\\end{equation}\n\n\\begin{align}\ncos\\theta &= \\frac{\\sum_i(a_i \\times b_i)}{\\sqrt{\\sum_i a_i^2} \\times \\sqrt{\\sum_i b_i^2}} \\\\\n&= \\frac{a \\cdot b}{\\parallel a \\parallel \\times \\parallel b \\parallel}\n\\end{align}\n\nSource: \n\n## Can we find out 「章魚里」 based on 2020 presidential data?\n\nDefinitely, we all have access to the [Central Election Commission](https://db.cec.gov.tw/).\n\n## We've downloaded these spreadsheets and prepared an in-browser environment for you.\n\n[](https://mybinder.org/v2/gh/yaojenkuo/talks/HEAD)\n\n## We can access to a Python notebook, R notebook, or RStudio in browser, no strings attached.\n\n\n\n## Besides a few kernels to execute, we also attached some data.\n\n- Reading a CSV file.\n- Reading a Excel spreadsheet.\n\n\n```python\n# reading data via Python's pandas library\ncsv_df = pd.read_csv('presidential_2020.csv')\nexcel_df = pd.read_excel('presidential-2020/總統-A05-4-候選人得票數一覽表-各投開票所(南投縣).xls', skiprows=[0, 1, 3, 4])\n```\n\n## Our CSV file is an integrated file after manipulations\n\n\n```python\ncsv_df.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countytownvillageofficenumbercandidatevotes
0宜蘭縣宜蘭市民族里11宋楚瑜/余湘37
1宜蘭縣宜蘭市民族里21宋楚瑜/余湘31
2宜蘭縣宜蘭市建軍里31宋楚瑜/余湘19
3宜蘭縣宜蘭市建軍里41宋楚瑜/余湘29
4宜蘭縣宜蘭市泰山里51宋楚瑜/余湘25
\n
\n\n\n\n## Our Excel spreadsheets are the original files downloaded from [Central Election Commission](https://db.cec.gov.tw/)\n\n\n```python\nexcel_df.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Unnamed: 0Unnamed: 1Unnamed: 2(1)\\n宋楚瑜\\n余湘(2)\\n韓國瑜\\n張善政(3)\\n蔡英文\\n賴清德Unnamed: 6Unnamed: 7Unnamed: 8Unnamed: 9Unnamed: 10Unnamed: 11Unnamed: 12Unnamed: 13
0總 計NaNNaN13,315133,791152,046299,1523,555302,70713302,720110,765413,48573.2087
1南投市NaNNaN3,07726,69030,91060,67769361,370361,37320,48081,85374.9759
2NaN龍泉里1.0262413916588666066622889474.4966
3NaN康壽里2.0302162665124516051612864480.1242
4NaN康壽里3.0252393065708578057815473278.9617
\n
\n\n\n\n## We can also try importing via the RStudio interface.\n\n```r\nlibrary(readxl)\n\ncsv_df = read.csv('presidential_2020.csv')\nexcel_df = read_excel('presidential-2020/總統-A05-4-候選人得票數一覽表-各投開票所(南投縣).xls')\nhead(csv_df)\nhead(excel_df)\n```\n\n## We write codes to integrate these spreadsheets into a CSV file\n\n\n```python\nfrom presidential import Presidential\n\npresidential = Presidential('presidential-2020')\npresidential_df = presidential.adjust_presidential_df()\npresidential_df.to_csv('presidential_2020.csv', index=False)\n```\n\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(宜蘭縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(彰化縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(金門縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(桃園市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(苗栗縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(臺南市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(雲林縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(南投縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(高雄市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(臺北市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(新北市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(花蓮縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(新竹市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(新竹縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(基隆市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(連江縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(嘉義縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(嘉義市).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(屏東縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(澎湖縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(臺東縣).xls\n Tidying 總統-A05-4-候選人得票數一覽表-各投開票所(臺中市).xls\n\n\n\n```python\npresidential_df.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countytownvillageofficenumbercandidatevotes
0宜蘭縣宜蘭市民族里11宋楚瑜/余湘37
1宜蘭縣宜蘭市民族里21宋楚瑜/余湘31
2宜蘭縣宜蘭市建軍里31宋楚瑜/余湘19
3宜蘭縣宜蘭市建軍里41宋楚瑜/余湘29
4宜蘭縣宜蘭市泰山里51宋楚瑜/余湘25
\n
\n\n\n\n\n```python\npresidential_df.tail()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
countytownvillageofficenumbercandidatevotes
51673臺中市和平區梨山里18453蔡英文/賴清德132
51674臺中市和平區梨山里18463蔡英文/賴清德107
51675臺中市和平區梨山里18473蔡英文/賴清德40
51676臺中市和平區平等里18483蔡英文/賴清德24
51677臺中市和平區平等里18493蔡英文/賴清德102
\n
\n\n\n\n## Check if the summations are right with Python\n\n\n```python\nttl_votes = presidential_df['votes'].sum()\nttl_votes_by_candidates = presidential_df.groupby('number')['votes'].sum()\nttl_votes_by_candidates\n```\n\n\n\n\n number\n 1 608590\n 2 5522119\n 3 8170231\n Name: votes, dtype: int64\n\n\n\n## Check if the summations are right with R\n\n```r\nlibrary(dplyr)\n\ncsv_df %>% \n group_by(number) %>% \n summarise(ttl_votes = sum(votes))\n```\n\n## National percentage is our target vector to be compared\n\n\n```python\nnational_percentage = ttl_votes_by_candidates / ttl_votes\nnational_percentage\n```\n\n\n\n\n number\n 1 0.042556\n 2 0.386137\n 3 0.571307\n Name: votes, dtype: float64\n\n\n\n## Total votes for each village\n\n\n```python\ncombined_key = presidential_df['county'].str.cat(presidential_df['town']).str.cat(presidential_df['village'])\npresidential_df = presidential_df.assign(combined_key=combined_key)\nttl_votes_by_combined_key = presidential_df.groupby(['combined_key'])['votes'].sum()\nttl_votes_by_combined_key\n```\n\n\n\n\n combined_key\n 南投縣中寮鄉中寮村 443\n 南投縣中寮鄉內城村 297\n 南投縣中寮鄉八仙村 535\n 南投縣中寮鄉和興村 422\n 南投縣中寮鄉崁頂村 304\n ... \n 高雄市鼓山區鼓岩里 847\n 高雄市鼓山區鼓峰里 1425\n 高雄市鼓山區龍井里 906\n 高雄市鼓山區龍子里 11410\n 高雄市鼓山區龍水里 16333\n Name: votes, Length: 7737, dtype: int64\n\n\n\n## Votes percentage by each candidate and village\n\n\n```python\nttl_votes_by_combined_key_candidates = presidential_df.groupby(['combined_key', 'number'])['votes'].sum()\nsoong = ttl_votes_by_combined_key_candidates[:, '1'] / ttl_votes_by_combined_key\nhan = ttl_votes_by_combined_key_candidates[:, '2'] / ttl_votes_by_combined_key\ntsai = ttl_votes_by_combined_key_candidates[:, '3'] / ttl_votes_by_combined_key\nvotes_obtained = pd.concat([soong, han, tsai], axis=1)\nvotes_obtained.columns = ['soong', 'han', 'tsai']\n```\n\n\n```python\nvotes_obtained\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
soonghantsai
combined_key
南投縣中寮鄉中寮村0.0406320.4898420.469526
南投縣中寮鄉內城村0.0572390.4747470.468013
南投縣中寮鄉八仙村0.0392520.4355140.525234
南投縣中寮鄉和興村0.0213270.5000000.478673
南投縣中寮鄉崁頂村0.0526320.3815790.565789
............
高雄市鼓山區鼓岩里0.0141680.3093270.676505
高雄市鼓山區鼓峰里0.0329820.4736840.493333
高雄市鼓山區龍井里0.0231790.3675500.609272
高雄市鼓山區龍子里0.0323400.3814200.586240
高雄市鼓山區龍水里0.0376540.3989470.563399
\n

7737 rows × 3 columns

\n
\n\n\n\n## Calculate cosine similarity\n\n\n```python\na = national_percentage.values\na_norm = np.linalg.norm(a)\ncos_similarities = []\nfor i in range(votes_obtained.shape[0]):\n b = votes_obtained.iloc[i, :].values\n b_norm = np.linalg.norm(b)\n ab = np.dot(a, b)\n cos_similarity = np.dot(a, b) / (a_norm*b_norm)\n cos_similarities.append(cos_similarity)\nvotes_obtained = votes_obtained.assign(cosine_similarity=cos_similarities)\nvotes_obtained = votes_obtained.reset_index()\n```\n\n\n```python\nvotes_obtained.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
combined_keysoonghantsaicosine_similarity
0南投縣中寮鄉中寮村0.0406320.4898420.4695260.977648
1南投縣中寮鄉內城村0.0572390.4747470.4680130.980246
2南投縣中寮鄉八仙村0.0392520.4355140.5252340.995217
3南投縣中寮鄉和興村0.0213270.5000000.4786730.977015
4南投縣中寮鄉崁頂村0.0526320.3815790.5657890.999882
\n
\n\n\n\n## Sort by cosine similarity with descending order to find 「章魚里」\n\n\n```python\nvotes_obtained.sort_values(['cosine_similarity', 'combined_key'], ascending=[False, True]).reset_index(drop=True).head(10)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
combined_keysoonghantsaicosine_similarity
0嘉義縣番路鄉內甕村0.0425530.3860180.5714291.000000
1臺南市東區關聖里0.0424500.3862950.5712551.000000
2臺南市中西區南門里0.0434100.3854600.5711300.999999
3新北市汐止區保長里0.0428330.3868470.5703200.999999
4新北市金山區五湖里0.0437650.3856320.5706030.999998
5臺北市南港區東新里0.0420360.3852980.5726660.999997
6臺北市內湖區西湖里0.0412850.3860080.5727070.999997
7新北市中和區清穗里0.0418650.3853470.5727880.999997
8臺南市北區重興里0.0428370.3848310.5723310.999997
9新北市板橋區景星里0.0425150.3876070.5698780.999996
\n
\n\n\n\n## Can we find the similarity of our own village?\n\nDefinitely.\n\n\n```python\ndef find_my_village(my_village, df):\n df = df.sort_values(['cosine_similarity', 'combined_key'], ascending=[False, True]).reset_index(drop=True)\n my_village_df = df[df['combined_key'] == my_village]\n return my_village_df\n```\n\n\n```python\nmy_village = '高雄市鼓山區桃源里'\nmy_village_df = find_my_village(my_village, votes_obtained)\nmy_village_similarity = my_village_df['cosine_similarity'].values[0]\nmy_village_rank = my_village_df.index[0]\nn_rows = votes_obtained.shape[0]\nprint(\"{}的餘弦相似度為{:.4f}, 排名{}/{}\".format(my_village, my_village_similarity, my_village_rank, n_rows))\nmy_village_df\n```\n\n 高雄市鼓山區桃源里的餘弦相似度為0.9985, 排名1714/7737\n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
combined_keysoonghantsaicosine_similarity
1714高雄市鼓山區桃源里0.0234190.3700230.6065570.998506
\n
\n\n\n\n## Feeling movivated?\n\n## Start with the most practical one: Python\n\n- Procedural programming with Python\n- Object-oriented programming with Python\n- Using Python libraries\n\n## Start with the most practical one: R\n\n- Procedural programming with R\n- Functional programming with R\n- Using R libraries\n\n## Resources I've used when learning Python\n\n- [Introducing Python](https://www.amazon.com/Introducing-Python-Modern-Computing-Packages/dp/1449359361)\n- [A Whirlwind Tour of Python](https://jakevdp.github.io/WhirlwindTourOfPython/index.html)\n- [Python Data Science Handbook](https://jakevdp.github.io/PythonDataScienceHandbook/)\n\n## Resources I've used when learning R\n\n- [The Art of R Programming](https://www.amazon.com/Art-Programming-Statistical-Software-Design/dp/1593273843)\n- [Advanced R](https://adv-r.hadley.nz/)\n- [R for Data Science](https://r4ds.had.co.nz/)\n- [Data Science Specialization](https://www.coursera.org/specializations/jhu-data-science)\n- [Statistics with R Specialization](https://www.coursera.org/specializations/statistics)\n\n## Learning resources from me\n\n- [數據交點](https://www.datainpoint.com)\n- [Substack](https://datainpoint.substack.com/about)\n\n## Phew, that is a lot to catch up...\n\nYou do not have to finish every course or book from end to end.\n\n\n\nSource: \n", "meta": {"hexsha": "30f8e041054f2189e4033ef3c6bce04f2c60ffe7", "size": 113258, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "data-analysts-toolbox.ipynb", "max_stars_repo_name": "yaojenkuo/talks", "max_stars_repo_head_hexsha": "6a3ba1b2da01b81ade2045cc9d6de034a59b451d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data-analysts-toolbox.ipynb", "max_issues_repo_name": "yaojenkuo/talks", "max_issues_repo_head_hexsha": "6a3ba1b2da01b81ade2045cc9d6de034a59b451d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-12-23T03:37:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-23T03:37:43.000Z", "max_forks_repo_path": "data-analysts-toolbox.ipynb", "max_forks_repo_name": "yaojenkuo/talks", "max_forks_repo_head_hexsha": "6a3ba1b2da01b81ade2045cc9d6de034a59b451d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.1784907366, "max_line_length": 27292, "alphanum_fraction": 0.6905384167, "converted": true, "num_tokens": 10989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.31524072154450117}} {"text": "# Python 预缓存的 Property 修饰器简单实现\n\n> 创建时间:2021-03-19\n\n这份简短笔记,我们会讨论预缓存 Python Property (类属性) 的简单实现。\n\n在运行程序时,特别是对于耗时但不耗内存、以后需要经常取用的计算,我们会希望找个内存或硬盘空间储存起来。为了方便起见,我们只讨论借用内存的方法。\n\n假设现在的问题是,我们要计算 $c = a+b, d = a^2$。为了调用的便利,$a, b$ 两个变量 (作为常数) 作为 property。\n\n但麻烦之处在于,$a, b$ 的值并不容易求,求完之后对内存的消耗却又不大。(嘛先不要追问为什么求个 1+1 要这么复杂)\n\n$$\n\\begin{align}\na &= \\sum_{n = 1}^{\\infty} \\frac{1}{2^n} \\simeq \\sum_{n = 1}^{1000} \\frac{1}{2^n} \\\\\nb &= \\int_0^1 3 x^2 \\, \\mathrm{d} x \\simeq \\sum_{n = 0}^{5000} \\frac{3 n^2}{5000^3}\n\\end{align}\n$$\n\n同时,我们也不清楚末端用户是否需要求 $c$ (需要同时计算 $a$, $b$),还是需要求 $d$ (只需要计算 $a$ 即可)。\n\n\n```python\ndef get_a():\n a = 0\n for n in range(1, 1001):\n a += 1 / 2**n\n return a\n```\n\n\n```python\ndef get_b():\n b = 0\n for n in range(5001):\n b += 3 * n**2 / 5000**3\n return b\n```\n\n这篇文档讨论四种做法。第一种做法简单但低效;第二、三种做法代码较复杂;第四种代码简单且不会产生多余的计算。作者倾向使用 [第三种](#偷懒的做法:将赋值函数嵌入-getter-函数) 与 [第四种](#改进的做法:缩减隐含变量的声明) 做法。\n\n## 即时调用 property 定义方法\n\n最简单粗暴的方法是需要 $a, b$ 时就现场计算。在第一次调用 $a, b$ 时固然需要耗时的计算,但第二次调用仍然会相当费时。\n\n\n```python\nclass Dummy:\n \n @property\n def a(self):\n return get_a()\n \n @property\n def b(self):\n return get_b()\n \n @property\n def c(self):\n return self.a + self.b\n \n @property\n def d(self):\n return self.a**2\n```\n\n\n```python\ndum = Dummy()\ndum.c\n```\n\n\n\n\n 2.00030002\n\n\n\n\n```python\n%%timeit -n 50\ndum.c\n```\n\n 2.41 ms ± 172 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)\n\n\n## 一般的 property 做法\n\n为了避免多余的计算,一般的方法是,需要首先在 `__init__` 中声明两个隐含变量 `_a`, `_b` 以保存结果。在使用 `a`, `b` 两个 property 之前,先要使用 setter 函数作 $a, b$ 的计算并分别保存到 `_a`, `_b` 中;随后再用 getter 函数调用它们。\n\n\n```python\nclass General:\n \n def __init__(self):\n self._a = NotImplemented\n self._b = NotImplemented\n \n @property\n def a(self):\n return self._a\n \n @a.setter\n def a(self, val):\n self._a = val\n \n @property\n def b(self):\n return self._a\n \n @b.setter\n def b(self, val):\n self._b = val\n \n @property\n def c(self):\n return self.a + self.b\n \n @property\n def d(self):\n return self.a**2\n```\n\n如果没有预先使用 setter 函数,就会碰到下面这种尴尬的情况:\n\n\n```python\ngen = General()\ngen.c\n```\n\n因此,正确的调用方式是\n\n\n```python\ngen = General()\ngen.a, gen.b = get_a(), get_b()\ngen.c, gen.d\n```\n\n\n\n\n (2.0, 1.0)\n\n\n\n上面的步骤是耗时的,但随后当要调用 `a`, `b` 变量时,就会快捷很多:\n\n\n```python\n%%timeit -n 50\ngen.c\n```\n\n 265 ns ± 28 ns per loop (mean ± std. dev. of 7 runs, 50 loops each)\n\n\n但这里有一个问题:$a, b$ 的值实际上可以看作常数;如果末端用户真正希望得到的是 $d = a^2$ 而非 $c = a + b$,那么实际上用户不需要 $b$,自然也就不需要对其花时间赋值了。决定是否要对 $b$ 赋值的任务由此交给末端用户,这会造成一些困扰。\n\n## 偷懒的做法:将赋值函数嵌入 getter 函数\n\n如果这个任务交给程序编写者,那么一种最简单的实现方式是把赋值函数嵌入到 getter 函数中:\n\n- 如果 $a$ 的值已经被计算过,那么就从缓存空间 `_a` 取出该值;\n\n- 如果 $a$ 被调用前没有被计算过,那么就计算该值并放入缓存 `_a`。\n\n\n```python\nclass Improved:\n \n def __init__(self):\n self._a = NotImplemented\n self._b = NotImplemented\n \n @property\n def a(self):\n if self._a is NotImplemented:\n self._a = get_a()\n return self._a\n \n @property\n def b(self):\n if self._b is NotImplemented:\n self._b = get_b()\n return self._b\n \n @property\n def c(self):\n return self.a + self.b\n \n @property\n def d(self):\n return self.a**2\n```\n\n如果末端用户只需要求 $d = a^2$,那么耗费时间的关键步就只有 $a$ 的计算;缓存空间 `_b` 就是空的。\n\n\n```python\nimp = Improved()\nprint(imp.d)\nprint(imp._b)\n```\n\n 1.0\n NotImplemented\n\n\n同时,以后再需要调用 $d$ 时,$a$ 的值也不会再被计算第二次。\n\n当然,这种做法的弊端是,用户原则上无权限更改 $a, b$ 的值 (通过更改隐含变量 `_a`, `_b` 是可能的,但这违背了 PEP8 的程序规范)。\n\n## 改进的做法:缩减隐含变量的声明\n\n但上面的定义仍然有很多冗余。对于每个 property,我们总要声明隐含变量、调用时判断是否缓存空间存在。这两步可以通过改编在 property 修饰器内部增加一段代码方便地实现。这个修饰器我们命名为 `cached_property`:\n\n\n```python\ndef cached_property(f):\n def wrap(*args, **kwargs):\n self = args[0] # self\n _f = \"_\" + f.__name__ # _a\n if not hasattr(self, _f) or getattr(self, _f) is NotImplemented: # if self._a is NotImplemented:\n setattr(self, _f, f(*args)) # self._a = get_a()\n return getattr(self, _f) # return self._a\n return property(wrap) # make this wrap a property\n```\n\n这样之后,不仅代码量减少很多 (调用方式与最简单的 `Dummy` 完全一致),同时也避免多余重复的计算。\n\n\n```python\nclass Advanced:\n \n @cached_property\n def a(self):\n return get_a()\n \n @cached_property\n def b(self):\n return get_b()\n \n @property\n def c(self):\n return self.a + self.b\n \n @property\n def d(self):\n return self.a**2\n```\n\n\n```python\nadv = Advanced()\nprint(adv.d)\nprint(hasattr(adv, \"_b\"))\n```\n\n 1.0\n False\n\n", "meta": {"hexsha": "b85c6f01b48bfafc90d21e33065e9900f503434b", "size": 13282, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "source/Simple_Notes/cached_property.ipynb", "max_stars_repo_name": "ajz34/ajz34.readthedocs.io", "max_stars_repo_head_hexsha": "73be05a73241c18b98fd0d4dbdc48c643278c3da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-07-30T12:31:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T03:56:56.000Z", "max_issues_repo_path": "source/Simple_Notes/cached_property.ipynb", "max_issues_repo_name": "ajz34/ajz34.readthedocs.io", "max_issues_repo_head_hexsha": "73be05a73241c18b98fd0d4dbdc48c643278c3da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Simple_Notes/cached_property.ipynb", "max_forks_repo_name": "ajz34/ajz34.readthedocs.io", "max_forks_repo_head_hexsha": "73be05a73241c18b98fd0d4dbdc48c643278c3da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-07-30T12:32:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T12:32:09.000Z", "avg_line_length": 24.7798507463, "max_line_length": 933, "alphanum_fraction": 0.4916428249, "converted": true, "num_tokens": 2236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3145090531165992}} {"text": "# FastEMRIWaveforms Tutorial\n## ICERM Workshop: Waveform acceleration with machine learning and GPUs\n\n### Michael Katz, Max Planck Institute for Gravitational Physics (Albert Einstein Institute), Lead developer for FastEMRIWaveforms\n\nIn this tutorial, you will learn the basics of building an accelereated EMRI waveform. We encourage participants to see our paper ([arxiv.org/2008.06071](https://arxiv.org/abs/2008.06071)) and the FastEMRIWaveforms [package documentation](https://bhptoolkit.org/FastEMRIWaveforms/) for more information, as well as our forthcoming paper that will describe the waveform in much more detail than our PRL submission. \n\nImport packages:\n\n\n```python\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\n\nimport h5py\n\n\nfrom few.amplitude import romannet\nfrom few.utils.utility import check_for_file_download, p_to_y\nfrom few.trajectory.flux import RunSchwarzEccFluxInspiral\nfrom few.amplitude.romannet import RomanAmplitude\nfrom few.amplitude.interp2dcubicspline import Interp2DAmplitude\nfrom few.waveform import FastSchwarzschildEccentricFlux\n```\n\n Matplotlib is building the font cache; this may take a moment.\n\n\n## A Quick Introduction to FastEMRIWaveforms\n\n### Collaborators: Alvin Chua, Niels Warburton, Scott Hughes, Lorenzo Speri\n\n\n```python\ngenerate = FastSchwarzschildEccentricFlux()\n\nM = 1e6 # large mass\nmu = 1e1 # small mass\np0 = 12.0 # separation \ne0 = 0.4 # eccentricity\ntheta = np.pi/3. # polar viewing angle\nphi = np.pi/4. # azimuthal viewing angle\ndist = 1.0 # distance in Gpc\n\nT = 1/365. # in years\ndt = 10.0 # time spacing of data stream\n\nwave = generate(M, mu, p0, e0, theta, phi, dist, T=T, dt=dt)\n\nplt.plot(wave.real)\nplt.plot(wave.imag)\n```\n\nFastEMRIWaveforms is the first fully relativistic template generation tool for extreme mass ratio inspirals. We think of it more as a framework than any specific waveform. In this tutorial, we will discuss the main pieces of this framework and how they relate to our first fully relativistic waveform model shown above. \n\nAs a basic primer, our five key points we want to achieve with this framework are:\n\n* Accuracy: Our fast waveforms must be accurate when compared to slow and accurate waveforms generated by the waveform modeling community.\n\n* Modularity: These waveforms are to be built out of a set of modules. These modules are to be easily interchangeable, as well as stand alone tools available for more in-depth analysis.\n\n* Flexibility: This framework must be easily adaptable to new computational methods and/or improvements in EMRI physics. \n\n* Easy User Interface: All modules and complete waveforms are to have a front-facing python interface with clear and extensive documentation, as well as many examples.\n\n* Parallelization: These waveforms must take advantage of parallelization techniques such as OpenMP, as well as accelerator hardware such as GPUs. \n\n## Basics of an EMRI Waveform\n\nThe guiding equation for building an EMRI waveform is given by\n\n\\begin{equation}\nh_+-ih_x = \\frac{1}{r}\\sum_{lmkn}\\left(-\\frac{Z_{lmkn}}{\\omega_{mkn}^2}\\right)\\left(S_{lmkn}(\\theta)e^{-im\\phi}\\right)e^{i\\Phi_{mkn}} = \\frac{1}{r}\\sum_{lmkn}A_{lmkn}\\Theta_{lmkn}e^{i\\Phi_{mkn}}.\n\\end{equation}\n\n\n\nHere we are concerned with generating fast and accurate waveforms. These waveforms are created with a sequence of modules. We will discuss the three main modules used to produce these waveforms. The first module is the Trajectory module which takes initial parameters and produces arrays for all of the evolving quantities of concern. These include the phase evolution, {$\\Phi_\\varphi,\\Phi_\\theta, \\Phi_r$}, from the start to the end of the EMRI orbit. With these quantities, we can produce:\n\n\\begin{equation}\n\\Phi_{mkn} = m\\Phi_\\varphi + k\\Phi_\\theta + n\\Phi_r.\n\\end{equation}\n\nThe trajectory also produces orbital quantities over time. These include the separation ($p$), eccentricity ($e$), and the inclination angle of the orbit ($\\iota$). With these arrays containing the orbital evolution of these values, we generate the amplitudes, $A_{lmkn}$. While the evolution is over time, the various phasing and amplitude computations are produced within a frequency decomposition into $(l,m,k,n)$ modes.\n\nWith phases and amplitdues in hand, we combine this with the angular harmonic information ($\\Theta_{lmkn}$) to produce the final waveform. In this step, we calculate the sum of all modes at each time point in the template data stream. \n\n## Overall Waveform Strategy\n\n* We calculate our trajectories and amplitudes as sparse arrays in time by using a large adaptive stepping integrator. This produces arrays with $\\sim100$ points. All of these quantities vary slowly and smoothly. After these calculations are complete, we scale this up to the actual data stream cadence. \n\n* The speed of EMRI waveforms is strongly determined by the amount of harmonic content. Higher eccentricities require more modes to produce a high fidelity waveform. In order to make our waveforms as efficient as possible, we perform an online mode content calculation that removes modes from consideration if they do not contribute to the waveform power determined by a user-defined threshold. \n\n## Current Waveform Model: Schwarzschild Eccentric\n\n* No $k$ modes\n* Orbit is equatorial\n* $S_{lmkn}(\\theta)e^{-im\\phi}$ reduces to $_{-2}Y_{lm}(\\theta,\\phi)$\n* $l:\\{2,10\\}$, $m:\\{-l,l\\}$, $n:\\{-30,30\\}$ $\\rightarrow$ 3843 modes. \n\n## Fast Trajectories: $\\{p, e, \\Phi_\\varphi, \\Phi_r\\}$\n\nWe are not going to spend too much time on the trajectory part. However, we need to generate it in order to build the rest of our waveform. To build the trajectory, we integrate with large steps using an RK8 integrator. \n\n\n```python\ntraj = RunSchwarzEccFluxInspiral()\n```\n\n\n```python\np0 = 16.0 # initial separation\ne0 = 0.4 # initial eccentricity\nmu = 180. # iniital small mass in solar masses, produces approximately 1 yr waveform\nM = 1e6 # initial large mass in solar masses\ndt = 10.0 # sets initial step size\nT = 1.0 # in years\n\nt, p, e, Phi_phi, Phi_r, flux = traj(M, mu, p0, e0, T=T, dt=dt)\nprint(\"length:\", len(t), \"duration:\", t[-1])\n```\n\n length: 122 duration: 29164387.553433623\n\n\n\n```python\nfig, axes = plt.subplots(2, 3)\nplt.subplots_adjust(wspace=0.3)\nfig.set_size_inches(14, 8)\naxes = axes.ravel()\n\nylabels = [r'$e$', r'$p$', r'$e$', r'$\\Phi_\\phi$', r'$\\Phi_r$', r'Flux']\nxlabels = [r'$p$', r'$t$', r'$t$', r'$t$', r'$t$', r'$t$', r'$t$', r'$t$']\nys = [e, p, e, Phi_phi, Phi_r, flux]\nxs = [p, t, t, t, t, t]\n\nfor i, (ax, x, y, xlab, ylab) in enumerate(zip(axes, xs, ys, xlabels, ylabels)):\n ax.plot(x, y, lw=0.5)\n ax.scatter(x, y, s=5)\n ax.set_xlabel(xlab, fontsize=16)\n ax.set_ylabel(ylab, fontsize=16)\n```\n\n## RomanNet Amplitudes: $A_{lmn}$\n\nTo generate the amplitudes, we use a RomanNet ([arXiv:1811.05491](https://arxiv.org/abs/1811.05491)). Roman stands for Reduced Order Modelling with Artificial Neurons. When training a neural network, it can be crucial to hand it data that is distilled to highlight the most pertinent information. A nice tool for doing this is Reduced Order Modeling. Reduced order modelling projects the information with lossless compression down to a lower dimensional space. We take our complex mode amplitude vectors containing 3843 modes and project this down to a real-valued space with 198 values. The neural network is then trained with inputs given by the $p$ and $e$ values and outputs given by the reduced order coefficients ($\\alpha_i$):\n\n\\begin{equation}\nA_{lmn}\\in\\mathbb{C}^{3843}\\xrightarrow{\\mathit{ROM}}\\alpha_i\\in\\mathbb{R}^{198}\\xrightarrow{\\mathit{train}} f(p,e)=\\alpha_i\n\\end{equation}\n\nThe neural network itself is extremely simple. It is a fully connected network with a LeakyReLU activation on all layers but the final layer. This means the neural network can be built simply with a sequence of linear matrix multiplications followed by a pass through the activation function. Once the neural network is trained, we will have a set of weights. This is where we will start in this tutorial. \n\nDuring online evaluation of the waveform, we perform the reverse process:\n\n\\begin{equation}\nf(p,e)\\xrightarrow{\\mathit{eval}}\\alpha_i\\in\\mathbb{R}^{198}\\xrightarrow{\\mathit{project}}A_{lmn}\\in\\mathbb{C}^{3843}\n\\end{equation}\n\nThis method has pros and cons:\n\nPros:\n\n* This is more of a global fit, rather than individual fits to given modes. This generally means storage of less information in memory. If we do individual fits of every mode, the memory necessary to store this information would scale badly with mode content. We are currently working in Schwarzschild Eccentric. As we go to generic Kerr, we expect the number of modes to increase by a factor of $\\sim10$.\n\n* Due to its global fit nature, this method is generally faster to evaluate than individual interpolants. \n\n* Since it is a neural network and a linear projection, this is very suitable to GPUs.\n\n* We expect this method, or methods similar to this, to scale better with dimensionality as we move towards the end goal of generic Kerr orbits. \n\nCons:\n\n* For extremely quiet modes, this method can be less accurate. However, as these modes are quiet, this does not result in a significant loss of accuracy in the final waveform. Caution must be taken when using this method to analyze individual mode amplitudes. There is an approximate floor in the amplitude values at $\\sim10^{-5}$. For reference, the loudest modes at a given $p$ and $e$ value are usually $\\sim0.1-1.0$. (These amplitudes are not scaled for distance.|) \n\n* Training these neural networks can be more of an art than a science. It takes a lot of trial and error to get this right. \n\n### Constructing the neural network from trained weights\n\n\n```python\n\n\n# prepare to load the weights\n\npath_to_few_dir = romannet.__file__[:-25]\n\nweight_file = fp = \"SchwarzschildEccentricInput.hdf5\"\ncheck_for_file_download(fp, path_to_few_dir)\n\nweights = []\nbias = []\ndim1 = []\ndim2 = []\n\n# get highest layer number\nnum_layers = 0\n\n# extract all necessary information from the file\nwith h5py.File(path_to_few_dir + \"few/files/\" + weight_file, \"r\") as fp:\n \n # get basic information\n num_teuk_modes = fp.attrs[\"num_teuk_modes\"]\n transform_factor = fp.attrs[\"transform_factor\"]\n break_index = fp.attrs[\"break_index\"]\n \n # determine layer arrangement \n for key, value in fp.items():\n if key == \"reduced_basis\":\n continue\n\n layer_num = int(key[1:])\n\n if layer_num > num_layers:\n num_layers = layer_num\n\n # get weights and bias\n for i in range(1, num_layers + 1):\n temp = {}\n for let in [\"w\", \"b\"]:\n mat = fp.get(let + str(i))[:]\n temp[let] = np.asarray(mat)\n\n weights.append(temp[\"w\"])\n bias.append(temp[\"b\"])\n dim1.append(temp[\"w\"].shape[0])\n dim2.append(temp[\"w\"].shape[1])\n\n # get the post network transform matrix\n transform_matrix = np.asarray(fp[\"reduced_basis\"])\n\n# activation function\n# we use a factor of 0.2 for negative values\ndef LeakyReLU(x):\n out = (x >= 0.0) * x + (x < 0.0) * 0.2*x\n return out\n\n# build the neural network\ndef RomanNet(p, e):\n \n p = np.atleast_1d(p)\n e = np.atleast_1d(e)\n \n # convert from the p coordinate to a special y coordinate\n # see the documentation for more details\n y = p_to_y(p, e)\n \n # prepare input\n x = np.array([y, e])\n \n # basic fully connected network\n for layer_i in range(num_layers):\n \n # linear transformation\n x = np.dot(weights[layer_i].T, x) + bias[layer_i][:, np.newaxis]\n \n # do not want to activate last layer\n if layer_i < num_layers - 1:\n # non-linear activatation\n x = LeakyReLU(x)\n \n # separate real and imaginary\n x = x[:break_index] + 1j * x[break_index:]\n \n # project back to amplitude basis\n out = np.dot(transform_matrix.T, x)/transform_factor\n return out.T\n \n \n```\n\n\n```python\n# test it\np_test = np.array([11.0, 10.0, 10.0])\ne_test = np.array([0.2, 0.3, 0.1])\n\nRomanNet(p_test, e_test)\n```\n\n\n\n\n array([[ 6.61875897e-06-9.45689250e-06j, 6.69607160e-06-1.13351771e-05j,\n 6.41141133e-06-1.40002164e-05j, ...,\n 7.50732732e-05+2.44753603e-05j, 6.73201363e-05-2.51759069e-06j,\n -2.62936078e-07-1.61971784e-05j],\n [-3.03984515e-05+2.23504926e-06j, -3.46638688e-05+2.11040541e-06j,\n -3.99084181e-05+1.67172621e-06j, ...,\n 8.48364501e-05-3.51356321e-05j, 1.27022103e-04-6.69149191e-06j,\n 9.19366706e-05+1.92716832e-05j],\n [-1.78544871e-06+1.54745952e-05j, -1.96676157e-06+1.75539377e-05j,\n 7.20295633e-07+2.05609755e-05j, ...,\n -1.38437626e-05+1.46714870e-05j, -2.75508914e-05+9.37792116e-06j,\n 1.12870278e-05+7.38750376e-06j]])\n\n\n\n### Produce amplitudes associated with our trajectories\n\n\n```python\n# generate amplitudes with roman net\namps = RomanNet(p, e)\n\n# check against actual code\nRomanNetTrue = RomanAmplitude()\namps_check_1 = RomanNetTrue(p, e)\n\nassert np.allclose(amps, amps_check_1)\n```\n\n### Check our RomanNet global fit against accurate values\n\n\n```python\n# get accurate values \n# each mode is fitted with a bicubic spline\nBicubicAmps = Interp2DAmplitude()\namps_check_2 = BicubicAmps(p, e)\n```\n\n#### Print vectors\n\n\n```python\nprint(\"romannet:\", amps_check_1[0][0:10], \"\\nBicubic Spline:\", amps_check_2[0][0:10])\n```\n\n romannet: [7.69192924e-06-5.39154229e-06j 9.99753291e-06-6.31307778e-06j\n 1.35171826e-05-8.06391248e-06j 1.78239290e-05-7.33261441e-06j\n 2.14797124e-05-6.31329971e-06j 2.57309168e-05-3.37761067e-06j\n 2.89725596e-05+1.17404671e-06j 3.27106651e-05+7.79482012e-06j\n 3.64016950e-05+1.64240791e-05j 3.63310870e-05+2.77218824e-05j] \n Bicubic Spline: [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]\n\n\nWe see if we take a quick examination of our results (a small subset) we see the problem with the global fit. It cannot handle modes with a very small amplitude. Therefore, you might naively think that this method might not work.\n\n#### Compare via the cosine between the vectors\n\n\n```python\ncos = (np.dot(amps_check_2.conj()[0].T, amps_check_1[0]) /\n np.sqrt(np.dot(amps_check_2.conj()[0], amps_check_2[0]) \n * np.dot(amps_check_1.conj()[0], amps_check_1[0]))).real\n\nprint('Cos:', cos)\n```\n\n Cos: 0.9999733790390088\n\n\nWe now see that if we compare the results as a whole, the results match very well. If we look at individual modes that have high power, they are likely to strongly match when the bicubic spline is compared to the RomanNet method. \n\n## GPU-accelerated Waveform Build: $\\sum_{lmn}$\n\n### Quick primer on GPUs\n\n\n\n\n\nGPUs run code in parallel in a configuration of grids, blocks, and threads.\n\n* **Threads** are the the actual software units that run the code. Threads run independently of one another. Threads are referenced in code using `threadIdx.x`.\n* **Blocks** are an array of threads. This array can be 1, 2, or 3 dimensions. In more than one dimension, thread indices are referenced using `x`, `y`, and `z` (e.g. `threadIdx.z`). Blocks, similar to threads, are referenced using `blockIdx.x`, `blockIdx.y`, or `blockIdx.z`. The size of a block, i.e. the number of threads along a given dimension is given as `blockDim.x`. **Note**: In applications I have worked on, I rarely ever use more than 1 dimension of threads. \n* **Grids** are an array of blocks. This array can be 1, 2, or 3 dimensions. There is no reference for grids as they efffectively represent the entire GPU kernel. The size of a grid, i.e. the number of blocks along a dimension, is determined with `gridDim.x`. \n\nOrganizing your code properly into blocks and threads is a key component of maximizing your efficiency. \n\nAnother equally important aspect to the maximization of efficiency is the proper use of the GPU memory structures. There are three main GPU memory structures to consider (there are a few more but they are for more specific uses). These are global memory, shared memory, and local memory.\n\n* **Global memory** is contained on the host (or off-chip). Global memory is accessible by every block and thread in the entire grid. It contains many GBs of RAM. (The GPUs I use currently, which are Tesla V100s, have ~16GB. The new A100s have 40-80GB.) Because this memory is contained off-chip, it is slow to access. A key to accessing global memory efficiently is to use so-called \"memory coalescence.\" This effectively means that neighboring threads access neighboring addresses in memory. This allows the compiler to make up to 32 memory reads at the same time, rather than 32 separate memory reads. We will see this in a simple case below. \n\n* **Local memory** is also contained on the host. Local memory consists of any arrays allocated within the kernel specific to each thread. Therefore, this memory is only accessible by the thread it is created on. Usually, around 512 KB are available for local memory for each thread. Since, this memory is off-chip, it is also slow to access. Local memory is, however, always accessed in a memory coalescing manner. \n\n* **Shared memory** is different. Shared memory is located on-chip. It is, therefore, much faster to read from (~100x faster). Shared memory is accessible by all the threads on a given block. The catch is that only ~48 KB are available for shared memory. Therefore, leveraging shared memory effectively is key to the efficiency of GPU code. \n\nTo sum up, there are two main points to consider when beginning to program on GPUs:\n\n* Layout your grid effectively for your given problem.\n* Use memory effectively: leverage the availability of shared memory and read from global memory in a coalescing fashion. \n\nSome parting thoughts on GPUs:\n\n* For maximal efficiency and stability, I usually code in C++/CUDA so that everything is precompiled and tested. \n* There are python libraries that leverage the power of GPUs. Check out numba, CuPy, PyTorch, Tensorflow, PyCUDA. \n* Lately, I have really focused on writing CPU/GPU agnostic code. This means that the source code is ~99% the same between the two. On the python side I usually sub in CuPy for Numpy. We will see some basic pointers on this below. In C++, I use short compiler directives to make minimal changes.\n* Generally speaking it is optimal to store all quantities in a 1 dimensional array when working with GPUs. Let's say you have a two dimensional array that has dimensions (dim1, dim2) and is referenced with (i, j). You can turn this into a 1D array that references each value with (i * dim2 + j). \n\n### Why are GPUs important for EMRI Waveforms?\n\nThe waveform summation is the key bottleneck. This is an operation that is uniquely suited to GPUs. You can see the improvement below.\n\n\n\n### Basic example coded in python\n\nWe are going to write code in python that will reflect what we will do on the GPU. It will obviously still be on the CPU, but will give you a chance to see how to write some basic GPU code and understand how it works. **Make sure to read the comments in the code.**\n\nWe will do two examples. \n\n#### Multiply two arrays\n\nHere we will multiply two arrays as we would on the GPU. \n\n\n```python\n# setup our GPU quantities that would come in if we were actually on GPUs. \n\nNUM_THREADS = 64 # needs to be a multiple of 32\nblockDim = NUM_THREADS # blockDim.x\n```\n\n\n```python\n\n# this initial piece is a basic of CPU/GPU agnostic code in python\ntry:\n import cupy as xp\n \nexcept ModuleNotFoundError:\n import numpy as xp\n\n# __global__\ndef multiply_arrays(array_out, array1, array2, n):\n \"\"\"\n // what this would like like in CUDA\n \n // if (threadIdx.x + blockDim.x * blockIdx.x >= n) return;\n for (int i = threadIdx.x + blockDim.x * blockIdx.x; i < n; i += blockDim.x * gridDim.x)\n {\n array_out[i] = array1[i] * array2[i];\n }\n \"\"\"\n # The loops here are to simulate the GPU. \n # In reality the GPU will run all threads and blocks in parallel\n \n # begin simulation\n for block in range(num_blocks):\n for thread in range(NUM_THREADS):\n # end simulation\n \n # get the overall index in the grid\n # based on the thread and block\n i = thread + block * blockDim\n \n # since the GPU runs threads in parallel\n # we need to make sure the GPU does not index a value\n # on the last block that goes over the array length\n if i >= n:\n continue\n \n # use our index to get values out of the array\n # notice this simple statement uses memory coalescence\n # neighboring threads will have consecutive indices\n # therefore, they will access consecutive addresses in each array\n array_out[i] = array1[i] * array2[i]\n \n\nlength = int(2 ** 14)\n\n# initialize arrays\narray1 = xp.random.rand(length)\narray2 = xp.random.rand(length)\n \n# prepare output array\narray_out = xp.zeros_like(array1)\n\n# get the number of blocks\n# the number of blocks multiplied by the number of threads per block\n# must be greater than the length of the array \nnum_blocks = int(np.ceil((length + NUM_THREADS -1)/NUM_THREADS))\n\n# this would actually be called as\n\"\"\"\nmultiply_arrays<<>>(array_out, array1, array2, length);\ncudaDeviceSynchronize();\n\"\"\"\n\nmultiply_arrays(array_out, array1, array2, length)\n\n# confirm it\nassert np.allclose(array_out, array1 * array2)\n```\n\n#### Linear Interpolation to scale up an array \n\nFor our second example it will be a bit more complicated. This way we can see how to use shared memory. \n\nHere we will scale up the size of an array using linear interpolation. The key here is that we need every block to read in the original array to shared memory. From there, we perform the interpolation. This allows us to achieve memory coalescence with all global reads and ensure that all reads when actually interpolating are done from shared memory. \n\n\n```python\n# in CUDA, when you statically allocate shared arrays,\n# you cannot use a variable length\n# therefore, in C++/CUDA you need to declare a max value up front\n\n#define MAX_INPUT 1000\n\ndef linear_interpolation(array_out, array_in, n_out, n_in, dx_out, dx_in):\n \n # we want to read in to shared memory\n # want to do this with memory coalescence\n # since this is only on a specific block\n # we need to use only the threads on this block\n \n \"\"\"\n // the below simulated code block in CUDA would look like this:\n \n // in CUDA, you have to declare shared arrays\n \n __shared__ double shared_array_in[MAX_INPUT];\n \n \n for (int i = threadIdx.x; i < n_in; i += blockDim.x)\n {\n // memory coalescence only needed from array_in (global memory)\n shared_array_in[i] = array_in[i];\n }\n \n // we need to make sure the threads all finish this operation before we move on\n // Therefore, we force the threads to synchronize\n \n __syncthreads();\n \n \"\"\"\n \n \n # we will just do the following to simulate in python easily\n shared_array_in = xp.zeros(n_in)\n \n for thread in range(NUM_THREADS):\n i = thread \n \n # this while statement simulates the above commented loop\n while (i < n_in):\n # here is the memory coalesced reads\n shared_array_in[i] = array_in[i]\n \n # just for simulation\n i += blockDim\n \n \n \"\"\"\n // this is what the below would really like it in CUDA\n // if (threadIdx.x + blockDim.x * blockIdx.x >= n_out) return;\n for (int i = threadIdx.x + blockDim.x * blockIdx.x; i < n_out; i += blockDim.x * gridDim.x)\n {\n // get the new out value assuming equal spacing\n double x_new = dx_out * i;\n \n // get index of the point in the original array below the new point\n int ind_in = (int) (x_new / dx_in);\n \n // get the below x value\n double x_old = ind_in * dx_in;\n\n // slope of segment\n double m = (shared_array_in[ind_in + 1] - shared_array_in[ind_in])/dx_in;\n\n // interpolate\n double new_value = m * (x_new - x_old) + shared_array_in[ind_in];\n array_out[i] = new_value;\n }\n \n \"\"\"\n # The loops here are to simulate the GPU. \n # In reality the GPU will run all threads and blocks in parallel\n \n # begin simulation\n for block in range(num_blocks):\n for thread in range(NUM_THREADS):\n # end simulation\n \n # get the overall index in the grid\n # based on the thread and block\n i = thread + block * blockDim\n \n # since the GPU runs threads in parallel\n # we need to make sure the GPU does not index a value\n # on the last block that goes over the array length\n if i >= n_out:\n continue\n \n x_new = dx_out * i\n \n ind_in = int(x_new / dx_in)\n x_old = ind_in * dx_in\n \n m = (shared_array_in[ind_in + 1] - shared_array_in[ind_in])/dx_in\n \n new_value = m * (x_new - x_old) + shared_array_in[ind_in]\n array_out[i] = new_value\n \n\n# original length\nlength_in = 100\n\n# prepare input arrays\nx_in = xp.arange(length_in)\ny_in = (x_in ** 2).astype(xp.float64)\n\n# set length out\nlength_out = int(2 ** 14)\n\n# setup the new x_values\nx_new = xp.linspace(x_in[0], x_in[-1], length_out + 1)[:-1]\n\n# change in original x values\ndx_in = 1.0\n\n# we will actually only use the spacing to find new points\ndx_out = x_new[1] - x_new[0]\n \ny_out = xp.zeros(length_out)\n\nnum_blocks = int(np.ceil((length_out + NUM_THREADS -1)/NUM_THREADS))\n\n# this would actually be called as\n# linear_interpolation<<>>(y_out, y_in, length_out, length_in, dx_out, dx_in);\n# cudaDeviceSynchronize();\nlinear_interpolation(y_out, y_in, length_out, length_in, dx_out, dx_in)\n\n# confirm it\nplt.plot(x_new, y_out, lw=6, label='out')\nplt.plot(x_in, y_in, '.', label='in')\n```\n\n### Comment on CPU/GPU Agnostic code in C++/CUDA and Python\n\nMaking CPU/GPU agnostic code consists of 3 main parts: \n\n* Sub CuPy for NumPy\n* Compiler directives in C++/CUDA\n* Easy transition from Python to C++ through an augmented Cython process\n\nAbove, we saw an example of how to deal with the Python side. The Cython functionality is effectively a decorator function that gets the pointer of a Numpy or Cupy array and sends that into the C++ code. Below is a basic example of how to use basic compiler directives to make your code more CPU/GPU agnostic.\n\n**Note**: I generally argue that we should build codes for GPUs and then adapt them to CPUs, not the other way around which is the typical direction. In my experience, the CPU codes adapted from GPU codes are just as fast or within a small percentage of the speed of CPU designed codes. And, generally, it is much harder to optimize going from CPU->GPU rather than GPU->CPU. \n\n\n\n## Future Plans\n\n* Build fast trajectories in Kerr under the NIT framework\n* Generate amplitudes in Kerr regime\n* Further analyze how to determine best methods for mode content inclusion\n\nWe need your help! If anyone is interested in working on these types of issues, please let myself or any of my collaborators (listed above) know!\n", "meta": {"hexsha": "ee1674ad5ddd8e120ff643cafbc27c7e6ffe836b", "size": 161208, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICERM_tutorial_GPUs_ML/ICERM_tutorial.ipynb", "max_stars_repo_name": "basuparth/ICERM_Workshop", "max_stars_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICERM_tutorial_GPUs_ML/ICERM_tutorial.ipynb", "max_issues_repo_name": "basuparth/ICERM_Workshop", "max_issues_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICERM_tutorial_GPUs_ML/ICERM_tutorial.ipynb", "max_forks_repo_name": "basuparth/ICERM_Workshop", "max_forks_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 159.4540059347, "max_line_length": 53780, "alphanum_fraction": 0.8737345541, "converted": true, "num_tokens": 7207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.31275853949656174}} {"text": "# Interpolating chemical equilibrium abundances\n\nThe atmospheric composition is determined by its elemental composition and the chemcical reactions that link these elements and chemical reactant species. In the atmosphere of an exoplanet, which is inherently 3-d and dynamic, mixing and advection processes complicate this picture, because the chemical abundances inferred from spectra are not necessarily representative of the pressures and temperatures probed locally by the observation. In addition, also the radiation field of the host star may influence the abundance and opacity structure of the atmosphere, by dissociating or ionizing chemical species or forming photochemical hazes. In this picture, using chemical equilibrium abundances, which means the steady state chemical composition of the atmosphere when treating its layers as isolated and independent (no advection/mixing/photochemistry), appears unwise.\n\nYet, calculating chemical equilibrium abundances may still serve as a useful starting point for initializing abundances in planetary atmospheres. In certain conditions, for example for planets hot enough such that mixing is negligible, chemical equilibrium abundances can even be sufficient to accurately describe the abundances in the atmospheric region probed by observations.\n\nHere we show how to use our ``poor_mans_nonequ_chem()`` function. This function interpolates the abundances of the most important species from a big chemical equilibrium table as a function of pressure, temperature, metallicity [Fe/H] (where [Fe/H]=0 is solar) and cabon-to-oxygen number ratio (C/O). A C/O $\\sim 0.55$ is the solar value, see, for example, [Asplund et al. (2009)](https://ui.adsabs.harvard.edu/abs/2009ARA%26A..47..481A/abstract).\n\n
\n\n**poor_mans_nonequ_chem() also contains a simple quenching implementation**. This means that a quench pressure can be specified above which the abundances of H$_2$O, CH$_4$ and CO are taken to be constant, following the reasoning in, for example, [Zahnle & Marley (2014)](https://ui.adsabs.harvard.edu/abs/2014ApJ...797...41Z/abstract).\n\n
\n\nThe chemical grid has been calculated with easyCHEM, which is our self-written Gibbs free energy minimizer that is described in [Mollière et al. 2017](https://ui.adsabs.harvard.edu/abs/2017A%26A...600A..10M/abstract), and essentially a CEA clone, see [Gordon & McBride (1994)](https://ntrs.nasa.gov/citations/19950013764). easyCHEM has been benchmarked as the chemical equilibrium tool of petitCODE in [Baudino et al. (2017)](https://ui.adsabs.harvard.edu/abs/2017ApJ...850..150B/abstract). The grid dimensions are $T \\in [60, 4000]~{\\rm K}$, with 100 equidistant temperature points, $P \\in [10^{-8}, 1000]~{\\rm bar}$, with 100 pressure points spaced equidistantly in log space, ${\\rm C/O} \\in [0.1, 1.6]$, with 20 equidistant points, and ${\\rm [Fe/H]} \\in [-2,3]$, with 40 equidistant points. C/O is varied by varing the oxygen abundance, once the total elemental composition has been set by [Fe/H]. The total list of reactant species included was H, H$_2$, He, O, C, N, Mg, Si, Fe, S, AL, Ca, Na, Ni, P, K, Ti, CO, OH, SH, N$_2$, O$_2$, SiO, TiO, SiS, H$_2$O, C$_2$, CH, CN, CS, SiC, NH, SiH, NO, SN, SiN, SO, S$_2$, C$_2$H, HCN, C$_2$H$_2$,acetylene, CH$_4$, ALH, ALOH, AL$_2$O, CaOH, MgH, Mg, OH, PH$_3$, CO$_2$, TiO$_2$, Si$_2$C, SiO$_2$, FeO, NH$_2$, NH$_3$, CH$_2$, CH$_3$, H$_2$S, VO, VO$_2$, NaCL, KCL, e-, H+, H-, Na+, K+, PH$_2$, P$_2$, PS, PO, P$_4$O$_6$, PH, V, FeH, VO(c), VO(L), MgSiO$_3$(c), SiC(c), Fe(c), Na$_2$S(c), KCL(c), Fe(L), SiC(L), MgSiO$_3$(L), H$_2$O(L), H$_2$O(c), TiO(c), TiO(L), TiO$_2$(c), TiO$_2$(L), H$_3$PO$_4$(c), H$_3$PO$_4$(L), where (c) stands for solid and (L) for liquid species. To conserve space only the mass fractions of the following species are tabulated for use in ``poor_mans_nonequ_chem()``: H$_2$, He, CO, H$_2$O, HCN, C$_2$H$_2$,acetylene, CH$_4$, PH$_3$, CO$_2$, NH$_3$, H$_2$S, VO, TiO, Na, K, SiO, e-, H-, H, FeH, MMW, nabla_ad. MMW denotes the mean molcular weight in the atmosphere, in units of amu. nabla_ad is the moist adiabatic lapse rate $\\nabla_{\\rm ad} = (\\partial {\\rm ln}T/\\partial {\\rm ln}P)_{\\rm ad}$, determined as described in [Mollière et al. (2020)](https://arxiv.org/abs/2006.09394).\n\n
\n\n**Abundances in poor_mans_nonequ_chem():** abundances in poor_mans_nonequ_chem() are in units of **mass fractions**, not number fractions (aka volume mixing ratio, VMR). You can convert between mass fractions and VMRs by using\n\\begin{equation}\nX_i = \\frac{\\mu_i}{\\mu}n_i,\n\\end{equation}\nwhere $X_i$ is the mass fraction of species $i$, $\\mu_i$ the mass of a single molecule/atom/ion/... of species $i$, $\\mu$ is the atmospheric mean molecular weight, and $n_i$ is the VMR of species $i$.\n
\n\n## Example\n\nHere we will give some examples for how to interpolate chemical abundances using ``poor_mans_nonequ_chem()``. The installation of it is described immediately below.\n\nWe begin by loading the relevant packages:\n\n\n```python\nimport numpy as np\nimport pylab as plt\nplt.rcParams['figure.figsize'] = (10, 6)\nfrom poor_mans_nonequ_chem import poor_mans_nonequ_chem as pm\nfrom petitRADTRANS import nat_cst as nc\n```\n\nNext, we define an atmospheric temperature and abundance structure, following an example similar to what is shown in [\"Getting Started\"](getting_started.html).\n\n\n```python\npressures = np.logspace(-6, 2, 100)\ngravity = 1e1**2.45\nkappa_IR = 0.01\ngamma = 0.4\nT_int = 200.\nT_equ = 800.\n\ntemperature = nc.guillot_global(pressures, kappa_IR, gamma, gravity, T_int, T_equ)\n\nplt.plot(temperature, pressures)\nplt.yscale('log')\nplt.ylim([1e2, 1e-6])\nplt.xlabel('T (K)')\nplt.ylabel('P (bar)')\nplt.show()\nplt.clf()\n```\n\nNo we calculate the abundances. Note that the input parameters temperature, pressure, [Fe/H] and C/O are all arrays, and must be defined at every layer, but usually C/O and [Fe/H] are not vertically varying in the atmosphere. Here we chose a solar metallicity and C/O.\n\n\n```python\nCOs = 0.55 * np.ones_like(pressures)\nFeHs = 0. * np.ones_like(pressures)\n \nmass_fractions = pm.interpol_abundances(COs, \\\n FeHs, \\\n temperature, \\\n pressures)\n```\n\nLets plot the abundances:\n\n\n```python\nplt.yscale('log')\nplt.xscale('log')\nplt.ylim([100,1e-6])\nplt.xlim([1e-10, 1])\n\nfor species in mass_fractions.keys():\n if species not in ['MMW', 'nabla_ad']:\n plt.plot(mass_fractions[species], pressures, label = species)\n \nplt.legend(loc='best', ncol=3)\nplt.xlabel('Mass fraction')\nplt.ylabel('P (bar)')\nplt.show()\nplt.clf()\n```\n\nAlso the MMW and adiabatic temperature gradient are accessible, which turns out to be vertically constant for this atmosphere:\n\n\n```python\nplt.yscale('log')\nplt.ylim([100,1e-6])\n\nplt.plot(mass_fractions['MMW'], pressures, label = species)\n \nplt.xlabel('Mean molecular weight (MMW)')\nplt.ylabel('P (bar)')\nplt.show()\nplt.clf()\n```\n\n\n```python\nplt.yscale('log')\nplt.ylim([100,1e-6])\n\nplt.plot(mass_fractions['nabla_ad'], pressures, label = species)\n \nplt.xlabel(r'Moist adiabatic temperature gradient $\\nabla_{\\rm ad}$')\nplt.ylabel('P (bar)')\nplt.show()\nplt.clf()\n```\n\nAs a test, we can also plot abundances at a given pressure, temperature, C/O, as a function of metallicity:\n\n\n```python\nFeHs = np.linspace(-2, 3, 100)\np_const = np.ones_like(FeHs)*1e-1\nt_const = np.ones_like(FeHs)*900.\nCOs = 0.55 * np.ones_like(FeHs)\n \nmass_fractions = pm.interpol_abundances(COs, \\\n FeHs, \\\n t_const, \\\n p_const)\n```\n\n\n```python\nplt.yscale('log')\nplt.ylim([1e-10, 1])\nplt.xlim([-2, 3])\n\nfor species in mass_fractions.keys():\n if species not in ['MMW', 'nabla_ad']:\n plt.plot(FeHs, mass_fractions[species], label = species)\n \nplt.legend(loc='best', ncol=3)\nplt.ylabel('Mass fraction')\nplt.xlabel('[Fe/H]')\nplt.title('T = 900 K, P = 0.1 bar, C/O = 0.55')\nplt.show()\nplt.clf()\n```\n\nThis is the mean molecular weight as a function of metallicity:\n\n\n```python\nplt.xlim([-2, 3])\nplt.ylim([0, 15])\n\nplt.plot(FeHs, mass_fractions['MMW'])\n\nplt.ylabel('Mean molecular weight')\nplt.xlabel('[Fe/H]')\nplt.title('T = 900 K, P = 0.1 bar, C/O = 0.55')\nplt.show()\nplt.clf()\n```\n\nHere the mass fractions as a function of the C/O ratio, at solar metallicity:\n\n\n```python\nCOs = np.linspace(0.1, 1.6, 100)\nFeHs = 0. * np.ones_like(COs)\np_const = np.ones_like(COs)*1e-1\nt_const = np.ones_like(COs)*1400.\n \nmass_fractions = pm.interpol_abundances(COs, \\\n FeHs, \\\n t_const, \\\n p_const)\n```\n\n\n```python\nplt.yscale('log')\nplt.ylim([1e-10, 1])\nplt.xlim([0.1, 1.6])\n\nfor species in mass_fractions.keys():\n if species not in ['MMW', 'nabla_ad']:\n plt.plot(COs, mass_fractions[species], label = species)\n \nplt.legend(loc='lower right', ncol=3)\nplt.ylabel('Mass fraction')\nplt.xlabel('C/O')\nplt.title('T = 1400 K, P = 0.1 bar, [Fe/H] = 0')\nplt.show()\nplt.clf()\n```\n\nFinally, we show an example with quenching here, assuming that the CH$_4$, H$_2$O and CO abundances are constant in for pressures below 1 bar. We will use the temperature structure from above again.\n\n\n```python\n# Nominal case:\nCOs = 0.55 * np.ones_like(pressures)\nFeHs = 0. * np.ones_like(pressures)\n \nmass_fractions = pm.interpol_abundances(COs, \\\n FeHs, \\\n temperature, \\\n pressures)\n\n# Quenching case:\nmass_fractions_quench = pm.interpol_abundances(COs, \\\n FeHs, \\\n temperature, \\\n pressures, \\\n Pquench_carbon = 1.)\n```\n\n\n```python\nplt.yscale('log')\nplt.xscale('log')\nplt.ylim([100,1e-6])\nplt.xlim([1e-10, 1])\n\nplt.plot(mass_fractions['H2'], pressures, linestyle = '--', color = 'black')\nplt.plot(mass_fractions_quench['H2'], pressures, label = 'H2', linestyle = '-', color = 'black')\nplt.plot(mass_fractions['He'], pressures, linestyle = '--', color = 'gray')\nplt.plot(mass_fractions_quench['He'], pressures, label = 'He', linestyle = '-', color = 'gray')\nplt.plot(mass_fractions['CO'], pressures, linestyle = '--', color = 'red')\nplt.plot(mass_fractions_quench['CO'], pressures, label = 'CO', linestyle = '-', color = 'red')\nplt.plot(mass_fractions['H2O'], pressures, linestyle = '--', color = 'purple')\nplt.plot(mass_fractions_quench['H2O'], pressures, label = 'H2O', linestyle = '-', color = 'purple')\nplt.plot(mass_fractions['CH4'], pressures, linestyle = '--', color = 'orange')\nplt.plot(mass_fractions_quench['CH4'], pressures, label = 'CH4', linestyle = '-', color = 'orange')\n\nplt.axhline(1., color = 'blue', linestyle = ':', label = 'Quench pressure')\n\nplt.legend(loc='best', ncol=1)\nplt.xlabel('Mass fraction')\nplt.ylabel('P (bar)')\nplt.title(\"Poor man's non-equilibrium chemistry: quenching\")\nplt.show()\nplt.clf()\n```\n\n## Installation of poor_mans_nonequ_chem()\n\nDownload the ``poor_mans_nonequ_chem()`` [here](https://www.dropbox.com/s/6r3djmzu8y1qplf/poor_mans_nonequ_chem.zip?dl=0). If relevant, activate the python environment that you want to run your code in (similar to the [installation tips when installing pRT](../installation.html)). Then, in the terminal, switch into the poor_mans_nonequ_chem/chem_fortran_util folder and type ``./make.sh``, again similar to the [pRT installation](../installation.html). Lastly, [like when installing pRT](../installation.html), enter the following line to your .bashrch or .bashprofile (depending on your operating system):\n\n``export PYTHONPATH=Path of the folder containing the highest level poor_mans_nonequ_chem folder/:$PYTHONPATH``\n\nAfter this close and reopen the terminal such that it will set the Python path correctly, or source the .bashrc/.bashprofile file. Alternatively, you can place the following line at the top of your scripts that use ``poor_mans_nonequ_chem``, berfore importing ``poor_mans_nonequ_chem``: \n\n\n```python\nimport sys\nsys.path.insert(0,'Path to folder containing the highest level poor_mans_nonequ_chem folder/')\n```\n\nYou are done!\n", "meta": {"hexsha": "65b878cb605e96be6486b15dca3728e7c7b3298c", "size": 375433, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/content/notebooks/poor_man.ipynb", "max_stars_repo_name": "nborsato/petitRADTRANS", "max_stars_repo_head_hexsha": "2df983bc46b892486b1b035d7c6933ab46f0d36c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "docs/content/notebooks/poor_man.ipynb", "max_issues_repo_name": "nborsato/petitRADTRANS", "max_issues_repo_head_hexsha": "2df983bc46b892486b1b035d7c6933ab46f0d36c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/content/notebooks/poor_man.ipynb", "max_forks_repo_name": "nborsato/petitRADTRANS", "max_forks_repo_head_hexsha": "2df983bc46b892486b1b035d7c6933ab46f0d36c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 583.8771384137, "max_line_length": 85440, "alphanum_fraction": 0.9453777372, "converted": true, "num_tokens": 3552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.3127270985321193}} {"text": "```python\n# %load /Users/facai/Study/book_notes/preconfig.py\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(color_codes=True)\nsns.set(font='SimHei')\nplt.rcParams['axes.grid'] = False\n\nfrom IPython.display import SVG\n\ndef show_image(filename, figsize=None):\n if figsize:\n plt.figure(figsize=figsize)\n\n plt.imshow(plt.imread(filename))\n```\n\nGBDT(Gradient Boosting Decision Tree) 原理简介\n=============================================\n\n### 0. 前言\n\n我最开始了解 GBDT 时,死活不理解决策树这种分段函数,怎么可能算出一阶导数。读了论文 Friedman - Greedy Function Approximation: A Gradient Boosting Machine 后,才发现自己完全误解了决策树在GBDT中的作用。论文总是倾向把简单事情描述复杂,博客又常常过于简练地只给具体算法。写这篇文章的想法,就是想用自己的理解,既照顾到数学框架,又落实到具体算法实现,把GBDT说清楚。这里可能有谬误,读者应审慎地阅读。\n\n### 1. Gradient Boosting 与最优化\nref:\n\n+ [机器学习中的算法(1)-决策树模型组合之随机森林与GBDT](http://www.cnblogs.com/LeftNotEasy/archive/2011/03/07/random-forest-and-gbdt.html)\n\n在说GBDT前,我们先说下它的俩前缀Gradient Boosting:\n\n+ Boosting: 这是一种迭代算法,每一次训练都是在前面已有模型的预测基础上进行。 \n 最简单地说,先训练一个初始模型,对比真实值和预测值的残差;用残差再训练一个模型,再计算残差;再训练……。这样,每一个模型都专注于修正前面模型最不给力的效果方面。于是,通过这种方式联合多个弱分类器,就能得到一个强分类器。\n+ Gradient: 梯度。对于单个变量来说,就是一阶导数。 \n 前面Boosting要计算残差,方法就很多了,你可以直接相减,也可以定义个函数。这里Gradient就是说用梯度来计算残差。\n \n所以说Gradient Boosting是一种算法框架,它是用Grdient计算残差的Boosting过程,而GBDT只是用决策树来训练的一种具体实现。说到这,学习过最优化的童鞋一定会对Gradient Boosting有种强烈的既视感,是的,那就是我们耳熟能详的最速梯度下降法。\n\n所以,我们先从最速梯度下降法作引,一步步走到Gradeint Boosting框架,然后再落到决策树上,最后如果有精力,介绍下进一步的优化TreeBoost。\n\n### 2. 最速梯度下降法\n\n我简要说下基本思路,详细可见[梯度下降法 - 维基百科](https://zh.wikipedia.org/wiki/梯度下降法)。\n\n假设有个有界函数 $| f(x) | < M$,我们需要知道它的最小值。日常的例子中,这个函数可能是一项工程所用的花销,一个项目占用的时间,我们想找到损失最小的方案,即:$\\operatorname{arg min}_x \\, f(x) $。 找到最小解的过程就叫寻优,函数$f(x)$常被称为损失函数。\n\n#### 2.0 理论 \n\n梯度下降法是一种数值寻优算法。什么是数值寻优呢?就是现实中$f(x)$很多时候难以用理论求解出最值,或者$f(x)$就是个黑盒子,我们没有办法直接找到最值,只能去有限的数值解中搜索,所以叫数值寻优。\n\n梯度下降法就是按函数梯度来步进到极值点的过程,其数学表达式形如:\n\\begin{equation}\n x_{m+1} = x_m - \\lambda \\frac{\\partial f(x)}{\\partial x}\n\\end{equation}\n\n具体过程如下图所示,取自[可扩展机器学习——梯度下降(Gradient Descent)](http://blog.csdn.net/google19890102/article/details/50276775):\n\n\n```python\nshow_image(\"./res/gradient_descent.jpg\", figsize=(12,8))\n```\n\n\n```python\nshow_image(\"./res/iterator.jpg\")\n```\n\n#### 2.1 增量寻优\n\n梯度下降法是利用了导数做为步进参考值,它要求函数是已知且可导的。问题是,现实中,有时这个函数是未知的,比如说对应的是一台机器。我不知道怎么对它建模,唯一的信息就是喂它输入,它就会返回输出。那怎么办呢?\n\n首先,我们回到 $\\frac{\\partial f(x)}{\\partial x}$ 来看,因为步进大小还受 $\\lambda$ 调控。这里梯度的作用,其实主要是指示步进方向。\n\n然后,我们换个思路找步进方向。\n\n假设机器的真实模型是 $f(x)$,对我们来说它是未知的。尝试如下:\n\n+ 第一次试探,随机给个初始值 $x_0$,得到 $f(x_0)$。\n+ 第二次试探,再随机输入 $x_1$,得到 $f(x_1)$。\n\n这时,有如下三种情况,可以指导第三次试探:\n\n1. $f(x_1) < f(x_0)$,也就是 $x_0 \\to x_1$的方向是对的。\n2. $f(x_1) = f(x_0)$,没有有用信息。\n3. $f(x_1) > f(x_0)$,方向反了。\n\n\n```python\nshow_image(\"./res/incr_opt.png\", figsize=(10,5))\n```\n\n因为我们始终是找极小值点,这个过程就始终如上图所示\"U\"形。那么每次的步进方向就可用 $f(x_1) - f(x_0)$ 来指示。也就是说,虽然我们无法对机器$f(x)$建模,但我们可以对寻优的过程 $z = f(x_i) - f(x_{i+1})$ 建模 $g(z)$。而 $g(z)$ 只要满足单调且过零点,理论上它可以是任意的,不同函数影响的只是收敛速度,但都会收敛到 $w^*$ 附近。\n\n#### 2.2 逼近\n\n再换个角度,我们不再想寻优。而是假设这个极小值$w^*$已经知道了,如何从初始值$w_0 = f(x_0)$一步步逼进到这个极小值$w^*$。其实可以完全借用上节的增量寻优建模手法,我们定义 $z = f(x_i) - w^*$,从而对逼近过程建模 $g(z)$。\n\n\n```python\nshow_image(\"./res/approx.png\", figsize=(10,5))\n```\n\n同样地,$g(z)$只要满足一定条件的函数。在这里,就是过零点,正数区间单增,负数区间单减,最常见的代表就是二次函数 $g(z) = z^2$。\n\n我们梳理下整个逼近过程,如下图:\n\n\n```python\nshow_image(\"./res/model.png\", figsize=(10,5))\n```\n\n从初始点$w_0$,沿着$w_1, w_2, \\dotsc, w_i$到达$w^*$。其中每步的步长是$\\lambda \\frac{\\partial g(z)}{\\partial z} |_{z = z_i}$。$\\lambda$是控制步长的字习率,不用管。我们重点看下$z_i$:\n\n\\begin{align}\n z_i &= w_i - w^* \\\\\n &= f(x_i) - w^*\n\\end{align}\n\n上面,每一步对应的$f(x_i)$是一个恒定的模型,变动的是$x$。我们反着想,假设$x$是固定的,而这个模型其实是变化的 $f_i(x)$,再把$w^*$用$y$表示。那么 \n\n\\begin{align}\n z_i &= f(x_i) - w^* \\\\\n &= f_i(x) - y\n\\end{align}\n\n是不是开始有点眼熟了,如果我们再令 $g(z) = z^2$,展开看看:\n\n\\begin{align}\n g(z_i) &= z_i^2 \\\\\n &= (y - f_i(x))^2\n\\end{align}\n\n好了,我们总结下上述函数的意义: \n给定自变量$x$、目标值$y$和初始位置$w_0$,可以用规定的$g(z)$和模型$f_i(x)$来构建出一个迭代序列$\\{w_0, w_1, \\dotsc, y\\}$,其中$w_{i+1} = w_i - \\lambda \\frac{\\partial g(z)}{\\partial z} \\, |_{z = y - f_i(x)}$。\n\n而: \n+ 对给定$x$,$y$是常数,所以$\\partial z = \\partial f_i(x)$。\n+ $g(z) | z = y - f_i(x)$表述的是$y$和$f_i(x)$的距离相近度,可以更泛性推广记为$L(y, f_i(x))$。\n\n所以记$w_{i+1} = w_i - \\lambda \\frac{\\partial L(y, f_i(x))}{\\partial f_i(x)}$\n\n用机器学习的术语翻译就是,如果有特征$x$、目标值$y$和初始模型$f_0$,对某个损失函数$L(y, f_i(x))$,就有模型序列使得$f_i(x) \\to y$。\n\n而Gradient Boosting就是回答了上述的两个规定:\n\n1. 怎样构建模型序列$f_i$?\n2. 什么样的损失函数$L(y, f_i(x))$?\n\n### 3. Gradient Boosting\n\n#### 3.1 怎样构建模型序列$f_i$\nGradient Boosting的答案就是使用Boosting来训练Gradient(梯度)值的加法模型。\n\n具体来说,已知有特征$x$、标签$y$和初始模型$f_0$。 \n然后,我们选定一种机器学习算法$\\text{Model}(\\text{feature}, \\text{value})$,输入数据后就会给出模型$F(x)$。\n\n我们规定模型生成序列方法如下:\n\n\\begin{align}\n & F_0 = f_0 \\\\\n & \\hat{y_i} = - \\frac{\\partial L(y, f_{i-1}(x)}{\\partial f_{i-1}(x)} \\\\\n & F_i = \\text{Model}(x, \\hat{y_i}) \\\\\n & f_{i} = f_{i-1} + F_i = \\displaystyle \\sum_{k=0}^{i} F_k \\\\\n\\end{align}\n\n上式第二行就是Gradient(梯度),第三行就是用梯度训练的单个模型$F_i$,而第四行$f_i$就是Boosting加法。请注意区分$f_i$和$F_i$。\n\n很多时候,我们期望初始模型自动产生,并且和其它模型是同种类型的,上面的生成序列方法就可改写为:\n\n\\begin{align}\n & F_0 = \\text{Model}(x, y) \\\\\n & \\hat{y_i} = - \\frac{\\partial L(y, f_{i-1}(x)}{\\partial f_{i-1}(x)} \\\\\n & F_i = \\text{Model}(x, \\hat{y_i}) \\\\\n & f_{i} = f_{i-1} + F_i = \\displaystyle \\sum_{k=0}^{i} F_k \\\\\n\\end{align}\n\n总结下流程:\n\n1. 用$x$和$y$训练初始模型$F_0$,并令累加模型$f_0 = F_0$。\n2. 用梯度计算出残差 $\\hat{y_i}$。\n3. 用$x$和残差训练新模型$F_i$。\n4. 将新模型加入累加模型$f_i$。\n5. 迭代直到达到终止条件。\n\n#### 3.2 什么样的损失函数 $L(y, f_i(x))$\n\n正如2.2节所说,损失函数$L(y, f_i(x))$定义的是从初始值到目标值的逼近过程。常理来说,离得越远,我们期望步距越大,调整越剧烈;离得越近,期望步距越小,调整越缓合。常用的有L1, L2和logistic。当然,理论上,你也可以用其它千奇百怪的函数,只要它符合$x_1 \\to x_2 \\implies f(x_1) \\to f(x_2)$。\n\n### 4. GBDT(Gradient Boosting Decision Tree)\n\n将第3节中的机器模型Model换成决策树,就得到了GBDT。嗯,就是这么简单。\n\nTreeboost是具体对决策树参与的计算做了公式推导,作用是简化运算量,打算后续开文专门讲。\n\n### 总结\n我们最后总结下,GBDT是Gradient Boosting框架用决策树完成的一个具体实现。Gradeint Boosting框架的本质思路是一个从基准值到目标值的逼近过程,也是一个基准弱模型向强模型的进化过程。逼近过程是用损失函数来描述和控制的,具体的步进量(残差)由损失函数的梯度来指示。机器模型的作用是用来拟合和预测残差。\n\n所以,我以前不理解决策树怎么求导,而事实是决策树压根就和求导没关系。希望这篇文章能帮助到其它人的理解,也请指正错点漏点疑点。\n\n\n```python\n\n```\n", "meta": {"hexsha": "b4998fbb92bca9cf1ed0ba9ba3035a3ecba2a444", "size": 421426, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "machine_learning/tree/gbdt/intro.ipynb", "max_stars_repo_name": "ningchi/book_notes", "max_stars_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2017-12-31T12:10:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-10T15:49:34.000Z", "max_issues_repo_path": "machine_learning/tree/gbdt/intro.ipynb", "max_issues_repo_name": "ningchi/book_notes", "max_issues_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-12-05T13:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-07T16:24:50.000Z", "max_forks_repo_path": "machine_learning/tree/gbdt/intro.ipynb", "max_forks_repo_name": "ningchi/book_notes", "max_forks_repo_head_hexsha": "c6f8001f7d5f873896c4b3a8b1409b21ef33c328", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2017-06-27T07:19:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T08:57:35.000Z", "avg_line_length": 1066.9012658228, "max_line_length": 106570, "alphanum_fraction": 0.9429271094, "converted": true, "num_tokens": 3966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.3110515592368845}} {"text": "```python\nimport pandas as pd\nimport numpy as np\nfrom utils import read_file, tokenize_latex\ndf = read_file(\"data/1601/*\")\n\n```\n\n error with: data/1601/1601.06597.json\n\n\n\n```python\nimport re\ndef clean_exp(exp):\n exp = re.sub(\"\\\\\\\\begin{equation[^}]*}\",\"\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\end{equation[^}]*}\",\"\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\begin{split[^}]*}\",\"\\\\\\\\begin{aligned}\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\end{split[^}]*}\",\"\\\\\\\\end{aligned}\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\begin{gather[^}]*}\",\"\\\\\\\\begin{aligned}\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\end{gather[^}]*}\",\"\\\\\\\\end{aligned}\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\begin{align[^}]*}\",\"\\\\\\\\begin{aligned}\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\end{align[^}]*}\",\"\\\\\\\\end{aligned}\" ,exp, flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\label{[^}]*}\",\"\" ,exp , flags=re.IGNORECASE)\n exp = re.sub(\"\\\\\\\\n\", \"\",exp, flags=re.IGNORECASE)\n exp = re.sub(\"\\\\$\", \"\",exp , flags=re.IGNORECASE)\n return exp\n```\n\n\n```python\ndf[\"processed\"] = df[\"text\"].apply(lambda x: clean_exp(x)).apply(lambda x: tokenize_latex(x))\n```\n\n\n```python\nfrom gensim import corpora\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\nequations = df[\"processed\"].tolist()\ndictionary = corpora.Dictionary(equations)\n\ncorpus = [dictionary.doc2bow(eq) for eq in equations]\ncorpora.MmCorpus.serialize('/tmp/equations.mm', corpus)\n# our vector space model\nprint(corpus[1:5])\n```\n\n 2017-12-02 00:49:54,164 : INFO : adding document #0 to Dictionary(0 unique tokens: [])\n 2017-12-02 00:49:54,691 : INFO : adding document #10000 to Dictionary(15769 unique tokens: [u'\\\\xi\\\\leq', u'4E+6F', u'0.000004', u'-P\\\\cdot\\\\frac', u'i|S']...)\n 2017-12-02 00:49:55,213 : INFO : adding document #20000 to Dictionary(25840 unique tokens: [u'\\\\xi\\\\leq', u'eF', u'q-1', u'q-2', u'+i+1']...)\n 2017-12-02 00:49:55,714 : INFO : adding document #30000 to Dictionary(35023 unique tokens: [u'\\\\xi\\\\leq', u'eF', u'-5AB\\\\sqrt', u'q-1', u'q-2']...)\n 2017-12-02 00:49:56,251 : INFO : adding document #40000 to Dictionary(43511 unique tokens: [u'\\\\xi\\\\leq', u'eF', u'-5AB\\\\sqrt', u'Model~III.~~~~~~~c', u'q-1']...)\n 2017-12-02 00:49:56,807 : INFO : adding document #50000 to Dictionary(53030 unique tokens: [u'\\\\xi\\\\leq', u'eF', u'-5AB\\\\sqrt', u'Model~III.~~~~~~~c', u'q-1']...)\n 2017-12-02 00:49:57,126 : INFO : built Dictionary(57545 unique tokens: [u'\\\\xi\\\\leq', u'eF', u'-5AB\\\\sqrt', u'Model~III.~~~~~~~c', u'q-1']...) from 56379 documents (total 3317666 corpus positions)\n 2017-12-02 00:49:59,982 : INFO : storing corpus in Matrix Market format to /tmp/equations.mm\n 2017-12-02 00:49:59,984 : INFO : saving sparse matrix to /tmp/equations.mm\n 2017-12-02 00:49:59,989 : INFO : PROGRESS: saving document #0\n 2017-12-02 00:50:00,214 : INFO : PROGRESS: saving document #1000\n 2017-12-02 00:50:00,492 : INFO : PROGRESS: saving document #2000\n 2017-12-02 00:50:00,695 : INFO : PROGRESS: saving document #3000\n 2017-12-02 00:50:00,897 : INFO : PROGRESS: saving document #4000\n 2017-12-02 00:50:01,096 : INFO : PROGRESS: saving document #5000\n 2017-12-02 00:50:01,327 : INFO : PROGRESS: saving document #6000\n 2017-12-02 00:50:01,510 : INFO : PROGRESS: saving document #7000\n 2017-12-02 00:50:01,744 : INFO : PROGRESS: saving document #8000\n 2017-12-02 00:50:01,944 : INFO : PROGRESS: saving document #9000\n 2017-12-02 00:50:02,147 : INFO : PROGRESS: saving document #10000\n 2017-12-02 00:50:02,364 : INFO : PROGRESS: saving document #11000\n 2017-12-02 00:50:02,544 : INFO : PROGRESS: saving document #12000\n 2017-12-02 00:50:02,693 : INFO : PROGRESS: saving document #13000\n 2017-12-02 00:50:02,832 : INFO : PROGRESS: saving document #14000\n 2017-12-02 00:50:02,976 : INFO : PROGRESS: saving document #15000\n 2017-12-02 00:50:03,130 : INFO : PROGRESS: saving document #16000\n 2017-12-02 00:50:03,270 : INFO : PROGRESS: saving document #17000\n 2017-12-02 00:50:03,452 : INFO : PROGRESS: saving document #18000\n 2017-12-02 00:50:03,622 : INFO : PROGRESS: saving document #19000\n 2017-12-02 00:50:03,787 : INFO : PROGRESS: saving document #20000\n 2017-12-02 00:50:04,009 : INFO : PROGRESS: saving document #21000\n 2017-12-02 00:50:04,199 : INFO : PROGRESS: saving document #22000\n 2017-12-02 00:50:04,452 : INFO : PROGRESS: saving document #23000\n 2017-12-02 00:50:04,596 : INFO : PROGRESS: saving document #24000\n 2017-12-02 00:50:04,747 : INFO : PROGRESS: saving document #25000\n 2017-12-02 00:50:04,929 : INFO : PROGRESS: saving document #26000\n 2017-12-02 00:50:05,071 : INFO : PROGRESS: saving document #27000\n 2017-12-02 00:50:05,197 : INFO : PROGRESS: saving document #28000\n 2017-12-02 00:50:05,350 : INFO : PROGRESS: saving document #29000\n 2017-12-02 00:50:05,494 : INFO : PROGRESS: saving document #30000\n 2017-12-02 00:50:05,629 : INFO : PROGRESS: saving document #31000\n 2017-12-02 00:50:05,765 : INFO : PROGRESS: saving document #32000\n 2017-12-02 00:50:05,912 : INFO : PROGRESS: saving document #33000\n 2017-12-02 00:50:06,065 : INFO : PROGRESS: saving document #34000\n 2017-12-02 00:50:06,231 : INFO : PROGRESS: saving document #35000\n 2017-12-02 00:50:06,389 : INFO : PROGRESS: saving document #36000\n 2017-12-02 00:50:06,559 : INFO : PROGRESS: saving document #37000\n 2017-12-02 00:50:06,705 : INFO : PROGRESS: saving document #38000\n 2017-12-02 00:50:06,858 : INFO : PROGRESS: saving document #39000\n 2017-12-02 00:50:07,132 : INFO : PROGRESS: saving document #40000\n 2017-12-02 00:50:07,409 : INFO : PROGRESS: saving document #41000\n 2017-12-02 00:50:07,598 : INFO : PROGRESS: saving document #42000\n 2017-12-02 00:50:07,769 : INFO : PROGRESS: saving document #43000\n 2017-12-02 00:50:07,915 : INFO : PROGRESS: saving document #44000\n 2017-12-02 00:50:08,053 : INFO : PROGRESS: saving document #45000\n 2017-12-02 00:50:08,210 : INFO : PROGRESS: saving document #46000\n 2017-12-02 00:50:08,365 : INFO : PROGRESS: saving document #47000\n 2017-12-02 00:50:08,495 : INFO : PROGRESS: saving document #48000\n 2017-12-02 00:50:08,629 : INFO : PROGRESS: saving document #49000\n 2017-12-02 00:50:08,771 : INFO : PROGRESS: saving document #50000\n 2017-12-02 00:50:08,903 : INFO : PROGRESS: saving document #51000\n 2017-12-02 00:50:09,041 : INFO : PROGRESS: saving document #52000\n 2017-12-02 00:50:09,176 : INFO : PROGRESS: saving document #53000\n 2017-12-02 00:50:09,391 : INFO : PROGRESS: saving document #54000\n 2017-12-02 00:50:09,622 : INFO : PROGRESS: saving document #55000\n 2017-12-02 00:50:09,792 : INFO : PROGRESS: saving document #56000\n 2017-12-02 00:50:09,875 : INFO : saved 56379x57545 matrix, density=0.038% (1222940/3244329555)\n 2017-12-02 00:50:09,895 : INFO : saving MmCorpus index to /tmp/equations.mm.index\n\n\n [[(5, 1), (6, 1), (8, 3), (12, 4), (13, 3), (14, 4), (15, 4), (17, 1), (18, 3), (19, 3), (21, 1), (22, 1), (23, 1)], [(0, 1), (3, 1), (5, 1), (6, 1), (8, 5), (9, 1), (10, 4), (12, 3), (13, 2), (14, 5), (15, 5), (17, 2), (18, 3), (19, 5), (20, 1), (22, 2), (24, 1), (25, 1), (26, 1)], [(2, 1), (4, 1), (5, 1), (6, 1), (12, 2), (14, 6), (15, 6), (17, 1), (19, 1), (27, 1), (28, 1), (29, 1), (30, 1), (31, 1), (32, 1), (33, 1), (34, 1), (35, 1), (36, 1), (37, 1), (38, 1), (39, 1)], [(1, 1), (2, 1), (4, 1), (5, 3), (6, 3), (7, 3), (8, 1), (14, 6), (15, 6), (17, 1), (19, 2), (20, 2), (29, 1), (40, 1), (41, 2), (42, 1), (43, 2)]]\n\n\n\n```python\nfrom gensim import corpora, models, similarities, matutils\ntfidf = models.TfidfModel(corpus)\ncorpus_tfidf = tfidf[corpus]\nfrom gensim import similarities\nindex = similarities.Similarity(\"index/\", corpus_tfidf, len(dictionary.keys()), num_best = 100)\n```\n\n 2017-12-02 00:50:09,937 : INFO : collecting document frequencies\n 2017-12-02 00:50:09,950 : INFO : PROGRESS: processing document #0\n 2017-12-02 00:50:10,032 : INFO : PROGRESS: processing document #10000\n 2017-12-02 00:50:10,099 : INFO : PROGRESS: processing document #20000\n 2017-12-02 00:50:10,168 : INFO : PROGRESS: processing document #30000\n 2017-12-02 00:50:10,247 : INFO : PROGRESS: processing document #40000\n 2017-12-02 00:50:10,350 : INFO : PROGRESS: processing document #50000\n 2017-12-02 00:50:10,406 : INFO : calculating IDF weights for 56379 documents and 57544 features (1222940 matrix non-zeros)\n 2017-12-02 00:50:10,461 : INFO : starting similarity index under index/\n 2017-12-02 00:50:17,575 : INFO : PROGRESS: fresh_shard size=10000\n 2017-12-02 00:50:24,426 : INFO : PROGRESS: fresh_shard size=20000\n 2017-12-02 00:50:28,874 : INFO : PROGRESS: fresh_shard size=30000\n 2017-12-02 00:50:30,080 : INFO : creating sparse index\n 2017-12-02 00:50:30,082 : INFO : creating sparse matrix from corpus\n 2017-12-02 00:50:30,091 : INFO : PROGRESS: at document #0/32768\n 2017-12-02 00:50:30,914 : INFO : PROGRESS: at document #10000/32768\n 2017-12-02 00:50:31,633 : INFO : PROGRESS: at document #20000/32768\n 2017-12-02 00:50:32,377 : INFO : PROGRESS: at document #30000/32768\n 2017-12-02 00:50:32,615 : INFO : created <32768x57545 sparse matrix of type ''\n \twith 707547 stored elements in Compressed Sparse Row format>\n 2017-12-02 00:50:32,626 : INFO : creating sparse shard #0\n 2017-12-02 00:50:32,627 : INFO : saving index shard to index/.0\n 2017-12-02 00:50:32,629 : INFO : saving SparseMatrixSimilarity object under index/.0, separately None\n 2017-12-02 00:50:32,661 : INFO : saved index/.0\n 2017-12-02 00:50:32,663 : INFO : loading SparseMatrixSimilarity object from index/.0\n 2017-12-02 00:50:32,747 : INFO : loaded index/.0\n 2017-12-02 00:50:32,865 : INFO : PROGRESS: fresh_shard size=0\n 2017-12-02 00:50:38,388 : INFO : PROGRESS: fresh_shard size=10000\n 2017-12-02 00:50:45,378 : INFO : PROGRESS: fresh_shard size=20000\n\n\n\n```python\ndocs = [\"\".join(eq) for eq in df[\"processed\"].tolist()]\n```\n\n\n```python\ndocs\n```\n\n\n\n\n [u'\\\\Phi_{z}(L)=\\\\sum_{i=1}^{N}\\\\frac{1}{C_{i}\\\\timesV_{\\\\rmmax,i}},',\n u'V_{\\\\rmmax}={\\\\rmmin}(V_{\\\\rmmax,radio},V_{\\\\rmmax,optical})',\n u'V_{\\\\rmmax,radio}=\\\\sum\\\\limits_{i=1}^{n}F_i\\\\timesV_{\\\\rmmax,radio,i}(z_{\\\\rmmax,i}),',\n u'C_{R}=0.5\\\\left[1+{\\\\rmerf}\\\\left(\\\\frac{{\\\\rmSNR}-\\\\mu}{\\\\sqrt{2}\\\\sigma}\\\\right)\\\\right]',\n u'\\\\Phi(L)=\\\\frac{C}{(L_{*}/L)^{A}+(L_{*}/L)^{B}},',\n u'\\\\Phi_{z}(L)=(1+z)^{k}\\\\Phi_{0}(L),',\n u'\\\\Phi_{z}(L)=\\\\Phi_{0}\\\\Bigg(\\\\frac{L}{(1+z)^{k}}\\\\Bigg),',\n u'\\\\log_{10}\\\\Phi_{z}=m\\\\log_{10}L+k\\\\log_{10}(1+z)+c,',\n u'\\\\log_{10}\\\\Phi_{z}=m(\\\\log_{10}(L)-k\\\\log_{10}(1+z))+c.',\n u'\\\\Gamma=\\\\gamma^{-1}(1-\\\\beta\\\\cos\\\\theta)^{-1},',\n u'\\\\sigma_{\\\\rmmNWA}=\\\\int_{M-\\\\Delta}^{M+\\\\Delta}dm_{{\\\\gamma\\\\gamma}}\\\\bigg[\\\\frac{d\\\\sigma_{\\\\rmsig}}{dm_{{\\\\gamma\\\\gamma}}}\\\\bigg]_{\\\\rmpeak},\\\\quad\\\\hbox{forabroadresonance}.',\n u'K_{\\\\rmintf}=\\\\frac{\\\\sigma_{\\\\rmmNWA}}{\\\\sigma_{\\\\rmprod}\\\\cdot{\\\\rmBr}_{{\\\\gamma\\\\gamma}}}',\n u'\\\\chi^2_{\\\\rmSM}=7.02,\\\\,4.93,\\\\,17.77,\\\\,1.52,\\\\,16.65,',\n u'{\\\\calL}\\\\,i\\\\,\\\\frac{1}{2}M_\\\\Phi^2\\\\Phi^2\\\\,+\\\\,\\\\sum_Q(s_Q\\\\Phi+M_Q)\\\\overline{Q}\\\\gamma_5Q\\\\,+\\\\,\\\\sum_L(s_L\\\\Phi+M_L)\\\\overline{L}\\\\gamma_5L,',\n u'M_Q=1\\\\,{\\\\rmTeV},\\\\,N_Q=2,\\\\,s_Q=0.2.',\n u'M_L=400\\\\,{\\\\rmGeV},\\\\,N_L=6,\\\\,s_L\\\\textrm{isvaried}.',\n u'\\\\Gamma_\\\\Phi=5\\\\,{\\\\rmGeV}.',\n u'\\\\phi\\\\simeq\\\\left\\\\{\\\\begin{array}{ll}8.3^\\\\circ&\\\\hbox{for}s_L>0;\\\\\\\\188.3^\\\\circ&\\\\hbox{for}s_L<0,\\\\end{array}\\\\right.',\n u'{\\\\calM}_{E}=\\\\left(\\\\begin{array}{cc}M&\\\\tfrac{1}{\\\\sqrt{2}}\\\\,Y_{E}v_{2}\\\\\\\\\\\\tfrac{1}{\\\\sqrt{2}}\\\\,Y_E^\\\\primev_2&M_E\\\\end{array}\\\\right)\\\\,.',\n u'\\\\phi\\\\simeq\\\\left\\\\{\\\\begin{array}{rl}90^\\\\circ&\\\\hbox{for}y_E>0;\\\\\\\\-90^\\\\circ&\\\\hbox{for}y_E<0.\\\\end{array}\\\\right.',\n u'da=a\\\\frac{|dm|}{m_1+m_2}\\\\.',\n u'\\\\frac{dN}{dVdt}=\\\\frac{dN_{\\\\rmgal}}{dV}\\\\dot{N}_{SF}f_{Z}f_{\\\\rmmass}f_{\\\\rmsep},',\n u'\\\\frac{dN}{dt}\\\\sim\\\\frac{0.01}{\\\\textrm{Mpc}^3}\\\\times\\\\frac{2}{\\\\textrm{yr}}\\\\times0.1\\\\times10^{-4}\\\\times0.1\\\\sim20\\\\\\\\textrm{Gpc}^{-3}\\\\textrm{yr}^{-1}.',\n u'\\\\begin{aligned}\\\\omega_c=&\\\\begin{cases}0.2+2.7\\\\times10^{-4}\\\\,\\\\left(\\\\frac{m}{M_\\\\odot}-50\\\\right)^2&\\\\text{for}m<50M_\\\\odot,\\\\\\\\0.2&\\\\text{for}m\\\\ge50M_\\\\odot.\\\\\\\\\\\\end{cases}\\\\end{aligned}',\n u'a_\\\\textrm{after}=\\\\frac{m_\\\\textrm{after}}{2m_\\\\textrm{after}-m_\\\\textrm{before}}a_\\\\textrm{before}\\\\,,',\n u'\\\\tau_\\\\textrm{GW}=\\\\frac{5}{256}\\\\frac{c^5}{G^3}\\\\frac{a^4}{m_1m_2(m_1+m_2)}\\\\,.',\n u'\\\\frac{d^2M_\\\\textrm{SFR}}{dtdV_c}=0.015\\\\frac{(1+z)^{2.7}}{[1+(1+z)/2.9]^{5.6}}\\\\,\\\\frac{M_\\\\odot}{\\\\textrm{Mpc}^{3}\\\\textrm{yr}}\\\\,.',\n u'\\\\textrm{CDF}(Z,z)=\\\\hat{\\\\Gamma}\\\\left(\\\\alpha+2,(Z/Z_\\\\odot)^\\\\beta10^{0.15\\\\betaz}\\\\right),',\n u'\\\\frac{d^4N_{\\\\rmmerge}}{dV_{\\\\rmc}\\\\,dt\\\\,dm_1\\\\,dm_2}(t_{\\\\rmm})=\\\\int_{P_{\\\\min}}^{P_{\\\\max}}dP\\\\int_0^1dZ\\\\int_0^{t_{\\\\rmm}}dt\\\\,p(t_{\\\\rmm};m_1,m_2,P,Z,t_{\\\\rmb})\\\\,\\\\,\\\\frac{d^2M_{\\\\rmSFR}}{dt\\\\,dV_{\\\\rmc}}(t_{\\\\rmb})\\\\,\\\\,\\\\frac{d^5N_\\\\textrm{binaries}}{dm_1\\\\,dm_2\\\\,dP\\\\,dZ\\\\,dM_{\\\\rmSFR}}(t_{\\\\rmb})\\\\,.',\n u'\\\\frac{dN_{k,i}^{\\\\rmbirth}}{dt\\\\,dV_{\\\\rmc}}=\\\\textrm{CDF}(Z,z_i)\\\\,\\\\,\\\\frac{d^2M_{\\\\rmSFR}}{dt\\\\,dV_{\\\\rmc}}\\\\,\\\\,\\\\frac{1}{dM_{\\\\rmSFR}},',\n u'\\\\frac{dN_{k,j}^{\\\\rmmerge}}{dt\\\\,dV_{\\\\rmc}}=\\\\sum\\\\frac{dN_{k,i}^{\\\\rmbirth}}{dt\\\\,dV_{\\\\rmc}}\\\\,\\\\delta_{t_i+\\\\tau_k,t_j}\\\\,\\\\frac{dt_i}{dt_j},',\n u'\\\\begin{aligned}\\\\omega_c=&\\\\begin{cases}0.25+3.2\\\\times10^{-4}\\\\,\\\\left(\\\\frac{m}{M_\\\\odot}-46\\\\right)^2&\\\\text{for}m<46M_\\\\odot,\\\\\\\\0.25&\\\\text{for}m\\\\ge46M_\\\\odot.\\\\\\\\\\\\end{cases}\\\\end{aligned}',\n u'u\\\\geq0;\\\\,\\\\,u(-\\\\Deltau-g)=0;\\\\,\\\\,-\\\\Deltau-g\\\\geq0\\\\,\\\\,in\\\\,\\\\,\\\\Omega;',\n u'-\\\\frac{\\\\partialu}{\\\\partialn}=\\\\alpha(u-b)\\\\,\\\\,on\\\\,\\\\,\\\\Gamma_1;\\\\,\\\\,-\\\\frac{\\\\partialu}{\\\\partialn}=q\\\\,\\\\,on\\\\,\\\\,\\\\Gamma_2;',\n u'a_{\\\\alpha}(u_{\\\\alphag},v-u_{\\\\alphag})\\\\geq(g,v-u_{\\\\alphag})_H-(q,v-u_{\\\\alphag})_Q+\\\\alpha(b,v-u_{\\\\alphag})_R,',\n u'V=H^1(\\\\Omega),\\\\hspace{.3cm}K_+=\\\\{v\\\\inV:\\\\,v\\\\geq0\\\\,\\\\,in\\\\,\\\\Omega\\\\},',\n u'\\\\[H=L^2(\\\\Omega),\\\\hspace{.2cm}Q=L^2(\\\\Gamma_2),\\\\hspace{.2cm}\\\\text{and}\\\\hspace{.2cm}\\\\,R=L^2(\\\\Gamma_1),\\\\]',\n u'\\\\[(u,v)_H=\\\\int_\\\\Omegau\\\\,v\\\\,\\\\,dx,\\\\hspace{.1cm}(u,v)_Q=\\\\int_{\\\\Gamma_2}u\\\\,v\\\\,\\\\,ds,\\\\hspace{.1cm}(u,v)_R=\\\\int_{\\\\Gamma_1}u\\\\,v\\\\,\\\\,ds,\\\\]',\n u'\\\\[a(u,v)=\\\\int_\\\\Omegaablau.ablav\\\\,\\\\,dx\\\\]',\n u'a_{\\\\alpha}(u,v)=a(u,v)+\\\\alpha(u,v)_R.',\n u'\\\\,\\\\,a_{\\\\alpha}(v,v)\\\\geq\\\\lambda_{\\\\alpha}\\\\,\\\\Arrowvertv\\\\Arrowvert^2_V\\\\hspace{.5cm}\\\\forall\\\\,\\\\,v\\\\inV.',\n u'J_\\\\alpha(g_{op_\\\\alpha})=\\\\min_{g\\\\inH}J_\\\\alpha(g)',\n u'J_\\\\alpha(g)=\\\\frac{1}{2}\\\\Arrowvertu_{\\\\alphag}\\\\Arrowvert^2_H+\\\\frac{M}{2}\\\\Arrowvertg\\\\Arrowvert^2_H',\n u'\\\\[V_h=\\\\{v_h\\\\inC^0(\\\\overline{\\\\Omega}):v_h/_T\\\\inP_1(T),\\\\,\\\\,\\\\forall\\\\,T\\\\,\\\\in\\\\tau_h\\\\},\\\\]',\n u'\\\\[K_{+h}=\\\\{v_h\\\\inV_{h}:v_h\\\\geq0\\\\,\\\\,in\\\\,\\\\Omega\\\\}\\\\]',\n u'\\\\Arrowvertv-\\\\Pi_h(v)\\\\Arrowvert_H\\\\,\\\\leq\\\\,c_0\\\\,h^r\\\\,\\\\Arrowvertv\\\\Arrowvert_r\\\\,\\\\,\\\\,\\\\forall\\\\,v\\\\inH^r(\\\\Omega),',\n u'\\\\Arrowvertv-\\\\Pi_h(v)\\\\Arrowvert_V\\\\,\\\\leq\\\\,c_0\\\\,h^{r-1}\\\\,\\\\Arrowvertv\\\\Arrowvert_r\\\\,\\\\,\\\\,\\\\forall\\\\,v\\\\inH^r(\\\\Omega).',\n u'a_\\\\alpha(u_{h\\\\alphag},v_h-u_{h\\\\alphag})\\\\geq(g,v_h-u_{h\\\\alphag})_H-(q,v_h-u_{h\\\\alphag})_Q+\\\\alpha(b,v_h-u_{h\\\\alphag})_R.',\n u'\\\\Arrowvertu_{h\\\\alphag_n}\\\\Arrowvert_V\\\\leqC;',\n u'lim_{n\\\\rightarrow\\\\infty}\\\\Arrowvertu_{h\\\\alphag_n}-u_{h\\\\alphag}\\\\Arrowvert_V=0.',\n u'\\\\[\\\\Arrowvertu_{h\\\\alphag_2}-u_{h\\\\alphag_1}\\\\Arrowvert_V\\\\leq\\\\frac{1}{\\\\lambda_\\\\alpha}\\\\Arrowvertg_2-g_1\\\\Arrowvert_H\\\\]',\n u'\\\\Arrowvertu_{h\\\\alphag}-u_{\\\\alphag}\\\\Arrowvert_V\\\\leqC(\\\\alpha)h^{(r-1)/2}.',\n u'\\\\[a_\\\\alpha(u_{h\\\\alphag}-u_{\\\\alphag},u_{h\\\\alphag}-u_{\\\\alphag})\\\\leqa_\\\\alpha(u_{h\\\\alphag},w)-(g,w)_H+(q,w)_Q-\\\\alpha(b,w)_R\\\\]',\n u'\\\\[\\\\Arrowvertu_{h\\\\alphag}-u_{\\\\alphag}\\\\Arrowvert_V^2\\\\,\\\\leq\\\\frac{C}{\\\\lambda_\\\\alpha}\\\\Arrowvert\\\\Pi_h(u_{\\\\alphag})-u_{\\\\alphag}\\\\Arrowvert_V\\\\leq\\\\frac{C}{\\\\lambda_\\\\alpha}h^{r-1}\\\\Arrowvertu_{\\\\alphag}\\\\Arrowvert_r\\\\]',\n u'\\\\,\\\\,J_{h\\\\alpha}(g)=\\\\frac{1}{2}\\\\Arrowvertu_{h\\\\alphag}\\\\Arrowvert^2_H+\\\\frac{M}{2}\\\\Arrowvertg\\\\Arrowvert^2_H',\n u'J_{h\\\\alpha}(g_{op_{h\\\\alpha}})=\\\\min_{g\\\\,\\\\in\\\\,H}J_{h\\\\alpha}(g).',\n u'\\\\[\\\\lim_{\\\\Arrowvertg\\\\Arrowvert_H\\\\rightarrow\\\\infty}J_{h\\\\alpha}(g)=\\\\infty.\\\\]',\n u'\\\\[\\\\liminf_{n\\\\rightarrow\\\\infty}J_{h\\\\alpha}(g_n)\\\\geq\\\\frac{1}{2}\\\\Arrowvertu_{h\\\\alphag}\\\\Arrowvert^2_H+\\\\frac{M}{2}\\\\Arrowvertg\\\\Arrowvert^2_H=J_{h\\\\alpha}(g).\\\\]',\n u'|J_{h\\\\alpha}(g)-J_\\\\alpha(g)|\\\\leqC(\\\\alpha)h^{\\\\frac{r-1}{2}}',\n u'J_{h\\\\alpha}(g)-J_{\\\\alpha}(g)=\\\\frac{1}{2}\\\\,(\\\\rVertu_{h\\\\alphag}\\\\lVert^2_H-\\\\rVertu_{\\\\alphag}\\\\lVert^2_H)=\\\\frac{1}{2}\\\\rVertu_{h\\\\alphag}-u_{\\\\alphag}\\\\lVert^2_H\\\\,+\\\\,(u_{\\\\alphag},u_{h\\\\alphag}-u_{\\\\alphag})_H',\n u'\\\\lvertJ_{h\\\\alpha}(g)-J{\\\\alpha}(g)\\\\rvert\\\\leq\\\\,(\\\\frac{1}{2}\\\\rVertu_{h\\\\alphag}-u_{\\\\alphag}\\\\lVert_H\\\\,+\\\\,\\\\rVertu_{\\\\alphag}\\\\lVert_H)\\\\,\\\\rVertu_{h\\\\alphag}-u_{\\\\alphag}\\\\lVert_H\\\\leqC(\\\\alpha)\\\\,h^{\\\\frac{r-1}{2}},',\n u'a_\\\\alpha(u_{h\\\\alphag},v_h-u_{h\\\\alphag})\\\\geq(g,v_h-u_{h\\\\alphag})_H-(q,v_h-u_{h\\\\alphag})_Q+\\\\alpha(b,v_h-u_{h\\\\alphag})_R',\n u'\\\\[a_\\\\alpha(\\\\eta_\\\\alpha,v-\\\\eta_\\\\alpha)\\\\geq(g,v-\\\\eta_\\\\alpha)_H-(q,v-\\\\eta_\\\\alpha)_Q+\\\\alpha(b,v-\\\\eta_\\\\alpha)_R,\\\\hspace{.4cm}\\\\forall\\\\,v\\\\inK_+\\\\]',\n u'\\\\[\\\\lim_{h\\\\rightarrow0^+}\\\\Arrowvertu_{h\\\\alphag}-u_{\\\\alphag}\\\\Arrowvert_V=0.\\\\]',\n u'g_3(\\\\mu)=\\\\mu\\\\,g_1+(1-\\\\mu)g_2\\\\,\\\\,\\\\inH,',\n u'u_{h\\\\alpha3}(\\\\mu)=\\\\mu\\\\,u_{h\\\\alphag_1}+(1-\\\\mu)u_{h\\\\alphag_2}\\\\,\\\\,\\\\,\\\\inK_{+h}',\n u'0\\\\lequ_{h\\\\alpha4}(\\\\mu)\\\\lequ_{h\\\\alpha3}(\\\\mu)\\\\hspace{0.1cm}in\\\\hspace{0.1cm}\\\\Omega,\\\\hspace{.5cm}\\\\forall\\\\,\\\\,\\\\mu\\\\in[0,1],\\\\,\\\\forallh>0,',\n u'\\\\rVertu_{h\\\\alpha4}(\\\\mu)\\\\lVert_H\\\\,\\\\leq\\\\,\\\\rVertu_{h\\\\alpha3}(\\\\mu)\\\\lVert_H\\\\hspace{.5cm}\\\\forall\\\\,\\\\,\\\\mu\\\\in[0,1],\\\\,\\\\forallh>0.',\n u'\\\\[\\\\rVertg_{3\\\\mu}\\\\lVert^2_H=\\\\mu\\\\rVertg_1\\\\lVert^2_H+(1-\\\\mu)\\\\rVertg_2\\\\lVert^2_H-\\\\mu(1-\\\\mu)\\\\rVertg_2-g_1\\\\lVert^2_H\\\\,\\\\,\\\\,\\\\forallg_1,g_2\\\\inH,\\\\forall\\\\mu\\\\in[0,1]\\\\]',\n u'\\\\[\\\\rVertu_{h\\\\alpha3}(\\\\mu)\\\\lVert^2_H=\\\\mu\\\\rVertu_{h\\\\alpha1}\\\\lVert^2_H+(1-\\\\mu)\\\\rVertu_{h\\\\alpha2}\\\\lVert^2_H-\\\\mu(1-\\\\mu)\\\\rVertu_{h\\\\alpha2}-u_{h\\\\alpha1}\\\\lVert^2_H\\\\]',\n u'\\\\muJ_{h\\\\alpha}(g_1)+(1-\\\\mu)J_{h\\\\alpha}(g_2)-J_{h\\\\alpha}(g_3(\\\\mu))',\n u'=\\\\frac{\\\\mu(1-\\\\mu)}{2}\\\\lVertu_{h\\\\alphag_2}-u_{h\\\\alphag_1}\\\\rVert^2_H+\\\\frac{M}{2}\\\\,\\\\mu(1-\\\\mu)\\\\,\\\\lVertg_2-g_1\\\\rVert^2_H+\\\\frac{1}{2}\\\\big[\\\\lVertu_{h\\\\alpha3}\\\\rVert^2_H-\\\\lVertu_{h\\\\alpha4}\\\\rVert^2_H\\\\big]',\n u'\\\\geq\\\\frac{\\\\mu(1-\\\\mu)}{2}\\\\lVertu_{h\\\\alphag_2}-u_{h\\\\alphag_1}\\\\rVert^2_H+\\\\frac{M}{2}\\\\,\\\\mu(1-\\\\mu)\\\\,\\\\lVertg_2-g_1\\\\rVert^2_H\\\\geq',\n u'\\\\frac{M}{2}\\\\,\\\\mu(1-\\\\mu)\\\\,\\\\lVertg_2-g_1\\\\rVert^2_H>0\\\\hspace{0.2cm}\\\\forall\\\\mu\\\\in(0,1),\\\\,\\\\,g_1eqg_2\\\\inH',\n u'u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}}\\\\rightarrowu_{\\\\alphag_{op_\\\\alpha}}\\\\,\\\\,\\\\,in\\\\,\\\\,\\\\,V\\\\,\\\\,\\\\,strong\\\\,\\\\,\\\\,when\\\\,\\\\,\\\\,h\\\\rightarrow0^+,',\n u'g_{op_{h\\\\alpha}}\\\\rightarrowg_{op_\\\\alpha}\\\\,\\\\,\\\\,in\\\\,\\\\,\\\\,H\\\\,\\\\,\\\\,strong\\\\,\\\\,\\\\,when\\\\,\\\\,\\\\,h\\\\rightarrow0^+.',\n u'J_{h\\\\alpha}(g_{op_{h\\\\alpha}})=\\\\frac{1}{2}\\\\lVertu_{h\\\\alphag_{op_{h\\\\alpha}}}\\\\rVert^2_H+\\\\frac{M}{2}\\\\lVertg_{op_{h\\\\alpha}}\\\\rVert^2_H\\\\,\\\\leq\\\\,\\\\frac{1}{2}\\\\lVertu_{h\\\\alphag}\\\\rVert^2_H+\\\\frac{M}{2}\\\\lVertg\\\\rVert^2_H.',\n u'J_{h\\\\alpha}(g_{op_{h\\\\alpha}})=\\\\frac{1}{2}\\\\lVertu_{h\\\\alphag_{op_{h\\\\alpha}}}\\\\rVert^2_H+\\\\frac{M}{2}\\\\lVertg_{op_{h\\\\alpha}}\\\\rVert^2_H\\\\,\\\\leq\\\\,\\\\frac{1}{2}\\\\lVertu_{h\\\\alpha0}\\\\rVert^2_H.',\n u'\\\\lVertu_{h\\\\alphag_{op_{h\\\\alpha}}}\\\\rVert_H\\\\leqC\\\\hspace{0.4cm}\\\\forall\\\\hspace{0.2cm}h',\n u'\\\\lVertg_{op_{h\\\\alpha}}\\\\rVert_H\\\\,\\\\leq\\\\,\\\\frac{1}{\\\\sqrt{M}}\\\\,\\\\lVertu_{h\\\\alpha0}\\\\rVert_H\\\\leq\\\\frac{1}{\\\\sqrt{M}}\\\\,C\\\\hspace{0.4cm}\\\\forall\\\\hspace{0.2cm}h.',\n u'\\\\lVertu_{h\\\\alphag_{op_{h\\\\alpha}}}\\\\rVert_V\\\\leqC',\n u'a_\\\\alpha(\\\\eta_\\\\alpha,v-\\\\eta_\\\\alpha)\\\\geq(f_\\\\alpha,v-\\\\eta_\\\\alpha)-(q,v-\\\\eta_\\\\alpha)_Q+\\\\alpha(b,v-\\\\eta_\\\\alpha)_R,\\\\hspace{1cm}\\\\forall\\\\,\\\\,v\\\\inK_+',\n u'\\\\[a_\\\\alpha(w_h,w_h)\\\\leq-a_\\\\alpha(u_{h\\\\alphag_{op_{h\\\\alpha}}},\\\\Pi_h(u_{\\\\alphag_{op_\\\\alpha}})-u_{\\\\alpha{g_{op\\\\alpha}}})+(q,\\\\Pi_h(u_{\\\\alphag_{op_\\\\alpha}})-u_{\\\\alpha{g_{op\\\\alpha}}})_Q\\\\]',\n u'\\\\[-\\\\alpha(b,\\\\Pi_h(u_{\\\\alphag_{op_\\\\alpha}})-u_{\\\\alpha{g_{op\\\\alpha}}})_R+(g_{op_{h\\\\alpha}},\\\\Pi_h(u_{\\\\alphag_{op_\\\\alpha}})-u_{h\\\\alphag_{op_{h\\\\alpha}}})_H\\\\]',\n u'\\\\[-(g_{op_\\\\alpha},w_h)_H.\\\\]',\n u'\\\\,\\\\,\\\\,\\\\,u\\\\geq0;\\\\,\\\\,u(-\\\\Deltau-g)=0;\\\\,\\\\,-\\\\Deltau-g\\\\geq0\\\\,\\\\,in\\\\,\\\\,\\\\Omega;',\n u'u=b\\\\,\\\\,\\\\,on\\\\,\\\\,\\\\Gamma_1;\\\\,\\\\,\\\\,-\\\\frac{\\\\partialu}{\\\\partialn}=q\\\\,\\\\,\\\\,on\\\\,\\\\,\\\\,\\\\Gamma_2;',\n u'a(u,v-u_g)\\\\geq(g,v-u_g)_H-(q,v-u_g)_Q,\\\\,\\\\,\\\\,\\\\forall\\\\,v\\\\inK',\n u'K=\\\\{v\\\\inV:\\\\,v\\\\geq0\\\\,\\\\,in\\\\,\\\\,\\\\Omega,\\\\,v{/\\\\Gamma_1}=b\\\\}.',\n u'J(g_{op})=\\\\min_{g\\\\inH}J(g)',\n u'J(g)=\\\\frac{1}{2}\\\\Arrowvertu_g\\\\Arrowvert^2_H+\\\\frac{M}{2}\\\\Arrowvertg\\\\Arrowvert^2_H',\n u'a(u_{hg},v_h-u_{hg})\\\\geq(g,v_h-u_{hg})_H-(q,v_h-u_{hg})_Q\\\\,\\\\,\\\\,\\\\forallv_h\\\\inK_h.',\n u'\\\\[K_h=\\\\{v_h\\\\inV_h:v_h\\\\geq0\\\\,\\\\,in\\\\,\\\\,\\\\Omega,v_h/\\\\Gamma_1=b\\\\}\\\\]',\n u'J_h(g_{op_h})=\\\\min_{g\\\\inH}J_h(g)=\\\\frac{1}{2}\\\\Arrowvertu_{hg}\\\\Arrowvert^2_H+\\\\frac{M}{2}\\\\Arrowvertg\\\\Arrowvert^2_H,',\n u'\\\\[lim_{\\\\alpha\\\\rightarrow\\\\infty}\\\\Arrowvertu_{h\\\\alphag}-u_{hg}\\\\Arrowvert_V=0.\\\\]',\n u'\\\\[a_\\\\alpha(w,w)-a_1(w,w)=(\\\\alpha-1)\\\\lVertw\\\\rVert_R^2.\\\\]',\n u'a_1(w,w)\\\\leqa_1(w,w)+(\\\\alpha-1)\\\\lVertw\\\\rVert_R^2\\\\leq(g,w)_H-(q,w)_Q-a(u_{hg},w)',\n u'\\\\[\\\\lVertu_{h\\\\alphag}-u_{hg}\\\\rVert_R^2\\\\leq\\\\frac{C}{\\\\alpha-1}\\\\]',\n u'\\\\[u_{h\\\\alphag}\\\\rightharpoonup\\\\eta\\\\,\\\\,\\\\text{in}\\\\,V\\\\,\\\\,(\\\\text{inHstrong}).\\\\]',\n u'u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}}\\\\rightarrowu_{hf_h}\\\\,\\\\,\\\\,in\\\\,\\\\,\\\\,V\\\\,\\\\,\\\\,when\\\\,\\\\,\\\\,\\\\alpha\\\\rightarrow\\\\infty,',\n u'g_{op_{h\\\\alpha}}\\\\rightarrowf_h\\\\,\\\\,\\\\,in\\\\,\\\\,\\\\,H\\\\,\\\\,\\\\,\\\\,when\\\\,\\\\,\\\\,\\\\alpha\\\\rightarrow\\\\infty.',\n u'\\\\[a_\\\\alpha(u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}},w_h)\\\\geq(g_{op_{h\\\\alpha}},w_h)_H-(q,w_h)_Q+\\\\alpha(b,w_h)_R\\\\]',\n u'a_1(-w_h,w_h)+a_1(b,w_h)\\\\geq(g_{op_{h\\\\alpha}},w_h)_H-(q,w_h)_Q+(\\\\alpha-1)\\\\lVertw_h\\\\rVert_R.',\n u'\\\\lVertu_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}}\\\\rVert_V\\\\leqC\\\\,\\\\,\\\\,\\\\forall\\\\,\\\\alpha>0.',\n u'\\\\lVertu_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}}\\\\rVert_R\\\\leq\\\\frac{C}{\\\\alpha-1}\\\\,\\\\,\\\\,\\\\forall\\\\,\\\\alpha>0.',\n u'g_{op_{h\\\\alpha}}\\\\rightharpoonupf_h\\\\,\\\\,\\\\text{in}\\\\,\\\\,H',\n u'u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}}\\\\rightharpoonup\\\\eta_h\\\\,\\\\,\\\\text{in}\\\\,\\\\,V\\\\,\\\\,\\\\text{(inHstrong)}',\n u'\\\\[a_\\\\alpha(u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}},w_h)\\\\geq(g_{op_{h\\\\alpha}},w_h)_H-(q,w_h)_Q+\\\\alpha(b,w_h)_R\\\\]',\n u'\\\\[a(u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}},w_h)\\\\geq(g_{op_{h\\\\alpha}},w_h)_H-(q,w_h)_Q+\\\\alpha(b-u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}},w_h)_R\\\\]',\n u'\\\\[a_\\\\alpha(u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}},w_h)\\\\geq(g_{op_{h\\\\alpha}},w_h)_H-(q,w_h)_Q+\\\\alpha(b,w_h)_R\\\\]',\n u'\\\\[a_1(w_h,w_h)\\\\leqa_1(u_{hf_h},w_h)-(g_{op_{h\\\\alpha}},w_h)_H+(q,w_h)_Q-\\\\alpha(b,w_h)_R\\\\,+\\\\]',\n u'\\\\[(\\\\alpha-1)(u_{h\\\\alphag_{op_{h\\\\alpha}}},w_h)_R.\\\\]',\n u'\\\\[J_h(f_h)\\\\leq\\\\lim_{\\\\alpha\\\\rightarrow\\\\infty}J_{h\\\\alpha}(g_{op_{h\\\\alpha}})\\\\leq\\\\lim_{\\\\alpha\\\\rightarrow\\\\infty}J_{h\\\\alpha}(g)\\\\,\\\\,\\\\\\\\forall\\\\,g\\\\inH\\\\]',\n u'\\\\[J_h(f_h)\\\\leqJ_h(g)\\\\,\\\\,\\\\\\\\forall\\\\,g\\\\inH.\\\\]',\n u'\\\\[J_h(f_h)\\\\leq\\\\lim_{\\\\alpha\\\\rightarrow\\\\infty}J_{h\\\\alpha}(g_{op_{h\\\\alpha}})\\\\leqJ_h(g)\\\\,\\\\,\\\\\\\\forall\\\\,g\\\\inH\\\\]',\n u'\\\\[\\\\lim_{\\\\alpha\\\\rightarrow\\\\infty}J_{h\\\\alpha}(g_{op_{h\\\\alpha}})=J_h(f_h)\\\\]',\n u'\\\\lim_{\\\\alpha\\\\rightarrow\\\\infty}\\\\lVertg_{op_{h\\\\alpha}}\\\\rVert_H=\\\\lVertf\\\\rVert_H.',\n u'u_{h\\\\alpha\\\\,g_{op_{h\\\\alpha}}}\\\\rightarrowu_{g_{op}}\\\\,\\\\,\\\\,in\\\\,\\\\,\\\\,V\\\\,\\\\,\\\\,when\\\\,\\\\,\\\\,(h,\\\\alpha)\\\\rightarrow(0^+,\\\\infty),',\n u'g_{op_{h\\\\alpha}}\\\\rightarrowg_{op}\\\\,\\\\,\\\\,in\\\\,\\\\,\\\\,H\\\\,\\\\,\\\\,\\\\,\\\\,when\\\\,\\\\,\\\\,(h,\\\\alpha)\\\\rightarrow(0^+,\\\\infty).',\n u'u_{h\\\\alphag_{op_{h\\\\alpha}}}\\\\rightharpoonupu^*\\\\hspace{1cm}(strong\\\\quadin\\\\quadH)',\n u'g_{op_{h\\\\alpha}}\\\\rightharpoonupg^*',\n u'\\\\[a(u_{h\\\\alphag_{op_{h\\\\alpha}}},w_h)\\\\geq(g_{op_{h\\\\alpha}},w_h)_H-(q,w_h)_Q.\\\\]',\n u'\\\\[a_\\\\alpha(u_{h\\\\alphag_{op_{h\\\\alpha}}}-u_{g^*},u_{h\\\\alphag_{op_{h\\\\alpha}}}-u_{g^*})\\\\leq(g_{op_{h\\\\alpha}},u_{h\\\\alphag_{op_{h\\\\alpha}}}-\\\\Pi(u_{g^*}))_H\\\\]',\n u'\\\\[+(q,u_{h\\\\alphag_{op_{h\\\\alpha}}}-\\\\Pi(u_{g^*}))_Q+\\\\alpha(b,u_{h\\\\alphag_{op_{h\\\\alpha}}}-\\\\Pi(u_{g^*}))_R-a_\\\\alpha(u_{g^*},u_{h\\\\alphag_{op_{h\\\\alpha}}}-\\\\Pi(u_{g^*}))\\\\]',\n u'\\\\[+a_\\\\alpha(u_{h\\\\alphag_{op_{h\\\\alpha}}},\\\\Pi(u_{g^*})-u_{g^*})-a_\\\\alpha(u_{g^*},\\\\Pi(u_{g^*})-u_{g^*}).\\\\]',\n u'R^s{\\\\stackrel{{u_{\\\\mathbf{a}}}}{\\\\longrightarrow}}R^\\\\ell{\\\\stackrel{{\\\\pi_{\\\\mathbf{a}}}}{\\\\longrightarrow}}M\\\\rightarrow0',\n u'0\\\\rightarrowK_{\\\\mathbf{a}}{\\\\stackrel{{j_{\\\\mathbf{a}}}}{\\\\longrightarrow}}R^\\\\ell{\\\\stackrel{{\\\\pi_{\\\\mathbf{a}}}}{\\\\longrightarrow}}M\\\\rightarrow0.',\n u'R^s/IR^s{\\\\stackrel{{u_{{\\\\mathbf{a}},I}}}{\\\\longrightarrow}}(R/I)^\\\\ell{\\\\stackrel{{\\\\pi_{{\\\\mathbf{a}},I}}}{\\\\longrightarrow}}M/IM\\\\rightarrow0.',\n u'0\\\\rightarrowK_{{\\\\mathbf{a}},I}{\\\\stackrel{{j_{{\\\\mathbf{a}},I}}}{\\\\longrightarrow}}(R/I)^\\\\ell{\\\\stackrel{{\\\\pi_{{\\\\mathbf{a}},I}}}{\\\\longrightarrow}}M/IM\\\\rightarrow0.',\n u'\\\\mu(M)\\\\cdot\\\\lambda_R(R/I)=\\\\lambda_R(K_{{\\\\mathbf{a}},I})+\\\\lambda_R(M/IM).',\n u'\\\\mu(J)\\\\cdot\\\\lambda_R(R/I)+\\\\lambda_R(R/J)=\\\\lambda_R(K_{{\\\\mathbf{a}},I})+\\\\lambda_R(R/IJ).',\n u'\\\\lambda_R(M/IM)\\\\leq\\\\mu(M)\\\\cdot\\\\lambda_R(R/I).',\n u'\\\\lambda_R(R/IJ)\\\\leq\\\\mu(J)\\\\cdot\\\\lambda_R(R/I)+\\\\lambda_R(R/J).',\n u'\\\\[\\\\lambda_R(R/IJ)\\\\leq\\\\min\\\\{\\\\mu(J)\\\\cdot\\\\lambda_R(R/I)+\\\\lambda_R(R/J),\\\\lambda_R(R/I)+\\\\mu(I)\\\\cdot\\\\lambda_R(R/J)\\\\}.\\\\]',\n u'\\\\[\\\\lambda_R(R/I^n)\\\\leq\\\\left(1+\\\\ell+\\\\cdots+\\\\ell^{n-1}\\\\right)\\\\cdot\\\\lambda_R(R/I).\\\\]',\n u'\\\\[v_{ij}({\\\\mathbf{a}}):=-a_je_i+a_ie_j,\\\\]',\n u'-a_je_i+a_ie_j\\\\inC_{ij}\\\\subseteq{\\\\mathrm{{im}}\\\\,}\\\\partial_2\\\\subseteqIR^\\\\ell=\\\\oplus_{h=1}^\\\\ellIe_h,',\n u'\\\\[K_{\\\\mathbf{a}}=\\\\ker\\\\partial_1={\\\\mathrm{{im}}\\\\,}\\\\partial_2=\\\\sum_{il,-C\\\\le\\\\boldsymbol{\\\\beta}_i\\\\le0;\\\\foralli\\\\\\\\&C,\\\\zeta,l\\\\,\\\\text{:hyper-parameters},\\\\\\\\\\\\end{aligned}\",\n u'g_{DS}({D}_i,{D}_j)=\\\\textbf{F}_i^\\\\textsf{T}\\\\textbf{P}_i\\\\textbf{P}_j^\\\\textsf{T}\\\\textbf{F}_j',\n u'a(T)=a_0+a_1\\\\left(\\\\frac{T_0}T\\\\right)+a_2\\\\left(\\\\frac{T_0}T\\\\right)^2,\\\\quadb(T)=b_3\\\\left(\\\\frac{T_0}T\\\\right)^3.',\n u'f_0(\\\\xi_i;\\\\Phi,\\\\bar\\\\Phi)=\\\\frac{\\\\bar\\\\Phi\\\\xi_i^2+2\\\\Phi\\\\xi_i+1}{\\\\xi_i^3+3\\\\bar\\\\Phi\\\\xi_i^2+3\\\\Phi\\\\xi_i+1}',\n u'\\\\rho(t)=\\\\mathcalU(t,t_0)\\\\rho(t_0)\\\\mathcalU^\\\\dagger(t,t_0),',\n u'\\\\rho_0(t)=\\\\mathcalU_0(t,t_0)\\\\rho(t_0)\\\\mathcalU^\\\\dagger_0(t,t_0)',\n u'H^\\\\prime_I(t^\\\\prime)=U^\\\\dagger_0(t^\\\\prime,t_0)H^\\\\prime(t^\\\\prime)\\\\mathcalU_0(t^\\\\prime,t_0)',\n u'\\\\delta\\\\langleA(t)\\\\rangle\\\\approxi\\\\intd\\\\bart\\\\theta(t-\\\\bart)\\\\langle[H_I^\\\\prime(\\\\bart),A_I(t)]\\\\rangle_0,',\n u'\\\\widetilde\\\\chi(k)=\\\\intd^4x\\\\chi(x)e^{ikx}.',\n u'\\\\widetildeS_a(i\\\\omega_n,\\\\mathbfp)=-\\\\int\\\\frac{dp^0}{2\\\\pi}\\\\frac{\\\\widetilde{\\\\mathcalA}_a(p)}{i\\\\omega_n-p^0},',\n u'\\\\widetilde{\\\\mathcalA}_a(p)\\\\equiv\\\\intd^4x\\\\mathcalA_a(x)e^{ipx/\\\\hbar}\\\\equiv\\\\intd^4x\\\\{q_a(x),\\\\barq_a(0)\\\\}e^{ipx/\\\\hbar}.',\n u'\\\\widetilde{\\\\mathcalA}_a(p)=\\\\pi[\\\\Delta_+(\\\\mathbfp)\\\\delta(p^0+\\\\widetilde\\\\mu_a-E_{\\\\mathbfp})-\\\\Delta_-(\\\\mathbfp)\\\\delta(p^0+\\\\widetilde\\\\mu_a+E_{\\\\mathbfp})],',\n u'\\\\Delta_\\\\pm(\\\\mathbfp)=\\\\pm\\\\gamma^0-\\\\frac{\\\\mathbfp}{E_\\\\mathbf{p}}\\\\cdot\\\\boldsymbol\\\\gamma+\\\\fracM{E_\\\\mathbf{p}},',\n u'D[f_a]=C[f_z],',\n u'D[f_a]\\\\equiv\\\\partial_tf_a+\\\\mathbfv\\\\cdotabla_\\\\mathbf{r}f_a+\\\\frac{M_a}{E_a}abla_\\\\mathbf{r}V^Sabla_\\\\mathbfpf_a,',\n u'D[f_a]\\\\approx\\\\partial_t\\\\deltaf_a+\\\\mathbfv\\\\cdotabla_\\\\mathbf{r}\\\\deltaf_a+\\\\frac{M_a}{E_a}abla_\\\\mathbf{r}\\\\deltaV^Sabla_\\\\mathbfpf^0_a,',\n u'C[f_a]\\\\approx-\\\\frac1{\\\\tau_a}\\\\deltaf_a,',\n u'\\\\frac1{\\\\tau_a}=\\\\sum_{bcd}\\\\intd^3\\\\mathbfPd^3\\\\mathbfp\\\\frac{(2\\\\pi)^{-5}\\\\delta(E_a+E_b-E_c-E_d)}{(1+\\\\delta_{ab})2^32E_a2E_b2E_c2E_d}|\\\\mathcalM_{ab}|^2\\\\frac{f_b^0(1-f_c^0)(1-f_d^0)}{1-f_a^0}.',\n u'\\\\delta(E_a+E_b-E_c-E_d)=\\\\intdE\\\\delta(E_a+E_b-E)\\\\delta(E_c+E_d-E),',\n u'\\\\delta(E-E_a-E_b)=\\\\frac{E_b}{Pp_a}\\\\delta\\\\left(x-\\\\frac{p_a^2-p_b^2+P^2}{2Pp_a}\\\\right),',\n u'\\\\delta(E_c+E_d-E)=\\\\delta\\\\left(p-E\\\\sqrt{\\\\frac{s-2m^2}{E^2-P^2x^{\\\\prime2}}}\\\\right)\\\\frac{4EE_cE_d}{p(E^2-P^2x^{\\\\prime2})},',\n u'\\\\partial_t\\\\deltaf_a+\\\\mathbfv\\\\cdotabla_\\\\mathbf{r}\\\\deltaf_a++\\\\frac{M_a}{E_a}abla_\\\\mathbf{r}\\\\deltaV^S_aabla_\\\\mathbfpf^0_a+\\\\tau^{-1}_a\\\\deltaf_a=0.',\n u'(\\\\omega+i\\\\tau^{-1}_a-\\\\mathbfk\\\\cdot\\\\mathbfv_a)\\\\delta\\\\tildef_a+\\\\frac{M_a}{E_a}\\\\delta\\\\tildeV^S_a\\\\mathbfk\\\\cdotabla_\\\\mathbfpf^0_a=0.',\n u'\\\\left(\\\\begin{array}{cc}1-2(G_S+K\\\\langle\\\\barss\\\\rangle)(\\\\chi_q-\\\\xi_q)&-2K\\\\langle\\\\barqq\\\\rangle(\\\\chi_q-\\\\xi_q)\\\\\\\\-4K\\\\langle\\\\barqq\\\\rangle(\\\\chi_s-\\\\xi_s)&1-2G_S(\\\\chi_s-\\\\xi_s)\\\\end{array}\\\\right)\\\\left(\\\\begin{array}{c}\\\\delta\\\\langle\\\\barqq\\\\rangle\\\\\\\\\\\\delta\\\\langle\\\\barss\\\\rangle\\\\end{array}\\\\right)=0,',\n u'\\\\xi=\\\\frac{N_c}{\\\\pi^2}\\\\intdE\\\\frac{p^3}{E^2}(f^0+\\\\barf^0-1).',\n u'\\\\left|\\\\begin{array}{cc}1-2(G_S+K\\\\langle\\\\barss\\\\rangle)(\\\\chi_q-\\\\xi_q)&-2K\\\\langle\\\\barqq\\\\rangle(\\\\chi_q-\\\\xi_q)\\\\\\\\-4K\\\\langle\\\\barqq\\\\rangle(\\\\chi_s-\\\\xi_s)&1-2G_S(\\\\chi_s-\\\\xi_s)\\\\end{array}\\\\right|=0.',\n u'\\\\[R_i=\\\\{c_{x1},c_{y1},c_{x2},c_{y2}\\\\},\\\\quadc_i\\\\simU(x|0,w)\\\\]',\n u'f(s,R_1,R_2)=\\\\begin{cases}1&\\\\text{if}\\\\displaystyle\\\\sum_{i|x_i\\\\inR_1}\\\\frac{x_i}{n_{1}}<\\\\sum_{i|x_i\\\\inR_2}\\\\frac{x_i}{n_{2}}\\\\\\\\0&\\\\text{otherwise}\\\\end{cases}',\n u'\\\\hat{S}(t)=\\\\prod_{j:t_{(j)}\\\\leqt}{\\\\left(1-\\\\frac{d_j}{r_j}\\\\right)}',\n u'\\\\hat{\\\\chi^2}=\\\\frac{\\\\left(\\\\sum^m_{i=1}{(d_{1i}-\\\\hat{e}_{1i})}\\\\right)^2}{\\\\sum^m_{i=1}{\\\\hat{v}_{1i}}}',\n u'S(t)=1-p(T\\\\leqt_0)=1-\\\\int_0^{t_0}{p(t)dt},',\n u'h(t)=\\\\lim\\\\limits_{\\\\Deltat\\\\rightarrow0}\\\\frac{P(tt)}{\\\\Deltat}=\\\\frac{p(T=t)}{S(t)}.',\n u'h(t|{\\\\boldsymbol{x}})=h_0(t)\\\\exp({\\\\boldsymbol{x}}^{T}{\\\\boldsymbol{\\\\beta}}),',\n u'p(t|\\\\alpha_w,\\\\lambda_w)=\\\\alpha_w\\\\frac{1}{\\\\lambda_w}t^{\\\\alpha_w-1}\\\\exp\\\\left(-\\\\frac{1}{\\\\lambda_w}t^{\\\\alpha_w}\\\\right),',\n u'p(\\\\left\\\\{t_i\\\\right\\\\}_{i=0}^{N}|\\\\alpha_w,\\\\lambda_w)=\\\\prod_{i=1}^N{\\\\left(\\\\frac{\\\\alpha_w}{\\\\lambda_w}t_i^{\\\\alpha_w-1}\\\\right)^{\\\\delta_i}\\\\exp\\\\left(-\\\\frac{1}{\\\\lambda_w}t_i^{\\\\alpha_w}\\\\right)},',\n u'\\\\eta={\\\\boldsymbol{x}}^{t}{\\\\boldsymbol{\\\\beta}}+\\\\epsilon,\\\\hspace{20pt}\\\\text{where\\\\}\\\\epsilon\\\\simN(0,\\\\sigma^2).',\n u'T_{ij}=\\\\frac{1}{N}\\\\sum_{k=1}^Nr_{ki}r_{kj}~,',\n u'R_p=\\\\left(\\\\frac{1}{N}\\\\sum_{i=1}^Nr_i^2\\\\right)^{1/2}=(\\\\Lambda_1+\\\\Lambda_2+\\\\Lambda_3)^{1/2}',\n u'R_g=\\\\sqrt{\\\\left\\\\langleR_p^2\\\\right\\\\rangle}=\\\\sqrt{\\\\left\\\\langle\\\\Lambda_1+\\\\Lambda_2+\\\\Lambda_3\\\\right\\\\rangle}~,',\n u'\\\\frac{x^2}{\\\\Lambda_1}+\\\\frac{y^2}{\\\\Lambda_2}+\\\\frac{z^2}{\\\\Lambda_3}=3~.',\n u'P_0(\\\\lambda_1,\\\\lambda_2,\\\\lambda_3)=P_1(\\\\lambda_1)P_2(\\\\lambda_2)P_3(\\\\lambda_3)~,',\n u'P_i(\\\\lambda_i)=\\\\frac{(a_id_i)^{n_i-1}\\\\lambda_i^{-n_i}}{2K_i}\\\\exp\\\\left(-\\\\frac{\\\\lambda_i}{a_i}-d_i^2\\\\frac{a_i}{\\\\lambda_i}\\\\right)~,',\n u'A(\\\\phi_n)=1-3\\\\frac{\\\\left\\\\langle\\\\lambda_1\\\\lambda_2+\\\\lambda_1\\\\lambda_3+\\\\lambda_2\\\\lambda_3\\\\right\\\\rangle}{\\\\left\\\\langle(\\\\lambda_1+\\\\lambda_2+\\\\lambda_3)^2\\\\right\\\\rangle}~.',\n u'\\\\frac{R_g(\\\\phi_n)}{R_g(0)}=\\\\sqrt{6\\\\left\\\\langle\\\\lambda_1+\\\\lambda_2+\\\\lambda_3\\\\right\\\\rangle}~,',\n u'R_i(\\\\phi_n)=R_g(0)\\\\sqrt{18\\\\lambda_i}~,\\\\quadi=1,2,3~.',\n u'f=k_BT~\\\\frac{4\\\\pin_pR_p^3}{q}\\\\left(1+\\\\frac{2}{\\\\sqrt{\\\\pi}q}+\\\\frac{1}{3q^2}\\\\right)~,',\n u'\\\\beta\\\\varepsilon=\\\\frac{4\\\\piR_p^3}{v_pq}\\\\left(1+\\\\frac{2}{\\\\sqrt{\\\\pi}q}+\\\\frac{1}{3q^2}\\\\right)~,',\n u'\\\\beta\\\\varepsilon=\\\\frac{3}{q}\\\\left(1+\\\\frac{2}{\\\\sqrt{\\\\pi}q}+\\\\frac{1}{3q^2}\\\\right)~,',\n u'v_p=\\\\frac{4\\\\pi}{3}\\\\intd\\\\lambda\\\\,P_0(\\\\lambda)R_1R_2R_3=1.8365~R_p^3~,',\n u'\\\\beta\\\\varepsilon=\\\\frac{6.8426}{q}\\\\left(1+\\\\frac{2}{\\\\sqrt{\\\\pi}q}+\\\\frac{1}{3q^2}\\\\right)~.',\n u'v_p(\\\\phi_n)=\\\\frac{4\\\\pi}{3}\\\\intd\\\\lambda\\\\,P(\\\\lambda;\\\\phi_n)R_1R_2R_3~.',\n u'{\\\\calP}_{\\\\rmconfig}({\\\\rmold}\\\\to{\\\\rmnew})=\\\\min\\\\left\\\\{e^{-\\\\beta\\\\DeltaF},~1\\\\right\\\\}~,',\n u\"{\\\\bfu}'=\\\\frac{{\\\\bfu}+\\\\tau{\\\\bfv}}{|{\\\\bfu}+\\\\tau{\\\\bfv}|}~,\",\n u\"{\\\\calP}_{\\\\rmshape}(\\\\lambda\\\\to\\\\lambda')=\\\\min\\\\left\\\\{\\\\frac{P_0(\\\\lambda')}{P_0(\\\\lambda)}e^{-\\\\beta\\\\DeltaF},~1\\\\right\\\\}~,\",\n u'v_{\\\\rmmf}(r)=\\\\Omega(r)-\\\\Omega(\\\\infty)~,',\n u\"v_{\\\\rmmf}(r)=-\\\\Pi_p\\\\int_{\\\\infty}^rdr'\\\\,A_{\\\\rmov}(r')=-\\\\Pi_pV_{\\\\rmov}(r)~,\",\n u'V_{\\\\rmov}(r)=\\\\frac{\\\\displaystyle4\\\\pi}{\\\\displaystyle3}\\\\left[\\\\left(R_n+R_p\\\\right)^3-\\\\frac{\\\\displaystyle3r}{\\\\displaystyle4}(R_n+R_p)^2+\\\\frac{\\\\displaystyler^3}{\\\\displaystyle16}\\\\right]~,',\n u'\\\\Xi(r)\\\\propto\\\\left\\\\langle\\\\exp[-\\\\betaU(r)]\\\\right\\\\rangle~,',\n u'\\\\betav_{\\\\rmmf}(r)=-\\\\ln\\\\left(\\\\frac{\\\\left\\\\langle\\\\exp[-\\\\betaU(r)]\\\\right\\\\rangle}{\\\\left\\\\langle\\\\exp[-\\\\betaU(\\\\infty)]\\\\right\\\\rangle}\\\\right)~,',\n u'\\\\betav_{\\\\rmmf}(r)=\\\\left\\\\langle\\\\exp[-\\\\betaU(\\\\infty)]\\\\right\\\\rangle-\\\\left\\\\langle\\\\exp[-\\\\betaU(r)]\\\\right\\\\rangle~.',\n u'\\\\left\\\\langle\\\\exp[-\\\\betaU(\\\\infty)]\\\\right\\\\rangle=1-2c(r)\\\\phi_n=2\\\\left\\\\langle\\\\exp(-\\\\betaU_0)\\\\right\\\\rangle-1~.',\n u'\\\\left\\\\langle\\\\exp(-\\\\betaU_0)\\\\right\\\\rangle=\\\\frac{V-\\\\frac{4\\\\pi}{3}(R_n+R_p)^3}{V}=1-\\\\phi_n(1+q)^3~.',\n u'\\\\left\\\\langle\\\\exp[-\\\\betaU(\\\\infty)]\\\\right\\\\rangle=1-2\\\\phi_n(1+q)^3~.',\n u'\\\\left\\\\langle\\\\exp[-\\\\betaU(r)]\\\\right\\\\rangle=\\\\frac{V-\\\\frac{8\\\\pi}{3}(R_n+R_p)^3+V_{\\\\rmov}(r)}{V}~.',\n u'\\\\left\\\\langle\\\\exp[-\\\\betaU(r)]\\\\right\\\\rangle=1-\\\\phi_n\\\\left[(1+q)^3+\\\\frac{3}{4}x(1+q)^2-\\\\frac{x^3}{16}\\\\right]~,',\n u'\\\\betav_{\\\\rmmf}(r)=-12\\\\phi_p\\\\left[\\\\frac{h(x/q)}{qx}+\\\\frac{g(x/q)}{q^2x}-\\\\frac{h(2x/q)}{2qx^2}\\\\right]~,',\n u'g(x)\\\\equiv\\\\frac{e^{-x^2}}{\\\\sqrt{\\\\pi}}-x+x{\\\\rmErf}(x)',\n u'h(x)\\\\equiv\\\\frac{1}{4}\\\\left[-\\\\frac{2}{\\\\sqrt{\\\\pi}}xe^{-x^2}+(1+2x^2){\\\\rmErfc}(x)\\\\right]~,',\n u'p^{(n)}(s)=\\\\frac{(n+1)^{n+1}}{\\\\Gamma(n+1)}\\\\frac{s^n}{{\\\\bars}^{n+1}}\\\\exp[-(n+1)s/{\\\\bars}]~,',\n u'P(\\\\lambda;\\\\phi_n)=P_0(\\\\lambda)\\\\frac{\\\\alpha(\\\\lambda;\\\\phi_n)}{\\\\alpha_{\\\\rmeff}(\\\\phi_n)}~,',\n u'\\\\alpha_{\\\\rmeff}(\\\\phi_n)\\\\equiv\\\\int_0^{\\\\infty}{\\\\rmd}\\\\lambda\\\\,P_0(\\\\lambda)\\\\alpha(\\\\lambda;\\\\phi_n)',\n u\"\\\\alpha(\\\\lambda;\\\\phi_n)=(1-\\\\phi_n')\\\\exp[-\\\\beta(pv_p+\\\\gammaa_p+\\\\kappac_p)]~,\",\n u'U_{i}(\\\\mathbf{x})=exp\\\\left(\\\\mathbf{|\\\\tildex_i|}\\\\right)^{\\\\beta}exp(i\\\\phi_{i})',\n u'\\\\phi_{p,i}(\\\\mathbf{x})=ka_{i}',\n u'\\\\phi_{t,i}(\\\\mathbf{x})=k\\\\mathbf{x}\\\\mathbf{b}_i',\n u'U(\\\\mathbf{x})=\\\\left[\\\\sum_{i=1}^{M}U_{i}(\\\\mathbf{x})\\\\right]exp\\\\left(\\\\dfrac{|\\\\mathbf{x}-\\\\mathbf{c}_0|_2}{R}\\\\right)^\\\\gamma',\n u'|\\\\mathbfc_{i}-\\\\mathbfc_{j}|>2r_s,ieqj',\n u'E^+(\\\\mathbf{v})=\\\\frac{1}{\\\\lambda}\\\\sum_{\\\\mathbf{x}}exp\\\\left(i\\\\frac{2\\\\pi}{\\\\lambda}\\\\mathbf{v}\\\\cdot\\\\mathbf{x}\\\\right)U(\\\\mathbf{x})exp(+ik_x\\\\mathbf{x})',\n u'E^-(\\\\mathbf{v})=\\\\frac{1}{\\\\lambda}\\\\sum_{\\\\mathbf{x}}exp\\\\left(i\\\\frac{2\\\\pi}{\\\\lambda}\\\\mathbf{v}\\\\cdot\\\\mathbf{x}\\\\right)U(\\\\mathbf{x})exp(-ik_x\\\\mathbf{x})',\n u'I(\\\\mathbf{x})=|E^+|^{2}+|E^-|^{2}',\n u'\\\\mathbf{d}_{r,i}=\\\\mathbf{d}_{0}-2\\\\left(\\\\mathbf{d}_{0}\\\\cdot\\\\mathbf{n}_{i}\\\\right)\\\\mathbf{n}_{i}',\n u'z=-(x^2+y^2)/4f+f',\n u'\\\\begin{aligned}\\\\theta_{x,i,0}=cos^{-1}(x/2pf)\\\\hspace{-4.8mm}\\t\\\\\\\\\\\\theta_{y,i,0}=cos^{-1}(y/2pf)\\\\hspace{-4.2mm}\\t\\\\\\\\\\\\theta_{z,i,0}=cos^{-1}(1/p)\\t\\\\end{aligned}',\n u'\\\\mathbf{\\\\theta}_{i}=\\\\mathbf{\\\\theta}_{i,0}+\\\\mathbf{\\\\Delta\\\\theta_{i}}',\n u'\\\\mathbf{m}_{i}=\\\\mathbf{c}_{i}+\\\\alpha\\\\cost\\\\mathbf{e}_{1}+\\\\alpha\\\\cost\\\\mathbf{e}_{2}',\n u'\\\\mathbf{u}_{i}=\\\\mathbf{m}_{i}+\\\\mathbf{d}_{r}\\\\frac{(\\\\mathbf{q}-\\\\mathbf{m}_{i})\\\\cdot\\\\mathbf{n}_{d}}{\\\\mathbf{d}_{r}\\\\cdot\\\\mathbf{n}_{d}}',\n u'\\\\begin{aligned}E^+(\\\\mathbf{u}^+_{i})=A^+_iexp(ik\\\\mathbf{d}^+_{r,i}\\\\cdot\\\\mathbf{u}^+_{i})exp(ikL^+_{i})\\\\\\\\\\\\E^-(\\\\mathbf{u}^-_{i})=A^-_iexp(ik\\\\mathbf{d}^-_{r,i}\\\\cdot\\\\mathbf{u}^-_{i})exp(ikL^-_{i})\\\\end{aligned}',\n u'I(\\\\mathbf{x}_{d})=|\\\\sum_{i=1}^{M}E{_i}^+(\\\\mathbf{x}_{d})|^2+|\\\\sum_{i=1}^{M}E{_i}^-(\\\\mathbf{x}_{d})|^2',\n u'g_{n}=(f\\\\otimesh_{n})+q_{n}',\n u'\\\\{f,h_{n}\\\\}=\\\\min_{h_{n}\\\\geq0,f\\\\geq0}\\\\frac{1}{N^{2}}\\\\sum_{n=0}^{N}\\\\sum_{\\\\mathbfu}|{G_{n}}-\\\\tilde{F}\\\\tilde{H_{n}}|^{2}(\\\\mathbfu)',\n u'H_{i}=H_{i-1}\\\\odot\\\\frac{F_{i}^{T}G_{i}}{F_{i}^{T}(F_{i}H_{i-1})}',\n u'F_{i}=F_{i-1}\\\\odot\\\\frac{H_{i}^{T}G_{i}}{H_{i}^{T}(H_{i}F_{i-1})}',\n u'{\\\\frac{\\\\bar{\\\\rho}}{\\\\bar{\\\\rho}_{\\\\odot}}}\\\\simeq{\\\\left(\\\\frac{\\\\Deltau}{\\\\Deltau_{\\\\odot}}\\\\right)}^{2}',\n u'{\\\\frac{g}{g_{\\\\odot}}}\\\\simeq{\\\\left(\\\\frac{u_{\\\\rm{max}}}{u_{\\\\rm{max},\\\\\\\\odot}}\\\\right)}{\\\\left(\\\\frac{T_{\\\\rm{eff}}}{T_{\\\\rm{eff},\\\\\\\\odot}}\\\\right)}^{-1/2}.',\n u\"I(t)\\\\equiv\\\\int_0^t\\\\left(\\\\frac{T_{\\\\rm{eff}}(t')}{4500\\\\rm{K}}\\\\right)^{4/3}\\\\left(\\\\frac{M_{\\\\rm{env}}(t')}{M_{\\\\odot}}\\\\right)^{2/3}\\\\left(\\\\frac{R(t')}{R_{\\\\odot}}\\\\right)^8dt'.onumber\",\n u'\\\\begin{aligned}V_5&=V_5^L+\\\\chi_5V_2V_3\\\\,,\\\\\\\\V_6&=V_6^L+\\\\chi_{63}V_3^2+\\\\chi_{62}V_2^3\\\\,,\\\\\\\\V_7&=V_7^L+\\\\chi_7V_2^2V_3\\\\,.\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\chi_4&=\\\\frac{{\\\\langle}V_4(V_2^*)^2{\\\\rangle}}{{\\\\langle}|V_2|^4{\\\\rangle}}=\\\\frac{v_4\\\\{\\\\Psi_2\\\\}}{\\\\sqrt{{\\\\langle}|V_2|^4{\\\\rangle}}}\\\\\\\\\\\\chi_5&=\\\\frac{{\\\\langle}V_5V_2^*V_3^*{\\\\rangle}}{{\\\\langle}|V_2|^2|V_3|^2{\\\\rangle}}=\\\\frac{v_5\\\\{\\\\Psi_{23}\\\\}}{\\\\sqrt{{\\\\langle}|V_2|^2|V_3|^2{\\\\rangle}}}\\\\\\\\\\\\chi_{62}&=\\\\frac{{\\\\langle}V_6(V_2^*)^3{\\\\rangle}}{{\\\\langle}|V_2|^6{\\\\rangle}}=\\\\frac{v_6\\\\{\\\\Psi_2\\\\}}{\\\\sqrt{{\\\\langle}|V_2|^6{\\\\rangle}}}\\\\,,\\\\qquad\\\\chi_{63}=\\\\frac{{\\\\langle}V_6(V_3^*)^2{\\\\rangle}}{{\\\\langle}|V_3|^4{\\\\rangle}}=\\\\frac{v_6\\\\{\\\\Psi_3\\\\}}{\\\\sqrt{{\\\\langle}|V_3|^4{\\\\rangle}}}\\\\\\\\\\\\chi_7&=\\\\frac{{\\\\langle}V_7(V_2^*)^2V_3^*{\\\\rangle}}{{\\\\langle}|V_2|^4|V_3|^2{\\\\rangle}}=\\\\frac{v_7\\\\{\\\\Psi_{23}\\\\}}{\\\\sqrt{{\\\\langle}|V_2|^4|V_3|^2{\\\\rangle}}}.\\\\end{aligned}',\n u'I(T,\\\\omega)=\\\\prod\\\\limits_{i\\\\inI}I({\\\\rmTh}(\\\\mathcal{A}_i),\\\\min\\\\{|A_i|,\\\\omega\\\\}).',\n u\"\\\\Sigma=\\\\langle\\\\leq,\\\\leq',P_n,\\\\{c_n\\\\},\\\\{c'_n\\\\}\\\\rangle_{n\\\\in\\\\omega}\",\n u'I_\\\\infty(T,\\\\lambda)=\\\\left\\\\{\\\\begin{array}{rl}\\\\sum\\\\limits_{i=0}^{{\\\\rmmin}\\\\{|J|,\\\\lambda\\\\}}C^i_{|J|},&\\\\mbox{if}J\\\\mbox{and}\\\\lambda\\\\mbox{arefinite;}\\\\\\\\|J|,&\\\\mbox{if}J\\\\mbox{isinfiniteand}|J|>\\\\lambda;\\\\\\\\2^{|J|},&\\\\mbox{if}J\\\\mbox{isinfiniteand}|J|\\\\leq\\\\lambda.\\\\end{array}\\\\right.',\n u'\\\\varphi^{E,\\\\sigma}(x_1,\\\\ldots,x_n)=\\\\existsx\\\\left(\\\\bigwedge\\\\limits_{i=1}^n(E(x,x_i)\\\\wedge\\\\existsy(E(x,y)\\\\wedge\\\\sigma(y))\\\\wedge\\\\psi^{E,\\\\sigma}(x,x_1,\\\\ldots,x_n)\\\\right);',\n u'\\\\varphi^{E,\\\\sigma}(x_1,\\\\ldots,x_n)=\\\\forallx\\\\left(\\\\bigwedge\\\\limits_{i=1}^nE(x,x_i)\\\\wedge\\\\existsy(E(x,y)\\\\wedge\\\\sigma(y))\\\\to\\\\psi^{E,\\\\sigma}(x,x_1,\\\\ldots,x_n)\\\\right).',\n u\"{\\\\rmTH}(\\\\mathcal{A}_E)=\\\\bigcap\\\\limits_{\\\\mathcal{A}'\\\\equiv\\\\mathcal{A}_E}{\\\\rmTH}(\\\\mathcal{A}'),\",\n u\"{\\\\rmComLim}(\\\\mathcal{A}_{E},\\\\mathcal{B}_{E'})\\\\leq{\\\\rmmin}\\\\{e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{A}_{E})),e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{B}_{E'}))\\\\},\",\n u\"{\\\\rmmax}\\\\{e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{A}_{E})),e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{B}_{E'}))\\\\}\\\\leqe\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{C}_{E''})),\",\n u\"e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{A}_{E}))+e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{B}_{E'}))=e\\\\mbox{-}{\\\\rmSp}({\\\\rmTh}(\\\\mathcal{C}_{E''}))+{\\\\rmComLim}(\\\\mathcal{A}_{E},\\\\mathcal{B}_{E'}).\",\n u'\\\\models\\\\forallx,y\\\\:((x\\\\frac{1}{2}\\\\sigma\\\\omega_*\\\\left(\\\\tanh\\\\left(\\\\rho_*-\\\\frac{1}{\\\\omega_*}\\\\right)+1\\\\right).',\n u'\\t\\\\zeta=\\\\frac{2\\\\alphah_0}{\\\\sigma}-1.',\n u'\\\\omega_*=\\\\rho_*^{-1}+\\\\mathrm{arctanh}\\\\,(\\\\zeta)\\\\rho_*^{-2}+\\\\mathcal{O}(\\\\rho_*^{-3}).',\n u'\\\\begin{aligned}\\\\lambda_\\\\xi&=-\\\\frac{\\\\sigma}{2}(1-\\\\zeta^2)+\\\\mathcal{O}(\\\\rho_*^{-1}),\\\\\\\\\\\\lambda_\\\\omega&=-\\\\frac{\\\\sigma}{2}(1-\\\\zeta^2)+\\\\mathcal{O}(\\\\rho_*^{-1}),\\\\\\\\\\\\lambda_v&=\\\\mathcal{O}(\\\\sigma\\\\rho_*^{-2}).\\t\\\\end{aligned}',\n u'\\\\begin{aligned}\\td\\\\phi&=\\\\omegadt+d\\\\mathcal{W}_\\\\phi^*,\\\\\\\\\\td{\\\\boldsymbol{\\\\xi}}&={\\\\mathbf{v}}dt+\\\\lambda_\\\\xi\\\\boldsymbol{\\\\xi}dt+d{\\\\boldsymbol{\\\\mathcal{W}}}_{{\\\\boldsymbol{\\\\xi}}}^*,\\\\\\\\\\td{\\\\omega}&=\\\\lambda_\\\\omega(\\\\omega-\\\\omega_*)dt+d\\\\mathcal{W}_{\\\\omega}^*,\\\\\\\\\\td{\\\\mathbf{v}}&=\\\\lambda_v\\\\mathbf{v}dt+d{\\\\boldsymbol{\\\\mathcal{W}}}_{{\\\\mathbf{v}}}^*.\\t\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\text{E}[\\\\boldsymbol{\\\\mathcal{W^*}}\\\\boldsymbol{\\\\mathcal{W}^*}^T]&=\\\\beta^2t\\\\cdot\\\\text{Diag}\\\\left(\\\\frac{\\\\omega_*}{4\\\\pi},\\\\frac{\\\\omega_*}{2\\\\pi},\\\\frac{\\\\omega_*}{2\\\\pi},\\\\frac{\\\\omega_*^5}{4\\\\pi},\\\\frac{\\\\omega_*^5}{2\\\\pi},\\\\frac{\\\\omega_*^5}{2\\\\pi}\\\\right),onumber\\\\\\\\&\\\\equivt\\\\cdot\\\\text{Diag}\\\\left(\\\\beta_\\\\phi^2,\\\\beta_\\\\xi^2,\\\\beta_\\\\xi^2,\\\\beta_\\\\omega^2,\\\\beta_v^2,\\\\beta_v^2\\\\right),\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\text{Var}[\\\\omega(t)]&=-\\\\frac{\\\\beta_\\\\omega^2}{2\\\\lambda_\\\\omega}\\\\left(1-\\\\exp{2\\\\lambda_\\\\omegat}\\\\right)onumber\\\\\\\\&\\\\rightarrow-\\\\frac{\\\\beta^2_\\\\omega}{2\\\\lambda_\\\\omega},\\\\quad\\\\text{as}\\\\,\\\\,t\\\\rightarrow\\\\infty.\\\\end{aligned}',\n u'\\\\phi(t)=\\\\int_0^t\\\\omega(s)ds+\\\\mathcal{W}^*_\\\\phi,',\n u'\\\\text{Var}[\\\\phi(t)]\\\\rightarrow\\\\left(\\\\frac{\\\\beta_\\\\omega^2}{\\\\lambda_\\\\omega^2}+\\\\beta_\\\\phi^2\\\\right)t\\\\quad\\\\text{as}\\\\,\\\\,t\\\\rightarrow\\\\infty,',\n u'\\\\begin{aligned}\\\\Deltaf&=\\\\left(\\\\frac{\\\\beta_\\\\omega^2}{\\\\lambda_\\\\omega^2}+\\\\beta_\\\\phi^2\\\\right)={\\\\beta^2}\\\\left(\\\\frac{\\\\omega_*^5}{4\\\\pi\\\\lambda_\\\\omega^2}+\\\\frac{\\\\omega_*}{2\\\\pi}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}s_{{\\\\boldsymbol{\\\\xi}}}^2(t)&=-\\\\frac{\\\\beta_{\\\\xi}^2}{2\\\\lambda_{\\\\xi}}\\\\left(1-e^{2\\\\lambda_{\\\\xi}t}\\\\right)-\\\\frac{\\\\beta_v^2}{2\\\\left(\\\\lambda_{\\\\xi}-\\\\lambda_v\\\\right){}^2}onumber\\\\\\\\&\\\\quad\\\\times\\\\left(\\\\frac{1-e^{2\\\\lambda_{\\\\xi}t}}{\\\\lambda_{\\\\xi}}+\\\\frac{4\\\\left(1-e^{\\\\left(\\\\lambda_{\\\\xi}+\\\\lambda_v\\\\right)t}\\\\right)}{\\\\lambda_{\\\\xi}+\\\\lambda_v}+\\\\frac{1-e^{2\\\\lambda_vt}}{\\\\lambda_v}\\\\right)onumber\\\\\\\\&\\\\rightarrow-\\\\frac{1}{2}\\\\frac{\\\\beta_v^2}{\\\\lambda_\\\\xi^2\\\\lambda_v}-\\\\frac{\\\\beta_\\\\xi^2}{\\\\lambda_\\\\xi}\\\\quad\\\\text{as}\\\\,\\\\,t\\\\rightarrow\\\\infty.\\\\end{aligned}',\n u'\\\\|\\\\boldsymbol{\\\\xi}_\\\\text{NL}(t)-\\\\boldsymbol{\\\\xi}_\\\\text{L}(t)\\\\|=\\\\mathcal{O}(s^2_{\\\\xi}).',\n u'\\\\begin{aligned}&abla\\\\cdot\\\\epsilon_r^{-1}abla\\\\left(H_{zs}+H_{zi}\\\\right)+k_0^2\\\\mu_r\\\\left(H_{zs}+H_{zi}\\\\right)=0,~\\\\mathrm{in}~\\\\Omega\\\\\\\\&\\\\epsilon_r^{-1}ablaH_{zs}\\\\cdot\\\\mathbf{n}+jk_0\\\\sqrt{\\\\epsilon_r^{-1}\\\\mu_r}H_{zs}=0,~\\\\mathrm{on}~\\\\Gamma_{a}\\\\\\\\&H_{zs}\\\\left(\\\\mathbf{x}+\\\\mathbf{a}\\\\right)=H_{zs}\\\\left(\\\\mathbf{x}\\\\right)e^{-j\\\\mathbf{k}\\\\cdot\\\\mathbf{a}},~\\\\mathbf{n}\\\\left(\\\\mathbf{x}+\\\\mathbf{a}\\\\right)\\\\cdotablaH_{zs}\\\\left(\\\\mathbf{x}+\\\\mathbf{a}\\\\right)=-e^{-j\\\\mathbf{k}\\\\cdot\\\\mathbf{a}}\\\\mathbf{n}\\\\left(\\\\mathbf{x}\\\\right)\\\\cdotablaH_{zs}\\\\left(\\\\mathbf{x}\\\\right),\\\\\\\\&\\\\mathrm{for}~\\\\forall\\\\mathbf{x}\\\\in\\\\Gamma_{ps},~\\\\mathbf{x}+\\\\mathbf{a}\\\\in\\\\Gamma_{pd}\\\\end{aligned}',\n u'\\\\epsilon_{rm}=\\\\epsilon_{r\\\\infty}-{{\\\\omega_p^2}\\\\over{\\\\omega\\\\left(\\\\omega-j\\\\gamma_c\\\\right)}}',\n u'\\\\epsilon_{rd}\\\\left(\\\\omega\\\\right)=10^{\\\\log{\\\\epsilon_{rm}\\\\left(\\\\omega\\\\right)}-{{1-\\\\rho^3}\\\\over{1+\\\\rho^3}}\\\\left[\\\\log{\\\\epsilon_{rm}\\\\left(\\\\omega\\\\right)}-\\\\log{\\\\epsilon_{rf}\\\\left(\\\\omega\\\\right)}\\\\right]}',\n u'\\\\begin{aligned}P_i&=\\\\int_{\\\\Gamma_i}{1\\\\over2}\\\\mathrm{Re}\\\\left(\\\\mathbf{E}_i\\\\times\\\\mathbf{H}_i^*\\\\right)\\\\cdot\\\\mathbf{n}_i\\\\,\\\\mathrm{d}\\\\Gamma\\\\\\\\&=\\\\int_\\\\Omega{1\\\\over2}\\\\mathrm{Re}\\\\left(\\\\mathbf{E}_i\\\\times\\\\mathbf{H}_i^*\\\\right)\\\\cdot\\\\mathbf{n}_i~\\\\delta\\\\left(dist\\\\left(\\\\mathbf{x},\\\\Gamma_i\\\\right)\\\\right)\\\\mathrm{d}\\\\Omega\\\\\\\\\\\\end{aligned}',\n u'\\\\begin{aligned}P_o&=\\\\int_{\\\\Gamma_o}{1\\\\over2}\\\\mathrm{Re}\\\\left(\\\\mathbf{E}\\\\times\\\\mathbf{H}^*\\\\right)\\\\cdot\\\\mathbf{n}_o\\\\,\\\\mathrm{d}\\\\Gamma\\\\\\\\&=\\\\int_\\\\Omega{1\\\\over2}\\\\mathrm{Re}\\\\left(\\\\mathbf{E}\\\\times\\\\mathbf{H}^*\\\\right)\\\\cdot\\\\mathbf{n}_o~\\\\delta\\\\left(dist\\\\left(\\\\mathbf{x},\\\\Gamma_o\\\\right)\\\\right)\\\\mathrm{d}\\\\Omega\\\\end{aligned}',\n u'T_r={P_o}/{P_i}',\n u'\\\\max_{\\\\rho\\\\in\\\\left[0,1\\\\right]}\\\\left\\\\{\\\\min_{\\\\lambda\\\\in\\\\left[\\\\lambda_0-{\\\\theta\\\\over2},\\\\lambda_0+{\\\\theta\\\\over2}\\\\right]}T_r\\\\left(\\\\lambda\\\\right)\\\\right\\\\}',\n u'(\\\\forallf:[{\\\\mathbb{N}}]^{n}\\\\tok)(\\\\existsY)(Y\\\\mbox{isinfinite}\\\\wedge\\\\Psi(f,Y))',\n u'{\\\\mathsf{WKL_0}}\\\\vdash{\\\\forall}X({\\\\exists}Y\\\\Theta(X,Y)\\\\leftrightarrow{\\\\exists}Z(Z\\\\mbox{isinfinite}\\\\wedge\\\\Psi(X,Z))).',\n u'\\\\begin{aligned}\\\\Psi(X,Z)\\\\equiv{\\\\forall}F\\\\subseteq_{{\\\\mathrm{fin}}}Z(Feq\\\\emptyset\\\\to(&{\\\\exists}\\\\sigma\\\\in2^{\\\\maxF})({\\\\forall}n<|F|)({\\\\exists}m<\\\\maxF)\\\\theta(X{\\\\upharpoonright}m,\\\\sigma{\\\\upharpoonright}m,n,m)).\\\\end{aligned}',\n u'\\\\begin{aligned}T=\\\\{\\\\sigma\\\\in2^{<{\\\\mathbb{N}}}\\\\mid{\\\\forall}F\\\\subseteqZ\\\\cap[0,|\\\\sigma|]_{{\\\\mathbb{N}}}(Feq\\\\emptyset\\\\to({\\\\forall}n<|F|)({\\\\exists}m<\\\\maxF)\\\\theta(X{\\\\upharpoonright}m,\\\\sigma{\\\\upharpoonright}m,k,n,m))\\\\}.\\\\end{aligned}',\n u'\\\\Gamma=(\\\\forallf:[{\\\\mathbb{N}}]^{n}\\\\tok)(\\\\existsY)(Y\\\\mbox{isinfinite}\\\\wedge\\\\Psi(f,Y)).',\n u'(\\\\forallf:[{\\\\mathbb{N}}]^{n}\\\\tok)(\\\\existsY)(Y\\\\mbox{isinfinite}\\\\wedge\\\\Psi(f,Y))',\n u'{\\\\forall}i_{1}<\\\\dotsn_e)=\\\\mu_j(n_s0).',\n u'\\\\begin{aligned}\\\\resizebox{0.97\\\\hsize}{!}{\\\\hat{J}_{L}\\\\mbox{}\\\\mu_i(n_s>n_e,M_S<0)=\\\\mu_{i_J}(n_sn_e,M_S<0)=\\\\mu_{i_P}(n_s>n_e,M_S>0)}\\\\\\\\\\\\resizebox{0.97\\\\hsize}{!}{\\\\hat{P}_{L}\\\\hat{J}_{L}\\\\mbox{}\\\\mu_i(n_s>n_e,M_S<0)=\\\\mu_{i_{PJ}}(n_s0)}\\\\end{aligned}',\n u'(\\\\hat{J}_{L})_{i,j}=(-1)^{\\\\eta_J}\\\\delta_{i,i_J}\\\\qquad(\\\\hat{P}_{L})_{i,j}=(-1)^{\\\\eta_P}\\\\delta_{i,i_P}\\\\\\\\',\n u'(\\\\hat{P}_{L}\\\\hat{J}_{L})_{i,j}=(-1)^{\\\\eta_{PJ}}\\\\delta_{i,i_{PJ}}',\n u'{\\\\calP}(\\\\Gamma)=\\\\frac{1}{h}\\\\sum_i\\\\chi(\\\\Gamma,{\\\\cal{R}}_i){\\\\cal{\\\\hat{R}}}_i',\n u'\\\\tilde{H}_{2l+2}=S^{\\\\dagger}H_{2l+2}S',\n u'\\\\begin{aligned}H&=\\\\sum_{,\\\\sigma}t_0(\\\\hatc_{i,\\\\sigma}^\\\\dagger\\\\hatc_{j,\\\\sigma}^{}+\\\\mbox{H.C.})+\\\\sum_i\\\\epsilon_i\\\\hatn_i\\\\\\\\&+\\\\sum_i\\\\frac{U}{2}\\\\hatn_i(\\\\hatn_i-1)+\\\\sum_{i>j}V_{ij}(\\\\hatn_i-z_i)(\\\\hatn_j-z_j)\\\\end{aligned}',\n u'2M\\\\rightarrowP^++P^-',\n u'E_C(N)=E_{P^+}(N)+E_{P^-}(N)-2E_M(N)',\n u'\\\\logL_{\\\\rm5~GHz}=(0.45\\\\pm0.11)\\\\logL_{\\\\rm[O\\\\,III]}+(5.6\\\\pm0.9),',\n u'\\\\alpha',\n u'S\\\\,=\\\\,\\\\int{d^4x}\\\\sqrt{-g}\\\\left[\\\\frac{R}{16\\\\piG}+{\\\\calL}_m\\\\right]\\\\,,',\n u'V(\\\\phi)\\\\,=\\\\,\\\\mu^4e^{\\\\phi/f}\\\\,,',\n u\"{\\\\ddot\\\\phi}+3H{\\\\dot\\\\phi}+V'(\\\\phi)\\\\,=\\\\,\\\\frac{\\\\lambda}{8f}{\\\\vec{E}_{a}}\\\\cdot{\\\\vec{B}_{a}}\\\\,,\",\n u\"V'(\\\\phi)\\\\,\\\\simeq\\\\,\\\\frac{\\\\lambda}{8f}{\\\\vec{E}_{a}}\\\\cdot{\\\\vec{B}_{a}}\\\\,,\",\n u'D^{ab}_\\\\alphaF^{b\\\\beta\\\\alpha}-\\\\frac{4\\\\lambda}{f}\\\\epsilon^{\\\\muu\\\\alpha\\\\beta}\\\\partial_\\\\alpha^{ab}(\\\\phiF_{\\\\muu}^b)=0\\\\,,',\n u'D_\\\\alpha^{ab}\\\\equiv\\\\delta^{ab}abla_\\\\alpha+gf^{acb}A^{c}_\\\\alpha',\n u'abla_{i}E^{i}_{a}=-\\\\frac{\\\\lambda}{f}\\\\vec{abla}\\\\phiabla_{j}B^{i}_{a},',\n u'abla\\\\timesE^{i}_{a}=-\\\\frac{\\\\partial}{\\\\partialt}B^{i}_{a}\\\\,',\n u'\\\\frac{\\\\partial}{\\\\partialt}E^{i}_{a}+2HE^{i}_{a}\\\\,=\\\\,0',\n u'\\\\frac{\\\\partial}{\\\\partialt}B^{i}_{a}+2HB^{i}_{a}\\\\,=\\\\,0\\\\,.',\n u'\\\\frac{\\\\partial}{\\\\partialt}E^{i}_{a}+2HE^{i}_{a}\\\\,=\\\\,-\\\\frac{\\\\lambda}{f}[\\\\dot{\\\\phi}B^{i}_{a}]',\n u'H(t_m)\\\\,\\\\simeq\\\\,m\\\\,',\n u'E(t),B(t)\\\\,\\\\sim\\\\,a(t)^{-3/2}\\\\,',\n u'{\\\\dotE}^{i}\\\\,+\\\\,2HE^{i}\\\\,=\\\\,S(t)^{i}\\\\,,',\n u'S^{i}(t)\\\\,=\\\\,\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|a^2(t_i)a^{-2}(t)B(t_i)^{i}\\\\,,',\n u\"E(t)\\\\,=\\\\,\\\\int_{t_i}^tdt'\\\\frac{t'}{t}S(t')+E(t_i)\\\\frac{t_i}{t}\\\\,,\",\n u'E(t)\\\\,=\\\\,E(t_i)\\\\frac{t_i}{t}\\\\bigl[1+\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|\\\\frac{B(t_i)}{E(t_i}(t-t_i)\\\\bigr]\\\\,',\n u'E(t)\\\\,=\\\\,E(t_m)\\\\bigl(\\\\frac{a(t_m)}{a(t)}\\\\bigr)^{3/2}\\\\bigl[1+\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|\\\\frac{B(t_m)}{E(t_m)}(t-t_m)\\\\bigr]\\\\,',\n u\"E(t)\\\\,=\\\\,\\\\int_{t_{eq}}^tdt'\\\\bigl(\\\\frac{a(t')}{a(t)}\\\\bigr)^{3/2}S(t')+E(t_{eq})\\\\bigl(\\\\frac{a(t_{eq)}}{a(t)}\\\\bigr)^{3/2}\\\\,,\",\n u'S(t)\\\\,=\\\\,\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|a^{-3/2}(t)B(t_{eq})\\\\,',\n u'E(t)\\\\,\\\\simeq\\\\,E(t_i)\\\\bigl(\\\\frac{a(t_{i})}{a(t_m)}\\\\bigr)^2\\\\bigl(\\\\frac{a(t_m)}{a(t)}\\\\bigr)^{3/2}\\\\bigl[1+\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|\\\\frac{B(t_i)}{E(t_i)}t\\\\bigr]\\\\,.',\n u't_c\\\\,=\\\\,\\\\frac{f}{\\\\lambda}\\\\frac{E(t_i)}{B(t_i)}\\\\frac{1}{|{\\\\dot\\\\phi}|}\\\\,.',\n u'{\\\\vec{E}}\\\\cdot{\\\\vec{B}}\\\\,\\\\sim\\\\,a(t)^{-4}',\n u'{\\\\vec{E}}\\\\cdot{\\\\vec{B}}\\\\,\\\\sim\\\\,a(t)^{-3}',\n u'{\\\\vec{E}}\\\\cdot{\\\\vec{B}}\\\\,\\\\sim\\\\,a(t)^{-3}t',\n u\"{\\\\ddot\\\\phi}+3H{\\\\dot\\\\phi}+V'(\\\\phi)\\\\,=\\\\,\\\\frac{\\\\lambda}{8f}{\\\\vec{E}}\\\\cdot{\\\\vec{B}}\\\\,,\",\n u\"V'(\\\\phi)\\\\,=\\\\,\\\\frac{\\\\lambda}{8f}{\\\\vec{E}}\\\\cdot{\\\\vec{B}}\\\\,\",\n u'V(\\\\phi)\\\\,=\\\\mu^4e^{\\\\phi/f},',\n u'V(\\\\phi)\\\\,=\\\\,\\\\frac{\\\\lambda}{8}{\\\\vec{E}}\\\\cdot{\\\\vec{B}}\\\\,',\n u'\\\\phi(t)\\\\,\\\\simeq\\\\,f{\\\\rmlog}(\\\\kappat^{-1})',\n u'\\\\kappa\\\\,=\\\\,\\\\frac{\\\\lambda}{8}\\\\frac{({\\\\vec{E}}\\\\cdot{\\\\vec{B}})(t_i)}{\\\\mu^4}(\\\\frac{a(t_i)}{a(t_m)})^4\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|\\\\frac{B(t_i)}{E(t_i)}t_0^2\\\\,.',\n u'{\\\\dot\\\\phi}^2(t)\\\\,\\\\simeq\\\\,\\\\frac{f^2}{t^2}',\n u'{\\\\ddot\\\\phi}\\\\,\\\\simeq\\\\,\\\\frac{f}{t^2}\\\\,.',\n u'f\\\\,\\\\ll\\\\,m_{pl}\\\\,.',\n u'\\\\Omega_{\\\\phi}(t_0)\\\\,\\\\simeq\\\\,\\\\frac{\\\\lambda}{8}\\\\frac{({\\\\vec{E}}\\\\cdot{\\\\vec{B}})(t_i)}{\\\\rho_r(t_i)}\\\\bigl(\\\\frac{a(t_{eq})}{a(t_m)}\\\\bigr)\\\\frac{\\\\lambda}{f}|{\\\\dot\\\\phi}|\\\\frac{B(t_i)}{E(t_i)}t_0\\\\,',\n u'\\\\frac{({\\\\vec{E}}\\\\cdot{\\\\vec{B}})(t_i)}{\\\\rho_r(t_i)}\\\\,\\\\sim\\\\,\\\\frac{n_B}{s}(t_i),\\\\,',\n u'\\\\bigl(\\\\frac{a(t_{eq})}{a(t_m)}\\\\bigr)\\\\,\\\\sim\\\\,\\\\bigl[\\\\frac{m}{T_{eq}}\\\\frac{m_{pl}}{T_{eq}}\\\\bigr]^{1/2}',\n u'\\\\lambda\\\\,\\\\sim\\\\,10^{-4}',\n u'\\\\partial_{\\\\mu}\\\\phi\\\\cdotJ_{5,B-L}^{\\\\mu}',\n u'\\\\phi(F\\\\wedgeF+\\\\frac{1}{f}\\\\sum_{j}m_{j}{\\\\bar{\\\\psi}}_{j}\\\\gamma_{5}\\\\psi_{j})\\\\,,',\n u'S\\\\,=\\\\,e^{-\\\\varphi}\\\\,+\\\\,ia\\\\,.',\n u'{\\\\tildeS}\\\\,=\\\\,e^{\\\\rho}\\\\,+\\\\,i{\\\\tildea}\\\\,.',\n u'\\\\[x=y\\\\iffx-y<\\\\text{eachfinitequantity}.\\\\]',\n u'|\\\\partial\\\\rho|_{\\\\omega_{0}}^{2},\\\\|\\\\sqrt{-1}\\\\partial\\\\bar{\\\\partial}\\\\rho|_{\\\\omega_{0}}\\\\leq\\\\frac{C}{r^{2}}',\n u'e^{-\\\\frac{\\\\delta}{t}}Q\\\\leq\\\\frac{C}{r^{2}}',\n u'\\\\frac{\\\\partial}{\\\\partialt}\\\\int_M\\\\omega_{\\\\varphi_{\\\\varepsilon}(t)}\\\\wedge\\\\eta=\\\\int_{M}\\\\frac{\\\\partial\\\\omega_{\\\\varphi_{\\\\varepsilon}(t)}}{\\\\partialt}\\\\wedge\\\\eta+\\\\int_M\\\\omega_{\\\\varphi_{\\\\varepsilon}(t)}\\\\wedge\\\\frac{\\\\partial\\\\eta}{\\\\partialt}',\n u't^2(R(g_{\\\\varepsilon,j}(t))-tr_{g_{\\\\varepsilon,j}(t)}\\\\theta_{\\\\varepsilon})\\\\geq-C',\n u'R(g_{\\\\varepsilon,j}(t))-tr_{g_{\\\\varepsilon,j}(t)}\\\\theta_{\\\\varepsilon}\\\\geq-C',\n u'R(g_{\\\\varepsilon}(t))-tr_{g_{\\\\varepsilon}(t)}\\\\theta_{\\\\varepsilon}\\\\geq-C',\n u'|a_{\\\\varepsilon}(t)|\\\\leqC',\n u'-Ric(\\\\omega_{\\\\varepsilon}(t))+\\\\beta\\\\omega_{\\\\varepsilon}(t)+\\\\theta_{\\\\varepsilon}=\\\\sqrt{-1}\\\\partial\\\\bar{\\\\partial}u_{\\\\varepsilon}(t)',\n u'\\\\|\\\\dot{\\\\psi}_{\\\\varepsilon}(t)\\\\|_{C^{0}}\\\\leqC',\n u\"(1-\\\\delta)\\\\|x-x'\\\\|_2^2\\\\leq\\\\|\\\\mathcal{P}x-\\\\mathcal{P}x'\\\\|_2^2\\\\leq(1+\\\\delta)\\\\|x-x'\\\\|_2^2.\",\n u\"S(\\\\mathcal{X})=\\\\left\\\\{\\\\dfrac{x-x'}{\\\\|x-x'\\\\|_2},x,x'\\\\in\\\\mathcal{X},xeqx'\\\\right\\\\}\",\n u'\\\\begin{aligned}(1-\\\\delta)\\\\|v_i\\\\|_2^2\\\\leq\\\\|\\\\psiv_i\\\\|_2^2&\\\\leq(1+\\\\delta)\\\\|v_i\\\\|_2^2\\\\\\\\|\\\\|\\\\psiv_i\\\\|_2^2-\\\\|v_i\\\\|_2^2|&\\\\leq\\\\delta\\\\\\\\|\\\\|\\\\psiv_i\\\\|_2^2-1|&\\\\leq\\\\delta\\\\\\\\|v_i^TPv_i-1|&\\\\leq\\\\delta\\\\end{aligned}',\n u'\\\\begin{aligned}&\\\\underset{P}{\\\\text{minimize}}&&\\\\operatorname{rank}(P)\\\\\\\\&\\\\text{subjectto}&&\\\\|\\\\mathcal{A}(P)-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\\\\\&&&P\\\\succeq0\\\\end{aligned}',\n u'\\\\begin{aligned}&\\\\underset{P}{\\\\text{minimize}}&&\\\\|P\\\\|_*\\\\\\\\&\\\\text{subjectto}&&\\\\|\\\\mathcal{A}(P)-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\\\\\&&&P\\\\succeq0\\\\end{aligned}',\n u'\\\\psi=\\\\Gamma_M^{1/2}U_M^T',\n u'\\\\begin{aligned}&\\\\underset{P,L,q}{\\\\text{minimize}}&&\\\\|P\\\\|_*\\\\\\\\&\\\\text{subjectto}&&P=L\\\\\\\\&&&\\\\mathcal{A}(L)=q,\\\\\\\\&&&\\\\|q-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\\\\\&&&P\\\\succeq0\\\\end{aligned}',\n u'L_A(P,L,q;\\\\Gamma,\\\\omega)=\\\\|P\\\\|_*+\\\\frac{\\\\beta_1}{2}\\\\|P-L-\\\\Gamma\\\\|_F^2+\\\\frac{\\\\beta_2}{2}\\\\|\\\\mathcal{A}(L)-q-\\\\omega\\\\|_2^2',\n u'\\\\begin{aligned}&\\\\underset{P,L,q,\\\\Gamma,\\\\omega}{\\\\text{minimize}}&&L_A(P,L,q,\\\\Gamma,\\\\omega)\\\\\\\\&\\\\text{subjectto}&&\\\\|q-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\\\\\&&&P\\\\succeq0\\\\end{aligned}',\n u'\\\\begin{aligned}&\\\\underset{W,H}{\\\\text{minimize}}&&\\\\|WH-V\\\\|_F^2\\\\\\\\&\\\\text{subjectto}&&W_{ij}\\\\geq0,H_{ij}\\\\geq0,\\\\forall~i,j\\\\\\\\\\\\end{aligned}',\n u'\\\\begin{aligned}&\\\\underset{P,\\\\psi}{\\\\text{minimize}}&&\\\\frac{1}{2}\\\\|P-\\\\psi^T\\\\psi\\\\|_F^2\\\\\\\\&\\\\text{subjectto}&&\\\\|\\\\mathcal{A}(P)-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\end{aligned}',\n u'\\\\begin{aligned}&\\\\underset{P,X,Y,q}{\\\\text{minimize}}&&\\\\frac{1}{2}\\\\|P-XY\\\\|_F^2\\\\\\\\&\\\\text{subjectto}&&\\\\mathcal{A}(P)=q\\\\\\\\&&&Y=X^T\\\\\\\\&&&\\\\|q-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\end{aligned}',\n u'\\\\begin{multline}L_A(X,Y,q,P)=\\\\frac{1}{2}\\\\|P-XY\\\\|_F^2+\\\\Gamma\\\\cdot(\\\\mathcal{A}(P)-q)+\\\\Pi\\\\cdot(Y-X^T)\\\\\\\\+\\\\frac{\\\\beta_1}{2}\\\\|\\\\mathcal{A}(P)-q\\\\|_2^2+\\\\frac{\\\\beta_2}{2}\\\\|Y-X^T\\\\|_F^2+\\\\iota_{\\\\{q:\\\\|q-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\}}\\\\end{multline}',\n u'\\\\iota_{\\\\{q:\\\\|q-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\}}=\\\\begin{cases}0&\\\\text{if}\\\\|q-1_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\\\\\\\\\infty&\\\\text{otherwise}\\\\end{cases}',\n u'q_{k+1}\\\\leftarrow\\\\underset{q}{\\\\arg\\\\min}~\\\\Gamma\\\\cdot(\\\\mathcal{A}(P)-q)+\\\\frac{\\\\beta_1}{2}\\\\|\\\\mathcal{A}(P)-q\\\\|_2^2+\\\\iota_{\\\\{q:\\\\|q-\\\\textbf{1}_S\\\\|_\\\\infty\\\\leq\\\\delta\\\\}}',\n u'q_{k+1}=1_S+\\\\operatorname{sign}(z)\\\\cdot\\\\min(|z|,\\\\delta)',\n u'P_{k+1}\\\\leftarrow\\\\underset{P}{\\\\arg\\\\min}~\\\\frac{1}{2}\\\\|P-XY\\\\|_F^2+\\\\Gamma\\\\cdot(\\\\mathcal{A}(P)-q)+\\\\frac{\\\\beta_1}{2}\\\\|\\\\mathcal{A}(P)-q\\\\|_2^2',\n u'(P-XY)+\\\\sum_{j=1}^s\\\\Gamma_jv_jv_j^T+\\\\beta_1\\\\mathcal{A}^*(\\\\mathcal{A}(P)-q)=0',\n u'X_{k+1}\\\\leftarrow\\\\underset{X}{\\\\arg\\\\min}~\\\\frac{1}{2}\\\\|P-XY\\\\|_F^2+\\\\Pi\\\\cdot(Y-X^T)+\\\\frac{\\\\beta_2}{2}\\\\|Y-X^T\\\\|_F^2',\n u'Y_{k+1}\\\\leftarrow\\\\underset{Y}{\\\\arg\\\\min}~\\\\frac{1}{2}\\\\|P-XY\\\\|_F^2+\\\\Pi\\\\cdot(Y-X^T)+\\\\frac{\\\\beta_2}{2}\\\\|Y-X^T\\\\|_F^2',\n u'\\\\begin{aligned}\\\\Gamma_{k+1}\\\\leftarrow&\\\\Gamma_k+\\\\eta\\\\beta_1(\\\\mathcal{A}(P_{k+1})-q_{k+1})\\\\\\\\\\\\Pi_{k+1}\\\\leftarrow&\\\\Pi_k+\\\\eta\\\\beta_2(Y_{k+1}-X_{k+1}^T)\\\\end{aligned}',\n u'\\\\underset{\\\\psi}{\\\\text{minimize}}\\\\|\\\\mathcal{A}(\\\\psi^T\\\\psi)-1_S\\\\|_\\\\infty',\n u'\\\\begin{aligned}\\\\underset{q,\\\\psi}{\\\\text{minimize}}&\\\\|q-1_s\\\\|_\\\\infty\\\\\\\\\\\\text{subjectto}&q=\\\\mathcal{A}(\\\\psi^T\\\\psi)\\\\end{aligned}',\n u'{\\\\operatorname{prox}}_f(x)=\\\\underset{u}{\\\\arg\\\\min}(f(u)+\\\\frac{1}{2}\\\\|u-x\\\\|_2^2)',\n u'x={\\\\operatorname{prox}}_f(x)+{\\\\operatorname{prox}}_{f^*}(x)',\n u'L_A(\\\\psi,q;\\\\omega)=\\\\|q-1_S\\\\|_\\\\infty+\\\\frac{\\\\beta}{2}\\\\|\\\\mathcal{A}(\\\\psi^T\\\\psi)-q-\\\\omega\\\\|_2^2',\n u'\\\\psi_{k+1}\\\\leftarrow\\\\underset{\\\\psi}{\\\\arg\\\\min}~\\\\frac{\\\\beta}{2}\\\\|\\\\mathcal{A}(\\\\psi^T\\\\psi)-q-\\\\omega\\\\|_2^2',\n u'q_{k+1}\\\\leftarrow\\\\underset{q}{\\\\arg\\\\min}~\\\\|q-1_S\\\\|_\\\\infty+\\\\frac{\\\\beta}{2}\\\\|\\\\mathcal{A}(\\\\psi^T\\\\psi)-q-\\\\omega\\\\|_2^2',\n u'\\\\begin{aligned}X&=\\\\frac{1}{\\\\beta}(\\\\beta\\\\tau-{\\\\operatorname{prox}}_{(\\\\|X\\\\|_1\\\\leq1)}(\\\\beta\\\\tau))\\\\\\\\q&=\\\\frac{1}{\\\\beta}(\\\\beta\\\\tau-{\\\\operatorname{prox}}_{(\\\\|X\\\\|_1\\\\leq1)}(\\\\beta\\\\tau))+1_S\\\\end{aligned}',\n u'\\\\omega_{k+1}\\\\leftarrow\\\\omega_k-\\\\beta(\\\\mathcal{A}(\\\\psi^T_{k+1}\\\\psi)-q_{k+1})',\n u'\\\\widehat{S}\\\\leftarrow\\\\{v_i\\\\inS_0:|v_i^T\\\\widehat{\\\\psi}^T\\\\widehat{\\\\psi}v_i-1|\\\\geq\\\\delta\\\\}',\n u'\\\\widehat{S}\\\\leftarrow\\\\widehat{S}\\\\bigcup\\\\{v_i\\\\inS_1:|v_i^T\\\\widehat{\\\\psi}^T\\\\widehat{\\\\psi}v_i-1|\\\\geq\\\\delta\\\\}',\n u'\\\\begin{aligned}&012,015,023,034,045,124^{\\\\prime},153^{\\\\prime},13^{\\\\prime}4^{\\\\prime},235^{\\\\prime},24^{\\\\prime}5^{\\\\prime},341^{\\\\prime},onumber\\\\\\\\&31^{\\\\prime}5^{\\\\prime},452^{\\\\prime},41^{\\\\prime}2^{\\\\prime},52^{\\\\prime}3^{\\\\prime},0^{\\\\prime}1^{\\\\prime}2^{\\\\prime},0^{\\\\prime}1^{\\\\prime}5^{\\\\prime},0^{\\\\prime}2^{\\\\prime}3^{\\\\prime},0^{\\\\prime}3^{\\\\prime}4^{\\\\prime},0^{\\\\prime}4^{\\\\prime}5^{\\\\prime}.\\\\end{aligned}',\n u'\\\\begin{array}{cl}G=1,~R_\\\\oplus=1,~m_\\\\oplus=1\\\\end{array}',\n u'a,\\\\;e,\\\\;{i},\\\\;\\\\omega\\\\;,\\\\Omega,\\\\;M,',\n u'\\\\theta=\\\\lambda_2-\\\\lambda_1=M_2-M_1+\\\\omega_2-\\\\omega_1,',\n u'{\\\\bfe}={\\\\bfv}{{{\\\\bf\\\\times}}}({\\\\bfr}{{{\\\\bf\\\\times}}}{\\\\bfv})/m_\\\\oplus-{\\\\bfr}/r,',\n u'\\\\widetilde{{\\\\bfe}}={\\\\bfe}_2-{\\\\bfe}_1,',\n u'\\\\dot{{\\\\bfx}}={\\\\bfw},\\\\\\\\\\\\\\\\dot{{\\\\bfw}}=-m_\\\\oplus({\\\\bfx}/r^3-3{\\\\bfr}\\\\cdot{\\\\bfx}\\\\:{\\\\bfr}/r^5),',\n u'{\\\\bfx}=\\\\sum{\\\\frac{\\\\partial{{\\\\bfr}}}{\\\\partial{q_k}}}\\\\deltaq_k\\\\\\\\{\\\\rmand}\\\\{\\\\bfw}=\\\\sum{\\\\frac{\\\\partial{{\\\\bfv}}}{\\\\partial{q_k}}}\\\\deltaq_k.',\n u'{\\\\bfx}_a=2{\\\\bfr}-3\\\\:t\\\\:{\\\\bfv},',\n u'a(2e\\\\sin(M)+\\\\theta,1-e\\\\cos(M)),',\n u'(\\\\Deltax,\\\\Deltay)=a(2e\\\\sin(M)+\\\\theta,-e\\\\cos(M))+\\\\vecO(\\\\varepsilon^2),',\n u'\\\\Delta^2=a^2((\\\\theta+2e\\\\sin(M))^2+e^2\\\\cos^2(M))+O(\\\\varepsilon^2).',\n u'H=K_1+K_2-R_1-R_2-R_{12},',\n u'K_u={\\\\bfp}_u^2/2-\\\\frac{m_\\\\oplus}{r_u},',\n u'R=\\\\sum_{n=1}^{N_x}\\\\sum_{m=0}^n\\\\frac{P_{n}^m(\\\\cos(\\\\theta))}{r^{n+1}}(C_n^m\\\\cos(m\\\\psi)+S_n^m\\\\sin(m\\\\psi))+R_{ls}.',\n u'R_u=\\\\frac{m_\\\\oplus}{r_u}(\\\\frac{J_2R_\\\\oplus^2}{2r_u^2}(1-3(\\\\frac{z_u}{r_u})^2),',\n u'\\\\Delta=|{\\\\bfr}_2-{\\\\bfr}_1|.',\n u'\\\\langleK_u-R_u\\\\rangle=-\\\\frac{m_\\\\oplus}{2a_u}-\\\\frac{{J_2R_\\\\oplus^2}m_\\\\oplus\\\\left(2-3\\\\sin^2(i_u)\\\\right)}{4a_u^3\\\\left(1-e_u^2\\\\right)^{3/2}.}',\n u'R_{12}(\\\\Delta)={\\\\epsilon}\\\\Delta,',\n u'\\\\Delta^2\\\\approxa^2({\\\\widetildee}^2\\\\cos(w)^2+(\\\\theta+2{\\\\widetildee}\\\\sin(w))^2)',\n u'{\\\\widetildee}=|{\\\\bfe}_2-{\\\\bfe}_1|,\\\\\\\\\\\\w=M+{\\\\rmconstant}.',\n u'R=\\\\sum_{u=1}^2\\\\frac{{J_2}m_\\\\oplusR_\\\\oplus^2\\\\left(2-3\\\\sin^2(i_u)\\\\right)}{4a_u^3\\\\left(1-e_u^2\\\\right)^{3/2}}+{\\\\epsilon}<\\\\Delta>.',\n u'\\\\dot\\\\theta=\\\\dot\\\\lambda_2-\\\\dot\\\\lambda_1=\\\\dotM_2+\\\\dot\\\\omega_2-\\\\dotM_1-\\\\dot\\\\omega_1.',\n u'\\\\dot\\\\theta\\\\approxn_2-n_1\\\\approx-\\\\frac32n\\\\alpha',\n u'\\\\ddot\\\\theta\\\\approx-\\\\frac{3}{a^2}({\\\\frac{\\\\partial{R}}{\\\\partial{M_2}}}-{\\\\frac{\\\\partial{R}}{\\\\partial{M_1}}})=-\\\\frac{6}{a^2}{\\\\frac{\\\\partial{R}}{\\\\partial{\\\\theta}}},',\n u'\\\\langleR_{12}\\\\rangle=\\\\frac{1}{2\\\\pi}\\\\int_0^{2\\\\pi}R_{12}(\\\\Delta(w))\\\\:dw',\n u'\\\\langleR_{12}\\\\rangle=R_{12}^{(0)}+R_{12}^{(2)}\\\\theta^2/2+..,',\n u'\\\\ddot\\\\theta=-\\\\frac{6}{a^2}{\\\\frac{\\\\partial{R_{12}}}{\\\\partial{\\\\theta}}}\\\\approx\\\\frac{-1.711{\\\\epsilon}}{a{\\\\widetildee}}\\\\theta,',\n u'\\\\langleR\\\\rangle={\\\\epsilon}_n\\\\frac{1}{2\\\\pi}\\\\int_0^{2\\\\pi}\\\\Delta^n(w)\\\\:dw.',\n u'\\\\sigma=G_0\\\\gamma\\\\,,',\n u'\\\\vec{f}^{\\\\rmel}_{ij}=\\\\begin{cases}-k(\\\\delta_{ij})\\\\,\\\\delta_{ij}\\\\,\\\\hat{r}_{ij}\\\\,,&\\\\delta_{ij}>0\\\\\\\\{\\\\vec0},&\\\\delta_{ij}<0.\\\\end{cases}',\n u'k=k_0\\\\,\\\\delta^{\\\\alpha-2}\\\\,.',\n u'\\\\vec{f}^{\\\\rmvisc}_{ij}=-\\\\tau_0\\\\,k(\\\\delta_{ij})\\\\,\\\\Delta{\\\\vecv}^{\\\\,c}_{ij}\\\\,,',\n u'\\\\sigma_{\\\\alpha\\\\beta}=\\\\frac{1}{2V}\\\\sum_{ij}f_{ij,\\\\alpha}r_{ij,\\\\beta}-\\\\frac{1}{V}\\\\sum_im_iv_{i,\\\\alpha}v_{i,\\\\beta}\\\\,,',\n u'\\\\frac{p}{k}\\\\sim\\\\Delta\\\\phi\\\\sim\\\\Deltaz^2\\\\,.',\n u'G_0/k\\\\sim(p/k)^{\\\\mu}\\\\,,',\n u'\\\\gamma_{\\\\rmcc}^{(1)}\\\\sim\\\\frac{(p/k)^{1/2}}{N}\\\\,.',\n u'\\\\gamma(t)=\\\\left\\\\lbrace\\\\begin{array}{cl}0&t<0\\\\\\\\\\\\gamma_0&t\\\\ge0\\\\,.\\\\end{array}\\\\right.',\n u'G_r(t,\\\\gamma_0)\\\\equiv\\\\frac{\\\\sigma(t,\\\\gamma_0)}{\\\\gamma_0}\\\\,.',\n u'{\\\\tau^*}\\\\sim\\\\left(\\\\frac{k}{p}\\\\right)^\\\\lambda\\\\tau_0\\\\,\\\\,\\\\,{\\\\rmas}\\\\,\\\\,\\\\,N\\\\rightarrow\\\\infty\\\\,.',\n u'\\\\frac{G_r(t)}{k}\\\\sim\\\\left\\\\lbrace\\\\begin{array}{cc}\\\\left({\\\\tau_0}/{t}\\\\right)^{\\\\theta}&1\\\\llt/\\\\tau_0\\\\ll({k}/p)^\\\\lambda\\\\\\\\(p/k)^{\\\\mu}&({k}/p)^\\\\lambda\\\\llt/\\\\tau_0\\\\,.\\\\end{array}\\\\right.',\n u'\\\\gamma(t)=\\\\left\\\\lbrace\\\\begin{array}{cl}0&t<0\\\\\\\\\\\\dot\\\\gamma_0t&t\\\\ge0\\\\end{array}\\\\right.',\n u'\\\\gamma^\\\\dag\\\\sim\\\\frac{p}{k}\\\\simp^{1/(\\\\alpha-1)}\\\\,,',\n u'n_{\\\\rmcc}(\\\\gamma)\\\\simeq\\\\frac{1}{N}\\\\left(\\\\frac{\\\\gamma}{\\\\gamma_{\\\\rmcc}^{(1)}}\\\\right)\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,{\\\\rmas}\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\gamma\\\\rightarrow0\\\\,.',\n u'n_{\\\\rmcc}^\\\\dag\\\\equivn_{\\\\rmcc}(\\\\gamma^\\\\dag)\\\\sim\\\\Deltaz\\\\,.',\n u\"\\\\frac{\\\\sigma}{\\\\gamma}=\\\\frac{1}{t}\\\\,\\\\int_0^{t}G_r(t')\\\\,{\\\\rmd}t'\\\\,.\",\n u'\\\\frac{\\\\sigma}{\\\\gamma}\\\\simk\\\\left(\\\\frac{\\\\tau_0}{t}\\\\right)^{\\\\theta},\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\,\\\\tau_0p_{\\\\mathrm{bot}}\\\\mathrm{.}\\\\end{cases}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}\\\\tau_{\\\\mathrm{rad}}(p)=\\\\begin{cases}\\\\tau_{\\\\mathrm{rad,top}}\\\\hspace{2cm}pp_{\\\\mathrm{bot}}\\\\mathrm{,}\\t\\\\end{cases}',\n u'\\\\alpha=\\\\frac{\\\\mathrm{ln}(\\\\tau_{\\\\mathrm{rad,top}}/\\\\tau_{\\\\mathrm{rad,bot}})}{\\\\mathrm{ln}(p_{\\\\mathrm{rad,top}}/p_{\\\\mathrm{bot}})}\\\\mathrm{.}',\n u'\\\\mathcal{F}_{\\\\mathrm{drag}}=-k_v(p){\\\\bfv}\\\\mathrm{,}',\n u'k_v(p)=\\\\max\\\\left[\\\\tau_{\\\\rmdrag}^{-1},\\\\tau_{\\\\mathrm{drag,bot}}^{-1}\\\\frac{(p-p_{\\\\mathrm{drag,top}})}{(p_{\\\\mathrm{drag,bot}}-p_{\\\\mathrm{drag,top}})}\\\\right]',\n u'U_{\\\\mathrm{rms}}(p)=\\\\sqrt{\\\\frac{\\\\int(u^2+v^2)dA}{A}}\\\\mathrm{.}',\n u'{\\\\bfv}\\\\cdotabla{\\\\bfv}+w^{\\\\star}\\\\frac{\\\\partial{\\\\bfv}}{\\\\partialz^{\\\\star}}+f{\\\\bfk}\\\\times{\\\\bfv}=-abla\\\\Phi-\\\\frac{{\\\\bfv}}{\\\\tau_{\\\\mathrm{drag}}}\\\\mathrm{,}',\n u'\\\\frac{\\\\partial\\\\Phi}{\\\\partialz^{\\\\star}}=RT\\\\mathrm{,}',\n u'abla\\\\cdot{\\\\bfv}+e^{z^\\\\star}\\\\frac{\\\\partial(e^{-z^\\\\star}w^{\\\\star})}{\\\\partialz^{\\\\star}}=0\\\\mathrm{,}',\n u'{\\\\bfv}\\\\cdotablaT+w^{\\\\star}\\\\frac{N^2H^2}{R}=\\\\frac{T_{\\\\mathrm{eq}}-T}{\\\\tau_{\\\\mathrm{rad}}}\\\\mathrm{.}',\n u'z^{\\\\star}\\\\equiv-\\\\mathrm{ln}\\\\frac{p}{p_{\\\\mathrm{00}}}\\\\mathrm{,}',\n u'\\\\frac{\\\\mathcal{U}}{\\\\mathcal{L}}\\\\sim\\\\max\\\\left[w^\\\\star,\\\\frac{w^\\\\star}{\\\\Deltaz^\\\\star}\\\\right].',\n u'\\\\frac{\\\\mathcal{U}}{\\\\mathcal{L}}\\\\sim\\\\frac{\\\\mathcal{W}}{H}.',\n u'\\\\left|T_{\\\\mathrm{eq}}-T\\\\right|_{\\\\mathrm{global}}\\\\equiv\\\\left|T_{\\\\mathrm{eq}}-T\\\\right|_{\\\\mathrm{day}}+\\\\left|T_{\\\\mathrm{eq}}-T\\\\right|_{\\\\mathrm{night}}\\\\mathrm{,}',\n u'\\\\DeltaT_{\\\\mathrm{eq}}-\\\\DeltaT\\\\sim\\\\left|T_{\\\\mathrm{eq}}-T\\\\right|_{\\\\mathrm{global}}\\\\mathrm{.}',\n u'\\\\frac{\\\\DeltaT_{\\\\mathrm{eq}}-\\\\DeltaT}{\\\\tau_{\\\\mathrm{rad}}}\\\\sim\\\\mathrm{max}\\\\left[\\\\frac{\\\\mathcal{U}\\\\DeltaT}{\\\\mathcal{L}}\\\\mathrm{,}\\\\frac{\\\\mathcal{W}N^2H}{R}\\\\right]\\\\mathrm{.}',\n u'\\\\frac{\\\\DeltaT_{\\\\mathrm{eq}}-\\\\DeltaT}{\\\\tau_{\\\\mathrm{rad}}}\\\\sim\\\\frac{\\\\mathcal{W}N^2H}{R}.',\n u\"\\\\Delta\\\\Phi\\\\approxR\\\\int_p^{p_{\\\\mathrm{bot}}}\\\\DeltaTd\\\\mathrm{ln}p'\\\\mathrm{.}\",\n u'\\\\DeltaT=\\\\DeltaT_{\\\\mathrm{top}}\\\\frac{\\\\mathrm{ln}(p/p_{\\\\mathrm{bot}})}{\\\\mathrm{ln}(p_{\\\\mathrm{eq,top}}/p_{\\\\mathrm{bot}})}\\\\mathrm{.}',\n u'\\\\Delta\\\\Phi\\\\approxR\\\\DeltaT\\\\mathrm{ln}\\\\left(\\\\frac{p_{\\\\mathrm{bot}}}{p}\\\\right)\\\\mathrm{.}',\n u'abla\\\\Phi\\\\sim\\\\mathrm{max}\\\\left[\\\\frac{\\\\mathcal{U}^2}{\\\\mathcal{L}}\\\\mathrm{,}\\\\frac{\\\\mathcal{U}\\\\mathcal{W}}{H}\\\\mathrm{,}f\\\\mathcal{U}\\\\mathrm{,}\\\\frac{\\\\mathcal{U}}{\\\\tau_{\\\\mathrm{drag}}}\\\\right]\\\\mathrm{.}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}\\\\mathcal{U}(p)\\\\sim\\\\begin{cases}\\\\frac{R\\\\DeltaT(p)\\\\Delta\\\\mathrm{ln}p\\\\\\\\tau_{\\\\mathrm{drag}}(p)}{\\\\mathcal{L}}\\\\hspace{0.8cm}\\\\mathrm{Drag}\\\\\\\\\\\\frac{R\\\\DeltaT(p)\\\\Delta\\\\mathrm{ln}p}{\\\\mathcal{L}f}\\\\hspace{2.cm}\\\\mathrm{Coriolis}\\\\\\\\\\\\sqrt{R\\\\DeltaT(p)\\\\Delta\\\\mathrm{ln}p}\\\\hspace{1.8cm}\\\\mathrm{Advection}\\\\mathrm{,}\\\\end{cases}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}\\\\mathcal{W}(p)\\\\sim\\\\begin{cases}\\\\frac{R\\\\DeltaT(p)H(p)\\\\Delta\\\\mathrm{ln}p\\\\\\\\tau_{\\\\mathrm{drag}}(p)}{\\\\mathcal{L}^2}\\\\hspace{0.8cm}\\\\mathrm{Drag}\\\\\\\\\\\\frac{R\\\\DeltaT(p)H(p)\\\\Delta\\\\mathrm{ln}p}{\\\\mathcal{L}^2f}\\\\hspace{2.cm}\\\\mathrm{Coriolis}\\\\\\\\{H(p)\\\\over\\\\mathcal{L}}\\\\sqrt{R\\\\DeltaT(p)\\\\Delta\\\\mathrm{ln}p}\\\\hspace{1.7cm}\\\\mathrm{Advection}\\\\mathrm{.}\\\\end{cases}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}\\\\frac{\\\\DeltaT(p)}{\\\\DeltaT_{\\\\mathrm{eq}}(p)}\\\\sim\\t\\\\begin{cases}\\\\left(1+\\\\frac{\\\\tau_{\\\\mathrm{rad}}(p)\\\\tau_{\\\\mathrm{drag}}(p)}{\\\\tau_{\\\\mathrm{wave}}^2(p)}\\\\Delta\\\\mathrm{ln}p\\\\right)^{-1}\\t\\\\hspace{.0cm}\\\\mathrm{Drag}\\\\\\\\\\\\left(1+\\\\frac{\\\\tau_{\\\\mathrm{rad}}(p)}{f\\\\tau_{\\\\mathrm{wave}}^2(p)}\\\\Delta\\\\mathrm{ln}p\\\\right)^{-1}\\\\hspace{0.7cm}\\\\mathrm{Coriolis}\\\\\\\\\\\\frac{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}-\\\\sqrt{\\\\gamma(p)}}{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}+\\\\sqrt{\\\\gamma(p)}}\\\\hspace{.3cm}\\\\mathrm{Advection}\\\\mathrm{,}\\\\end{cases}',\n u'\\\\begin{aligned}\\\\everymath=\\\\expandafter{\\\\displaystyle}\\\\mathcal{W}\\\\sim\\t\\\\begin{cases}\\\\frac{RH(p)}{\\\\mathcal{L}^2}\\\\frac{\\\\tau_{\\\\mathrm{wave}}^2(p)}{\\\\tau_{\\\\mathrm{rad}}(p)}\\\\DeltaT_{\\\\mathrm{eq}}(p)\\\\\\\\\\\\times\\\\left[1-\\\\left(1+\\\\frac{\\\\tau_{\\\\mathrm{rad}}(p)\\\\tau_{\\\\mathrm{drag}}(p)}{\\\\tau_{\\\\mathrm{wave}}^2(p)}\\\\Delta\\\\mathrm{ln}p\\\\right)^{-1}\\\\right]\\t\\\\hspace{.0cm}\\\\mathrm{Drag}\\\\\\\\\\\\\\\\\\\\frac{RH(p)}{\\\\mathcal{L}^2}\\\\frac{\\\\tau_{\\\\mathrm{wave}}^2(p)}{\\\\tau_{\\\\mathrm{rad}}(p)}\\\\DeltaT_{\\\\mathrm{eq}}(p)\\\\\\\\\\\\times\\\\left[1-\\\\left(1+\\\\frac{\\\\tau_{\\\\mathrm{rad}}(p)}{f\\\\tau_{\\\\mathrm{wave}}^2(p)}\\\\Delta\\\\mathrm{ln}p\\\\right)^{-1}\\\\right]\\\\hspace{0.7cm}\\\\mathrm{Coriolis}\\\\\\\\\\\\\\\\\\\\frac{RH(p)}{\\\\mathcal{L}^2}\\\\frac{\\\\tau_{\\\\mathrm{wave}}^2(p)}{\\\\tau_{\\\\mathrm{rad}}(p)}\\\\DeltaT_{\\\\mathrm{eq}}(p)\\\\\\\\\\\\times\\\\left[1-\\\\frac{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}-\\\\sqrt{\\\\gamma(p)}}{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}+\\\\sqrt{\\\\gamma(p)}}\\\\right]\\\\hspace{.3cm}\\\\mathrm{Advection}\\\\mathrm{.}\\\\end{cases}\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\tau_{\\\\mathrm{adv}}(p)=&\\\\frac{\\\\mathcal{L}^2\\\\tau_{\\\\mathrm{rad}}(p)}{R\\\\tau^2_{\\\\mathrm{wave}}(p)\\\\DeltaT_{\\\\mathrm{eq}}(p)}\\\\\\\\&\\\\times\\\\left[1-\\\\frac{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}-\\\\sqrt{\\\\gamma(p)}}{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}+\\\\sqrt{\\\\gamma(p)}}\\\\right]^{-1}\\\\mathrm{.}\\\\end{aligned}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}A(p)\\\\sim\\\\begin{cases}\\\\left(1+\\\\frac{\\\\tau_{\\\\mathrm{rad}}(p)\\\\tau_{\\\\mathrm{drag}}(p)}{\\\\tau_{\\\\mathrm{wave}}^2(p)}\\\\Delta\\\\mathrm{ln}p\\\\right)^{-1}\\\\hspace{0.05cm}\\\\tau_{\\\\mathrm{drag}}f^{-1}\\\\mathrm{.}\\\\end{cases}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}A_{\\\\mathrm{eq}}(p)\\\\sim\\\\begin{cases}\\\\\\\\\\\\left(1+\\\\frac{\\\\tau_{\\\\mathrm{rad}}(p)\\\\tau_{\\\\mathrm{drag}}(p)}{\\\\tau_{\\\\mathrm{wave}}^2(p)}\\\\Delta\\\\mathrm{ln}p\\\\right)^{-1}\\\\hspace{-0.3cm}\\\\tau_{\\\\mathrm{drag}}(p)<\\\\tau_{\\\\mathrm{adv}}(p)\\\\\\\\\\\\\\\\\\\\frac{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}-\\\\sqrt{\\\\gamma(p)}}{\\\\sqrt{\\\\gamma(p)+4\\\\DeltaT_{\\\\mathrm{eq}}(p)}+\\\\sqrt{\\\\gamma(p)}}\\\\hspace{0cm}\\\\tau_{\\\\mathrm{drag}}(p)>\\\\tau_{\\\\mathrm{adv}}(p)\\\\mathrm{,}\\\\end{cases}',\n u'\\\\everymath=\\\\expandafter{\\\\displaystyle}\\\\tau_{\\\\mathrm{wave}}(p)\\\\sim\\\\begin{cases}\\\\sqrt{\\\\tau_{\\\\mathrm{drag}}(p)\\\\tau_{\\\\mathrm{rad}}(p)\\\\Delta\\\\mathrm{ln}p}\\\\hspace{0.5cm}\\\\tau_{\\\\mathrm{drag}}(p)f^{-1}\\\\mathrm{.}\\\\end{cases}',\n u'\\\\tau_{\\\\mathrm{vert}}\\\\sim\\\\frac{\\\\DeltaTR}{\\\\mathcal{W}N^2H}\\\\mathrm{.}',\n u'\\\\tau_{\\\\mathrm{vert}}\\\\sim\\\\frac{\\\\tau^2_{\\\\mathrm{wave}}}{\\\\tau_{\\\\mathrm{drag}}\\\\Delta\\\\mathrm{ln}p}\\\\mathrm{.}',\n u'\\\\tau_{\\\\mathrm{rad}}\\\\sim\\\\frac{\\\\tau^2_{\\\\mathrm{wave}}}{\\\\tau_{\\\\mathrm{drag}}\\\\Delta\\\\mathrm{ln}p}',\n u'\\\\tau_{\\\\mathrm{vert}}\\\\sim\\\\tau_{\\\\mathrm{rad}}\\\\sim\\\\frac{f\\\\tau^2_{\\\\mathrm{wave}}}{\\\\Delta\\\\mathrm{ln}p}\\\\mathrm{.}',\n u'A(\\\\phi,p)=\\\\left\\\\{\\\\frac{\\\\int_{0}^{2\\\\pi}\\\\left[T(\\\\lambda,\\\\phi,p)-\\\\bar{T}(\\\\phi,p)\\\\right]^2d\\\\lambda}{\\\\int_{0}^{2\\\\pi}\\\\left[T_{\\\\mathrm{eq}}(\\\\lambda,\\\\phi,p)-\\\\bar{T}(\\\\phi,p)\\\\right]^2d\\\\lambda}\\t\\\\right\\\\}^{1/2}\\\\mathrm{.}',\n u'A(p)=\\\\frac{3}{2\\\\pi}\\\\int_{-\\\\pi/3}^{\\\\pi/3}A(\\\\phi,p)d\\\\phi{\\\\mathrm{.}}',\n u'W_{\\\\mathrm{rms}}(p)=\\\\sqrt{\\\\frac{\\\\intw^2dA}{A}}\\\\mathrm{,}',\n u'\\\\frac{E_v}{E_h}\\\\approx\\\\frac{W_{\\\\mathrm{rms}}N^2H}{R}\\\\left(\\\\frac{U_{\\\\mathrm{rms}}A\\\\DeltaT_{\\\\mathrm{eq}}}{\\\\mathcal{L}}\\\\right)^{-1}\\\\mathrm{.}',\n u'A_{\\\\mathrm{obs,ll}}=\\\\frac{F_{\\\\mathrm{day}}^{1/4}-F_{\\\\mathrm{night,max}}^{1/4}}{F_{\\\\mathrm{day}}^{1/4}}\\\\mathrm{.}\\\\vspace{0.01cm}',\n u'R=\\\\frac{\\\\theta_{int}}{t_{int}}=\\\\frac{d\\\\alpha}{dt}\\\\cos\\\\,\\\\delta_0',\n u'\\\\alpha_{i}=\\\\alpha_{0}+\\\\frac{R}{\\\\cos\\\\,\\\\delta_{0}}\\\\cdot(t_{i}-t_{0})',\n u'T_{A}=T_{sys}\\\\cdot\\\\frac{ON-OFF}{OFF}',\n u'\\\\small(i-\\\\gamma)\\\\psi_{t}=[-\\\\frac{1}{2}(\\\\partial_{x}^2+\\\\partial_{y}^2)+V(x,y)-\\\\mu+p|\\\\psi|^2-\\\\OmegaL_{z}]\\\\psi\\\\eqno{(1)}',\n u'\\\\largeJ_{i}=\\\\sum\\\\limits_{i=1}^N\\\\sum\\\\limits_{j=1}^cu_{ij}^m{||x_i-v_j||}^2\\\\\\\\',\n u'\\\\begin{aligned}\\\\large\\\\sum\\\\limits_{j=1}^cu_{ij}=1,1\\\\leqi\\\\leqn\\\\\\\\0<\\\\sum\\\\limits_{i=1}^nu_{ij}0,m}\\\\frac{\\\\Phi_{lm}}{R\\\\sqrt{l(l+1)}}Y_{lm}\\\\,,\\\\\\\\\\\\Theta&=\\\\displaystyle\\\\sum_{l>0,m}\\\\frac{\\\\Theta_{lm}}{R\\\\sqrt{l(l+1)}}Y_{lm}\\\\,.\\\\\\\\\\\\end{array}',\n u'G\\\\left\\\\{\\\\begin{aligned}\\\\theta&\\\\rightarrow\\\\pi-\\\\theta\\\\\\\\\\\\phi&\\\\rightarrow\\\\phi+\\\\pi\\\\left(1+\\\\frac{1}{n}\\\\right)\\\\end{aligned}\\\\right.',\n u'Y_{lm}(G\\\\Omega)=(-1)^lY_{lm}(\\\\Omega)e^{im\\\\pi/n}\\\\,.',\n u'\\\\begin{array}{lll}\\\\mathcal{L}&=&\\\\intR^2d\\\\Omega\\\\\\\\Phi\\\\;\\\\hspace{0.01em}_1\\\\bar\\\\eth_0\\\\eth\\\\left(\\\\Box-\\\\frac{\\\\hspace{0.01em}_1\\\\bar\\\\eth_0\\\\eth}{R^2}\\\\right)\\\\Phi\\\\i\\\\+\\\\Phi_{2,-2}\\\\left(\\\\Box-\\\\frac{6}{R^2}\\\\right)\\\\Phi_{2,2}+\\\\Phi_{2,2}\\\\left(\\\\Box-\\\\frac{6}{R^2}\\\\right)\\\\Phi_{2,-2}\\\\\\\\&=&\\\\Phi_{2,2}^\\\\dagger\\\\left(\\\\Box-\\\\frac{6}{R^2}\\\\right)\\\\Phi_{2,2}+\\\\Phi_{2,2}\\\\left(\\\\Box-\\\\frac{6}{R^2}\\\\right)\\\\Phi_{2,2}^\\\\dagger\\\\=\\\\2\\\\Phi_{2,2}^\\\\dagger\\\\left(\\\\Box-\\\\frac{6}{R^2}\\\\right)\\\\Phi_{2,2}\\\\mathrm{\\\\\\\\}\\\\\\\\&=&\\\\varphi^\\\\dagger\\\\left(\\\\Box-\\\\frac{6}{R^2}\\\\right)\\\\varphi\\\\\\\\\\\\end{array}',\n u'{\\\\calL}_H^{6D}=(D_M\\\\phi)^\\\\dagger(D^M\\\\phi)+\\\\mu_{6D}^2\\\\phi^\\\\dagger\\\\phi-\\\\lambda_{6D}(\\\\phi^\\\\dagger\\\\phi)^2',\n u'\\\\phi=\\\\frac{1}{\\\\sqrt{2}}\\\\left(\\\\begin{array}{c}\\\\phi_1+i\\\\phi_2\\\\\\\\v_{6D}+H+i\\\\phi_3\\\\end{array}\\\\right)\\\\,.',\n u'\\\\phi(x^\\\\mu,\\\\Omega)=\\\\sum\\\\frac{Y_{lm}(\\\\Omega)}{R}\\\\phi_{lm}(x^\\\\mu)\\\\,.',\n u'v_{6D}=\\\\sqrt{\\\\frac{\\\\mu^2_{6D}}{2\\\\lambda_{6D}}}=\\\\frac{v_{4D}}{\\\\sqrt{4\\\\pi}R}\\\\,.',\n u'\\\\begin{aligned}{\\\\calL}_{gf}=&-\\\\frac{1}{\\\\xi}tr(f^af_a)\\\\\\\\f^a=&\\\\eta^{\\\\muu}\\\\partial_\\\\muA_u^a+\\\\frac{\\\\xi}{R^2\\\\sin\\\\theta}\\\\partial_\\\\theta\\\\left(\\\\sin\\\\thetaA_\\\\theta^a\\\\right)+\\\\frac{\\\\xi}{R^2\\\\sin\\\\theta}\\\\partial_\\\\phiA_\\\\phi^a\\\\\\\\&-\\\\xigF_i^a\\\\phi_i\\\\end{aligned}',\n u'M^2_{gf}=\\\\frac{\\\\xi}{R^2}\\\\begin{pmatrix}g^2\\\\zeta^2&g\\\\zeta\\\\sqrt{l\\\\left(l+1\\\\right)}\\\\\\\\g\\\\zeta\\\\sqrt{l\\\\left(l+1\\\\right)}&l\\\\left(l+1\\\\right)\\\\end{pmatrix}',\n u'\\\\begin{pmatrix}1\\\\\\\\-\\\\frac{g\\\\zeta}{\\\\sqrt{l\\\\left(l+1\\\\right)}}\\\\end{pmatrix}\\\\,.',\n u'{\\\\calL}_{m_{EW}}=-\\\\frac{1}{8}g^2_{4D}v_{4D}^2\\\\left[\\\\bar\\\\varphi_W^+\\\\varphi_W^-+\\\\bar\\\\varphi_W^-\\\\varphi_W^++\\\\frac{\\\\bar\\\\varphi_Z\\\\varphi_Z}{cos^2\\\\theta_W}\\\\right]',\n u'm_{\\\\varphi_W^+}^2=m_{\\\\varphi_W^-}^2=\\\\frac{6}{R^2}+m_W^2\\\\,,\\\\quadm_{\\\\varphi_Z}^2=\\\\frac{6}{R^2}+m_Z^2\\\\,,\\\\quadm_{\\\\varphi_A}^2=\\\\frac{6}{R^2}\\\\,.',\n u'{\\\\calL}_{m_\\\\varphi}=\\\\frac{-1}{4}\\\\left(f_\\\\text{bulk}(\\\\theta)F_{MN}F^{MN}+2f_\\\\text{loc}\\\\delta(\\\\theta)F_{\\\\theta\\\\phi}F^{\\\\theta\\\\phi}\\\\right)',\n u'\\\\frac{1}{R}>\\\\unit{1.6}{\\\\tera\\\\electronvolt}\\\\,,\\\\qquadM_{l=2}>{\\\\unit{{3.9}}{\\\\tera\\\\electronvolt}}\\\\,,',\n u'{\\\\frac{\\\\partial{n}}{\\\\partial{t}}}+3Hn=-\\\\left<{\\\\sigmav}\\\\right>\\\\left(n^2-n_{eq}^2\\\\right)',\n u'n_{eq}=g\\\\left(\\\\frac{mT}{2\\\\pi}\\\\right)^{\\\\frac{3}{2}}e^{-m/T}',\n u'\\\\Omega_{DM}h^2\\\\approx\\\\frac{1.04\\\\times10^9}{M_{pl}}\\\\frac{m}{T_f\\\\sqrt{g_*}}\\\\frac{1}{a+3mb/T_f}\\\\,.',\n u'{\\\\frac{\\\\partial{N}}{\\\\partial{t}}}+3HN=-\\\\left<{\\\\sigma_{eff}v}\\\\right>\\\\left(N^2-N_{eq}^2\\\\right)\\\\,,',\n u'\\\\sigma_{eff}=\\\\sum_i^K\\\\sum_j^K\\\\sigma_{ij}\\\\frac{g_ig_j}{g_{eff}^2}(1+\\\\Delta_i)^{3/2}(1+\\\\Delta_j)^{3/2}e^{-x(\\\\Delta_i+\\\\Delta_j)}\\\\,.',\n u'\\\\sum_i^Kg_i(1+\\\\Delta_i)^{3/2}e^{-x\\\\Delta_i}\\\\,.',\n u'{\\\\calL}_{SSV}=\\\\frac{g}{2}\\\\epsilon_{abc}A_\\\\mu^a\\\\left(\\\\eth\\\\Phi^b\\\\partial_\\\\mu\\\\bar\\\\eth\\\\Phi^c+\\\\bar\\\\eth\\\\Phi^b\\\\partial\\\\eth\\\\Phi^c\\\\right).',\n u'\\\\begin{array}{rl}{\\\\calL}^{\\\\sc{4D}}_{\\\\sc{SSV}_1}=\\\\left.g_{4D}\\\\frac{1}{2i}\\\\right[&\\\\left(\\\\partial_\\\\mu\\\\bar\\\\varphi^+_W\\\\varphi^-_W-\\\\partial_\\\\mu\\\\bar\\\\varphi^-_W\\\\varphi^+_W\\\\right)W^{3\\\\mu}_{\\\\sc{SM}}\\\\\\\\+&\\\\left(\\\\partial_\\\\mu\\\\varphi^+_W\\\\bar\\\\varphi^-_W-\\\\partial_\\\\mu\\\\varphi^-_W\\\\bar\\\\varphi^+_W\\\\right)W^{3\\\\mu}_{\\\\sc{SM}}\\\\\\\\-&\\\\left(W^{+\\\\mu}_{\\\\sc{SM}}\\\\varphi_W^--W^{-\\\\mu}_{\\\\sc{SM}}\\\\varphi_W^+\\\\right)\\\\partial_\\\\mu\\\\bar\\\\varphi_{W^3}\\\\\\\\-&\\\\left(W^{+\\\\mu}_{\\\\sc{SM}}\\\\bar\\\\varphi_W^--W^{-\\\\mu}_{\\\\sc{SM}}\\\\bar\\\\varphi_W^+\\\\right)\\\\partial_\\\\mu\\\\varphi_{W^3}\\\\\\\\+&\\\\left(W^{+\\\\mu}_{\\\\sc{SM}}\\\\partial_\\\\mu\\\\varphi_W^--W^{-\\\\mu}_{\\\\sc{SM}}\\\\partial_\\\\mu\\\\varphi_W^+\\\\right)\\\\bar\\\\varphi_{W^3}\\\\\\\\+&\\\\left.\\\\left(W^{+\\\\mu}_{\\\\sc{SM}}\\\\partial_\\\\mu\\\\bar\\\\varphi_W^--W^{-\\\\mu}_{\\\\sc{SM}}\\\\partial_\\\\mu\\\\bar\\\\varphi_W^+\\\\right)\\\\varphi_{W^3}\\\\right]\\\\\\\\\\\\end{array}',\n u'\\\\begin{array}{rl}{\\\\calL}^{\\\\sc{4D}}_{\\\\sc{SSV}_2}=\\\\left.g_{4D}\\\\frac{\\\\sqrt{5}}{14i}\\\\right[&\\\\left(\\\\partial_\\\\mu\\\\bar\\\\varphi^+_W\\\\varphi^-_W-\\\\partial_\\\\mu\\\\bar\\\\varphi^-_W\\\\varphi^+_W\\\\right)W^{3\\\\mu}_{(2,0)}\\\\\\\\+&\\\\left(\\\\partial_\\\\mu\\\\varphi^+_W\\\\bar\\\\varphi^-_W-\\\\partial_\\\\mu\\\\varphi^-_W\\\\bar\\\\varphi^+_W\\\\right)W^{3\\\\mu}_{(2,0)}\\\\\\\\-&\\\\left(W^{+\\\\mu}_{(2,0)}\\\\varphi_W^--W^{-\\\\mu}_{(2,0)}\\\\varphi_W^+\\\\right)\\\\partial_\\\\mu\\\\bar\\\\varphi_{W^3}\\\\\\\\-&\\\\left(W^{+\\\\mu}_{(2,0)}\\\\bar\\\\varphi_W^--W^{-\\\\mu}_{(2,0)}\\\\bar\\\\varphi_W^+\\\\right)\\\\partial_\\\\mu\\\\varphi_{W^3}\\\\\\\\+&\\\\left(W^{+\\\\mu}_{(2,0)}\\\\partial_\\\\mu\\\\varphi_W^--W^{-\\\\mu}_{(2,0)}\\\\partial_\\\\mu\\\\varphi_W^+\\\\right)\\\\bar\\\\varphi_{W^3}\\\\\\\\+&\\\\left.\\\\left(W^{+\\\\mu}_{(2,0)}\\\\partial_\\\\mu\\\\bar\\\\varphi_W^--W^{-\\\\mu}_{(2,0)}\\\\partial_\\\\mu\\\\bar\\\\varphi_W^+\\\\right)\\\\varphi_{W^3}\\\\right]\\\\\\\\\\\\end{array}',\n u'{\\\\calL}_{SSVV}=\\\\frac{1}{2}g^2\\\\left[A_\\\\mu^aA_a^\\\\mu\\\\eth\\\\Phi^b\\\\bar\\\\eth\\\\Phi_b-A^a_\\\\mu\\\\eth\\\\Phi_aA_b^\\\\mu\\\\bar\\\\eth\\\\Phi^b\\\\right],',\n u'{\\\\calL}_{V_sV_sWW}=g^2_{4D}W^+_{SM\\\\mu}W_{-\\\\mu}^{SM}\\\\bar\\\\varphi_{A^3}\\\\varphi_{A^3}',\n u'{\\\\calL}_{V_sW_sVW}=-\\\\frac{1}{2}g_{4D}A^3_\\\\mu\\\\left[\\\\varphi^3\\\\left(W^{+\\\\mu}\\\\bar\\\\varphi_W^-+W^{-\\\\mu}\\\\bar\\\\varphi_W^+\\\\right)+\\\\bar\\\\varphi^3\\\\left(W^{+\\\\mu}\\\\varphi_W^-+W^{-\\\\mu}\\\\varphi_W^+\\\\right)\\\\right]',\n u'\\\\begin{array}{rl}{\\\\calL}_{W_sW_sWW}&=\\\\frac{1}{2}g^2_{4D}\\\\left[W_+^{SM\\\\mu}W_{-\\\\mu}^{SM}\\\\left(\\\\varphi_W^+\\\\bar\\\\varphi_W^-+\\\\varphi_W^-\\\\bar\\\\varphi_W^+\\\\right)-W^{SM}_{+\\\\mu}W^{SM\\\\mu}_{+}\\\\bar\\\\varphi_W^-\\\\varphi_W^-\\\\right.\\\\\\\\&\\\\left.\\\\phantom{aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}-W^{SM}_{-\\\\mu}W^{SM\\\\mu}_{-}\\\\bar\\\\varphi_W^+\\\\varphi_W^+\\\\right]\\\\end{array}',\n u'{\\\\calL}_{W_sW_sVV}=\\\\frac{1}{2}g^2_{4D}A^3_{SM\\\\mu}A^{SM\\\\mu_3}\\\\left[\\\\bar\\\\varphi_W^+\\\\varphi_W^-+\\\\bar\\\\varphi_W^-\\\\varphi_W^+\\\\right]',\n u'{\\\\calL}_{SSHH}=-\\\\frac{1}{8}H^\\\\daggerH\\\\bar\\\\eth\\\\phi^a\\\\eth\\\\phi',\n u'{\\\\calL}_{SSHH}^{4D}=-\\\\frac{1}{8}g^2_{4D}hh\\\\left[\\\\bar\\\\varphi_W^+\\\\varphi_W^-+\\\\bar\\\\varphi_W^-\\\\varphi_W^++\\\\frac{\\\\bar\\\\varphi_Z\\\\varphi_Z}{\\\\cos^2\\\\theta_W}\\\\right]',\n u'{\\\\calL}_{SSH}^{4D}=-\\\\frac{1}{4}g_{4D}^2vh\\\\left[\\\\bar\\\\varphi_W^+\\\\varphi_W^-+\\\\bar\\\\varphi_W^-\\\\varphi_W^++\\\\frac{\\\\bar\\\\varphi_Z\\\\varphi_Z}{cos^2\\\\theta_W}\\\\right]\\\\\\\\',\n u'tfidf-c=\\\\frac{tf(t_{k},d_{j})\\\\timeslog\\\\left(N/df(t_{k})\\\\right)}{\\\\sqrt{{\\\\displaystyle\\\\sum_{t\\\\ind_{j}}(tf(t_{k},d_{j})\\\\timeslog\\\\left(N/df(t_{k})\\\\right)^{2})}}}',\n u'sim(a,b)=\\\\frac{v}{|N(a)||N(b)|}\\\\sum_{i\\\\inN(a),,j\\\\inN(b)}sim(i,j)',\n u'Auth(w_{t})=(1-\\\\alpha)*e_{t}+\\\\alpha\\\\sum_{s\\\\inT(w_{t})}Hub(s)',\n u'Hub(w_{s})=(1-\\\\gamma)*e_{s}+\\\\alpha\\\\sum_{t\\\\inT(w_{s})}Auth(t)',\n u'\\\\tau=\\\\frac{N_{i}+1/2*N_{j}}{N}',\n u'S_{D}=\\\\sum_{i}^{n}p(S_{i})*W_{i}',\n u'\\\\frac{1}{min(i,N-i+1)}',\n u'tf-isf=\\\\sum_{t\\\\ins}tf(t,s)*log\\\\frac{N}{sf(t)}',\n u'\\\\sum_{i=1}^{5}\\\\lambda_{i}F_{i}',\n u'PW(w)=\\\\sum_{i\\\\inP}log_{2}(\\\\frac{p(w,i)}{p(w).p(i)})-\\\\sum_{i\\\\inN}log_{2}(\\\\frac{p(w,i)}{p(w).p(i)})',\n u'\\\\{-,-\\\\}:{\\\\mathcal{O}}_{X}\\\\times{\\\\mathcal{O}}_{X}\\\\longrightarrow{\\\\mathcal{O}}_{X}',\n u'\\\\{F,G\\\\}_{U}(m)=\\\\langled_{m}F\\\\wedged_{m}G,\\\\pi_{m}\\\\rangle',\n u'd(\\\\pi_{x}\\\\circ\\\\phi)|_{u}\\\\oplusd(\\\\pi_{y}\\\\circ\\\\phi)|_{u}:T_{u}U={\\\\mathbb{R}}^{n}\\\\longrightarrowT_{x}X\\\\oplusT_{y}Y',\n u'\\\\partial(X\\\\times_{f,Z,g}Y)\\\\cong(\\\\partialX\\\\times_{f\\\\circi_{X},Z,g}Y){\\\\scriptstyle\\\\coprod}(X\\\\times_{f,Z,g\\\\circi_{Y}}\\\\partialY).',\n u'p^{U}_{W}=p^{V}_{W}\\\\circp^{U}_{V}',\n u'\\\\{-,-\\\\}={\\\\mathcal{O}}\\\\times{\\\\mathcal{O}}\\\\longrightarrow{\\\\mathcal{O}}',\n u'f_{\\\\#}(U):{\\\\mathcal{O}}_{Y}(U)=C^{\\\\infty}(U)\\\\rightarrow{\\\\mathcal{O}}_{X}(f^{-1}(U))=C^{\\\\infty}(f^{-1}(U))',\n u'\\\\{f,gs\\\\}=\\\\{f,g\\\\}s+g.\\\\{f,s\\\\}',\n u'\\\\[\\\\theta=f_1\\\\frac{\\\\partial}{\\\\partialz_1}+\\\\ldots+f_n\\\\frac{\\\\partial}{\\\\partialz_n}\\\\]',\n u'\\\\[h\\\\cdot\\\\theta_{|V}=\\\\theta^\\\\prime_{|V}.\\\\]',\n u'\\\\[\\\\theta(w_1)=\\\\ldots=\\\\theta(w_{n-1})=0.\\\\]',\n u'\\\\[\\\\xymatrix{\\\\mathbb{C}^n&W\\\\ar@{^{(}->}[l]\\\\ar[d]&V\\\\capV^\\\\prime\\\\ar[l]_{\\\\cong}\\\\ar[ld]^{\\\\pi}\\\\ar[r]^{\\\\cong}\\\\ar[rd]_{\\\\pi^\\\\prime}&W^\\\\prime\\\\ar[d]\\\\ar@{^{(}->}[r]&\\\\mathbb{C}^n\\\\\\\\&\\\\mathbb{C}^{n-1}&&\\\\mathbb{C}^{n-1}&}\\\\]',\n u'\\\\[A=\\\\left(\\\\frac{\\\\partialf_j}{\\\\partialz_i}(0)\\\\right)_{i,j=1,\\\\ldots,n}\\\\]',\n u'\\\\[\\\\lambda_i=\\\\sum_{j=1}^nm_j\\\\lambda_j.\\\\]',\n u'\\\\[|\\\\sum_{i=1}^n\\\\lambda_it_i|\\\\geqc\\\\cdot\\\\sum_{i=1}^nt_i,\\\\]',\n u'\\\\[\\\\left(\\\\sum_{i=1}^n\\\\overline{p_i}dz_i+\\\\sum_{i=1}^np_id\\\\overline{z_i}\\\\right)\\\\left(\\\\sum_{i=1}^nf_i(p)\\\\frac{\\\\partial}{\\\\partialz_i}\\\\right)=\\\\sum_{i=1}^n\\\\overline{p_i}\\\\cdotf_i(p)=0,\\\\]',\n u'\\\\[\\\\left|\\\\sum_{j\\\\inJ}\\\\overline{p_j}\\\\frac{c}{2n}p_{j+1}\\\\right|\\\\leq|J|\\\\cdot\\\\frac{c}{2n}\\\\cdot\\\\epsilon^2\\\\leq\\\\frac{c}{2}\\\\cdot\\\\epsilon^2.\\\\]',\n u'\\\\[\\\\sup_{p\\\\inS^{2n-1}_{\\\\epsilon}}|\\\\sum_{i=1}^n\\\\overline{p_i}g_i(p)|\\\\leqC\\\\cdot\\\\epsilon^3.\\\\]',\n u'\\\\[\\\\left|\\\\left(\\\\sum_{i=1}^n\\\\overline{p_i}dz_i+\\\\sum_{i=1}^np_id\\\\overline{z_i}\\\\right)\\\\left(\\\\sum_{i=1}^nf_i(p)\\\\frac{\\\\partial}{\\\\partialz_i}\\\\right)\\\\right|=\\\\left|\\\\sum_{i=1}^n\\\\overline{p_i}\\\\cdotf_i(p)\\\\right|\\\\]',\n u'\\\\[\\\\Psi:B^{2n}_{\\\\epsilon_0}\\\\times[0,\\\\infty)\\\\rightarrowB^{2n}_{\\\\epsilon_0},\\\\x\\\\mapstoxe^{-t}\\\\]',\n u'\\\\[\\\\Psi(\\\\{\\\\mathrm{leaf\\\\of\\\\}\\\\mathcal{F}\\\\capS^{2n-1}_{\\\\epsilon_0}\\\\}\\\\times[0,\\\\infty))\\\\]',\n u'\\\\[H:B^{2n}_{\\\\epsilon_0}\\\\rightarrowB^{2n}_{\\\\epsilon_0},\\\\q\\\\mapsto\\\\Psi_{t_q}(\\\\Phi^{-1}_{t_q}(q)),\\\\\\\\qeq0,\\\\\\\\mathrm{and\\\\}H(0)=0,\\\\]',\n u'\\\\[h:S^{2n-1}_{\\\\epsilon^\\\\prime}\\\\stackrel{H_C}{\\\\hookrightarrow}B^{2n}_{\\\\epsilon}-\\\\{0\\\\}\\\\stackrel{r}{\\\\rightarrow}S^{2n-1}_{\\\\epsilon}\\\\]',\n u'\\\\[(h\\\\circ\\\\Phi_{\\\\mathcal{F}})(x,t)eq\\\\Phi_{\\\\mathcal{G}}(h(x),t).\\\\]',\n u'\\\\[\\\\Phi_{\\\\widetilde{\\\\mathcal{F}}}((x,t^\\\\prime),t):=(\\\\Phi_{\\\\mathcal{F}}(x,t),t+t^\\\\prime),x\\\\inS^{2n-1}_{\\\\epsilon^\\\\prime},t,t^\\\\prime\\\\in\\\\mathbb{R}.\\\\]',\n u'\\\\[\\\\Phi_{\\\\widetilde{\\\\mathcal{G}}}((y,s^\\\\prime),s):=(\\\\Phi_{\\\\mathcal{G}}(y,s),s+s^\\\\prime),y\\\\inS^{2n-1}_{\\\\epsilon},s,s^\\\\prime\\\\in\\\\mathbb{R}\\\\]',\n u'\\\\[\\\\widetilde{H}:S^{2n-1}_{\\\\epsilon^\\\\prime}\\\\times\\\\mathbb{R}\\\\rightarrowS^{2n-1}_{\\\\epsilon}\\\\times\\\\mathbb{R}\\\\]',\n u'\\\\[\\\\Phi_{\\\\widetilde{\\\\mathcal{G}}}((h(x),0),s)=\\\\widetilde{H}(\\\\Phi_{\\\\mathcal{F}}(x,t),t),\\\\]',\n u'\\\\[\\\\Phi_{\\\\mathcal{G}}((h(x),s),s)=(h(\\\\Phi_{\\\\mathcal{F}}(x,t)),(q_2\\\\circ\\\\widetilde{H})(\\\\Phi_{\\\\mathcal{F}}(x,t),t)).\\\\]',\n u'h(\\\\Phi_{\\\\mathcal{F}}(x,t))=\\\\Phi_{\\\\mathcal{G}}((h(x),\\\\tau(x,t)).',\n u'\\\\tau(x,0)=0.',\n u'\\\\tau(x,t+t^\\\\prime)=\\\\tau(x,t)+\\\\tau(\\\\Phi_{\\\\mathcal{F}}(x,t),t^\\\\prime).',\n u'\\\\[\\\\tau(x,t+t^\\\\prime)=\\\\tau(x,t)+\\\\tau(\\\\Phi_{\\\\mathcal{F}}(x,t),t^\\\\prime)+k(t,t^\\\\prime)\\\\cdotT_{\\\\mathcal{G},h(x)},\\\\]',\n u'\\\\[\\\\tau(x,t+T_{\\\\mathcal{F},x})=\\\\tau(x,t)+l\\\\cdotT_{\\\\mathcal{G},h(x)}.\\\\]',\n u'\\\\tau(x,t+T_{\\\\mathcal{F},x})=\\\\tau(x,t)+T_{\\\\mathcal{G},h(x)}.',\n u'\\\\lim_{t\\\\rightarrow\\\\infty}\\\\tau(x,t)=\\\\infty\\\\\\\\mathrm{and}\\\\\\\\lim_{t\\\\rightarrow-\\\\infty}\\\\tau(x,t)=-\\\\infty:',\n u'\\\\[y=h(\\\\Phi_{\\\\mathcal{F}}(x,t))=\\\\Phi_{\\\\mathcal{G}}(h(x),\\\\tau(x,t))\\\\]',\n u'\\\\[\\\\gamma_{\\\\delta}(x,t):=\\\\min_{t0,\\\\]',\n u'\\\\[\\\\sigma(x,t):=\\\\frac{1}{\\\\gamma_\\\\delta(x,t)}\\\\int_t^{t+\\\\gamma_\\\\delta(x,t)}\\\\mu(x,t^\\\\prime)dt^\\\\prime\\\\]',\n u'\\\\sigma(x,t+t^\\\\prime)=\\\\sigma(\\\\Phi_{\\\\mathcal{F}}(x,t),t^\\\\prime)+\\\\tau(x,t).',\n u'\\\\[\\\\sigma(x,t)=\\\\sigma(x,0)+k\\\\cdotT_{\\\\mathcal{G},h(x)}=\\\\sigma(x,0)+k\\\\cdot\\\\tau(x,T_{\\\\mathcal{F},x})=\\\\sigma(x,k\\\\cdotT_{\\\\mathcal{F},x}),\\\\]',\n u'\\\\[\\\\lambdax\\\\frac{\\\\partial}{\\\\partialx}+y\\\\frac{\\\\partial}{\\\\partialy},\\\\\\\\lambda\\\\in\\\\mathbb{C}-\\\\mathbb{R}.\\\\]',\n u'\\\\[ye^{it_2}d(xe^{it_1})-\\\\lambdaxe^{it_1}d(ye^{it_2})=e^{i(t_1+t_2)}(ydx-\\\\lambdaxdy)\\\\]',\n u'\\\\[d(x\\\\overline{x})=\\\\overline{x}dx+xd\\\\overline{x}\\\\\\\\mathrm{and}\\\\d(y\\\\overline{y})=\\\\overline{y}dy+yd\\\\overline{y}.\\\\]',\n u'\\\\[(\\\\overline{y}dy+yd\\\\overline{y})(\\\\lambdax\\\\frac{\\\\partial}{\\\\partialx}+y\\\\frac{\\\\partial}{\\\\partialy})=\\\\overline{y}y\\\\in\\\\mathbb{R}\\\\\\\\mathrm{and}\\\\yeq0\\\\]',\n u'\\\\[(\\\\overline{x}dx+xd\\\\overline{x})(\\\\lambdax\\\\frac{\\\\partial}{\\\\partialx}+y\\\\frac{\\\\partial}{\\\\partialy})=\\\\lambda\\\\overline{x}x\\\\\\\\mathrm{and}\\\\xeq0\\\\]',\n u'\\\\[\\\\omega=d(y^2+|x|^2-1)=2ydy+\\\\overline{x}dx+xd\\\\overline{x}.\\\\]',\n u'\\\\[\\\\omega_{\\\\mathrm{Re}}=ydy+\\\\overline{y}d\\\\overline{y}+\\\\overline{x}dx+xd\\\\overline{x}\\\\\\\\mathrm{and}\\\\\\\\omega_{\\\\mathrm{Im}}=-i(ydy-\\\\overline{y}d\\\\overline{y}).\\\\]',\n u'\\\\[\\\\omega_{\\\\mathrm{Re}}(\\\\theta(x,y))=2y^2+\\\\lambdax\\\\overline{x}\\\\\\\\mathrm{and}\\\\d(\\\\overline{x}x+\\\\overline{y}y)(\\\\theta(x,y))=\\\\lambdax\\\\overline{x}+y\\\\overline{y},\\\\]',\n u'\\\\[\\\\Phi_x^{(i)}:T_{1/2}\\\\times(0,1/2]\\\\rightarrow\\\\{(x,y)\\\\inS^3:0<|x|\\\\leq1/2\\\\}\\\\]',\n u'\\\\[\\\\Phi_x^{(2)}\\\\circ\\\\left[\\\\mathrm{id}_{T^x{\\\\frac{1}{2}}}\\\\times((\\\\phi^{(2)}_x)^{-1}\\\\circ\\\\phi^{(1)}_x)\\\\right]\\\\circ(\\\\Phi_x^{(1)})^{-1}\\\\]',\n u'\\\\[(mx+y^m)\\\\frac{\\\\partial}{\\\\partialx}+y\\\\frac{\\\\partial}{\\\\partialy},\\\\m\\\\geq1.\\\\]',\n u'\\\\[\\\\overline{x}(mx+y^m)+\\\\overline{y}y=\\\\overline{x}x+\\\\overline{y}y+(m-1)\\\\overline{x}x+\\\\overline{x}y^meq0.\\\\]',\n u'\\\\[|\\\\overline{x}y^m|=|x|\\\\cdot|y|^m<\\\\epsilon^{m+1}\\\\leq\\\\epsilon^2,\\\\]',\n u'\\\\[\\\\lambda_{(a,b)}:\\\\mathbb{C}\\\\rightarrow\\\\mathbb{C}^2,\\\\t\\\\mapsto((a+b^mt)e^{mt},be^t)\\\\]',\n u'\\\\[1=e^{m(t+\\\\overline{t})}(a\\\\overline{a}+b^m\\\\overline{a}t+a\\\\overline{b}^m\\\\overline{t}+(b\\\\overline{b})^mt\\\\overline{t})+b\\\\overline{b}e^{t+\\\\overline{t}}.\\\\]',\n u'\\\\[\\\\tag{\\\\ast}(b\\\\overline{b})^mt_I^2+2\\\\mathrm{Im}(a\\\\overline{b}^m)t_I+a\\\\overline{a}+2\\\\mathrm{Re}(b^m\\\\overline{a})t_R+(b\\\\overline{b})^mt_R^2+b\\\\overline{b}e^{2(1-m)t_R}-e^{-2mt_R}=0.\\\\]',\n u'\\\\[2\\\\mathrm{Re}(b^m\\\\overline{a})+2(b\\\\overline{b})^mt_R+2(1-m)b\\\\overline{b}e^{2(1-m)t_R}+2me^{-2mt_R}\\\\]',\n u'\\\\[\\\\{(a,b)\\\\inS^3:\\\\mathrm{Im}(a\\\\overline{b}^m)=0,beq0\\\\}.\\\\]',\n u'\\\\[\\\\begin{array}{ccccc}V_1^\\\\prime&\\\\stackrel{\\\\Phi}{\\\\rightarrow}&\\\\Phi(V_1^\\\\prime)&\\\\subset&V_2^\\\\prime\\\\\\\\\\\\cap&&\\\\cap&&\\\\cap\\\\\\\\S^3-\\\\{y=0\\\\}&\\\\stackrel{\\\\Phi}{\\\\rightarrow}&S^3-\\\\{y=0\\\\}&=&S^3-\\\\{y=0\\\\}.\\\\\\\\\\\\end{array}\\\\]',\n u'\\\\[\\\\begin{array}{ccccc}\\\\rule{.5cm}{0cm}\\\\mathbb{Z}&\\\\stackrel{\\\\cdot\\\\pm1}{\\\\longrightarrow}&\\\\mathbb{Z}&\\\\rightarrow&\\\\mathbb{Z}\\\\rule{.5cm}{0cm}\\\\\\\\\\\\cdotm_1\\\\downarrow&&&&\\\\downarrow\\\\cdotm_2\\\\\\\\\\\\rule{.5cm}{0cm}\\\\mathbb{Z}&=&\\\\mathbb{Z}&=&\\\\mathbb{Z}\\\\rule{.5cm}{0cm}\\\\end{array}\\\\]',\n u'\\\\[t(1-m+t^mx^{m-1})dx-(mx+t^mx^m)dt\\\\\\\\mathrm{resp.\\\\}(mx+t^mx^m)\\\\frac{\\\\partial}{\\\\partialx}+t(1-m+t^mx^{m-1})\\\\frac{\\\\partial}{\\\\partialt}\\\\]',\n u'\\\\[yds+(s(1-m)+y^{m-1})dy\\\\\\\\mathrm{resp.\\\\}y\\\\frac{\\\\partial}{\\\\partialy}+((m-1)s+y^{m-1})\\\\frac{\\\\partial}{\\\\partials}\\\\]',\n u'\\\\[\\\\lambdax\\\\frac{\\\\partial}{\\\\partialx}+y\\\\frac{\\\\partial}{\\\\partialy},\\\\\\\\lambda\\\\in\\\\mathbb{R}_{>0}.\\\\]',\n u'\\\\[t\\\\cdot_\\\\lambda(e^{ia},e^{ib})=(e^{i(a+\\\\lambdat)},e^{i(b+t)}),\\\\t,a,b\\\\in\\\\mathbb{R}.\\\\]',\n u'\\\\[\\\\phi_Q:T^2\\\\rightarrowT^2,(e^{ix},e^{iy})\\\\mapsto(e^{i(ax+by)},e^{i(cx+dy)})\\\\]',\n u'\\\\[\\\\mu=Q\\\\cdot\\\\lambda=\\\\frac{a\\\\lambda+b}{c\\\\lambda+d}.\\\\]',\n u'\\\\[L_P^{(\\\\lambda)}:=\\\\{(e^{i(a+\\\\lambdat)},e^{i(b+t)})|t\\\\in\\\\mathbb{R}\\\\}\\\\subsetT^2\\\\]',\n u'\\\\[\\\\left[\\\\frac{\\\\lambdab_\\\\epsilon}{2\\\\pi}\\\\right]\\\\leq\\\\left|p([0,b_\\\\epsilon])\\\\capC_2\\\\right|\\\\leq\\\\left[\\\\frac{\\\\lambdab_\\\\epsilon}{2\\\\pi}\\\\right]+1\\\\\\\\mathrm{and}\\\\left[\\\\frac{b_\\\\epsilon}{2\\\\pi}\\\\right]\\\\leq\\\\left|p([0,b_\\\\epsilon])\\\\capC_1\\\\right|\\\\leq\\\\left[\\\\frac{b_\\\\epsilon}{2\\\\pi}\\\\right]+1,\\\\]',\n u'\\\\[\\\\lambda=\\\\lim_{\\\\epsilon\\\\rightarrow0}\\\\frac{[\\\\gamma_{P,\\\\epsilon}^{(\\\\lambda)}]\\\\cdot[C_2]}{[\\\\gamma_{P,\\\\epsilon}^{(\\\\lambda)}]\\\\cdot[C_1]}=\\\\lim_{\\\\epsilon\\\\rightarrow0}\\\\frac{[\\\\phi(\\\\gamma_{P,\\\\epsilon}^{(\\\\lambda)})]\\\\cdot[\\\\phi(C_2)]}{[\\\\phi(\\\\gamma_{P,\\\\epsilon}^{(\\\\lambda)})]\\\\cdot[\\\\phi(C_1)]}=\\\\lim_{\\\\epsilon\\\\rightarrow0}\\\\frac{[\\\\phi(\\\\gamma_{P,\\\\epsilon}^{(\\\\lambda)})]\\\\cdot[C_2]}{[\\\\phi(\\\\gamma_{P,\\\\epsilon}^{(\\\\lambda)})]\\\\cdot[C_1]},\\\\]',\n u'\\\\[\\\\lim_{\\\\epsilon\\\\rightarrow0}\\\\frac{[\\\\gamma_{\\\\phi(P),U_\\\\epsilon}^{(\\\\mu)}]\\\\cdot[C_2]}{[\\\\gamma_{\\\\phi(P),U_\\\\epsilon}^{(\\\\mu)}]\\\\cdot[C_1]}=\\\\mu,\\\\]',\n u'\\\\[0<\\\\mathrm{Re}\\\\lambda_1<\\\\cdots<\\\\mathrm{Re}\\\\lambda_n\\\\\\\\mathrm{resp.\\\\}0<\\\\mathrm{Re}\\\\mu_1<\\\\cdots<\\\\mathrm{Re}\\\\mu_n.\\\\]',\n u'\\\\[L_1:=\\\\left\\\\{z_l=0:leqi_1,\\\\ldots,i_k\\\\right\\\\},L_2:=\\\\left\\\\{z_m=0:meqj_1,\\\\ldots,j_k\\\\right\\\\}\\\\subset\\\\mathbb{C}^n\\\\]',\n u'\\\\mathscr{T}_{ij}\\\\equiv\\\\mathrm{H}(\\\\Phi)_{ij}=\\\\frac{\\\\partial^2\\\\Phi}{\\\\partial\\\\vec{x}_i\\\\partial\\\\vec{x}_j},',\n u'\\\\Delta\\\\Phi(\\\\vec{x})=\\\\delta(\\\\vec{x}),',\n u'\\\\vec{x}(\\\\vec{q})\\\\equiv\\\\vec{q}+\\\\vec{\\\\Psi}(\\\\vec{q}).',\n u'J(\\\\vec{q})\\\\equiv\\\\det\\\\left[\\\\frac{\\\\partial\\\\vec{x}}{\\\\partial\\\\vec{q}}\\\\right]=\\\\det\\\\mathscr{D}=\\\\det(\\\\mathscr{I}+\\\\mathscr{R}),',\n u'\\\\mathrm{T}_i(\\\\vec{q}_\\\\ell|\\\\xi)\\\\in\\\\{0,1\\\\}\\\\;\\\\mathrm{for}\\\\;i\\\\in\\\\llbracket0,3\\\\rrbracket\\\\quad\\\\mathrm{and}\\\\quad\\\\sum_{i=0}^{3}\\\\mathrm{T}_i(\\\\vec{q}_\\\\ell|\\\\xi)=1',\n u'\\\\mathcal{T}_i(\\\\vec{q}_\\\\ell|\\\\xi)\\\\in[0,1]\\\\;\\\\mathrm{for}\\\\;i\\\\in\\\\llbracket0,3\\\\rrbracket\\\\quad\\\\mathrm{and}\\\\quad\\\\sum_{i=0}^{3}\\\\mathcal{T}_i(\\\\vec{q}_\\\\ell|\\\\xi)=1.',\n u'\\\\left\\\\langle\\\\mathcal{P}(\\\\mathrm{T}_i(\\\\vec{q}_\\\\ell)|d,\\\\xi)\\\\right\\\\rangle=\\\\frac{1}{N}\\\\sum_{n=1}^{N}\\\\sum_{j=0}^{3}\\\\delta^{(\\\\mathrm{K})}_{\\\\mathrm{T}_i(\\\\vec{q}_\\\\ell)\\\\mathrm{T}^n_j(\\\\vec{q}_\\\\ell|\\\\xi)},',\n u'\\\\left\\\\langle\\\\mathcal{P}(\\\\mathrm{T}_i(\\\\vec{x}_k)|d,\\\\xi)\\\\right\\\\rangle=\\\\frac{1}{N_{\\\\vec{x}_k}}\\\\sum_{n=1}^N\\\\mathcal{P}_n(\\\\mathrm{T}_i(\\\\vec{x}_k)|d,\\\\xi),',\n u'N_{\\\\vec{x}_k}=\\\\sum_{n=1}^N\\\\delta^{\\\\mathrm{(K)}}_{\\\\mathcal{S}_n(\\\\vec{x}_k),1}.',\n u'{F=(c\\\\hbar/2\\\\pie)A},',\n u'{{R}_{T}}=\\\\frac{2{{\\\\pi}^{2}}{{k}_{B}}nT/\\\\hbar{{\\\\omega}_{c}}}{\\\\text{sh}(2{{\\\\pi}^{2}}{{k}_{B}}nT/\\\\hbar{{\\\\omega}_{c}})};',\n u'{{{R}_{\\\\tau}}=\\\\exp(-2{{\\\\pi}^{2}}{{k}_{B}}nx/\\\\hbar{{\\\\omega}_{c}}),}',\n u'{{{R}_{0}}=\\\\frac{16\\\\rho{{l}_{i}}}{3\\\\pi{{d}^{2}}}+\\\\beta({{l}_{i}}/d)\\\\frac{\\\\rho}{d}}',\n u'{{{N}_{\\\\omega}}(\\\\mathbf{r})=\\\\frac{eV-\\\\hbar\\\\omega}{2\\\\hbar\\\\omega}\\\\Theta(eV-\\\\hbar\\\\omega){{q}_{\\\\omega}}(\\\\mathbf{r}),}',\n u\"{{{q}_{\\\\omega}}(\\\\mathbf{r})\\\\frac{1}{4\\\\pi\\\\Lambda_{\\\\omega}^{2}}\\\\int{d\\\\mathbf{r}\\\\frac{\\\\exp(-R/{{\\\\Lambda}_{\\\\omega}})}{R}}q(\\\\mathbf{{r}'});}\",\n u\"\\\\[\\\\begin{matrix}R=\\\\left|\\\\mathbf{r}-\\\\mathbf{{r}'}\\\\right|;\\\\\\\\q(r)=\\\\frac{1}{2}\\\\left[1-{{\\\\left(1-\\\\frac{\\\\Omega(\\\\textbf{r})}{2\\\\pi}\\\\right)}^{2}}\\\\right];\\\\\\\\{{\\\\Lambda}_{\\\\omega}}={{\\\\left(l_{i}^{ph}l_{\\\\varepsilon}^{ph}/3\\\\right)}^{1/2}}{{({{\\\\omega}_{D}}-\\\\omega)}^{{1}/{2}\\\\;}}\\\\\\\\\\\\end{matrix}\\\\]\",\n u'\\\\[\\\\tau_{\\\\varepsilonD}^{-1}=\\\\frac{2\\\\pi}{\\\\hbar}\\\\int\\\\limits_{0}^{\\\\omegaD}{g(\\\\omega)d\\\\omega}\\\\]',\n u'{\\\\lambda(eV)=\\\\frac{{{\\\\lambda}_{0}}}{2}\\\\left[1+\\\\frac{{{(h{{u}_{0}})}^{2}}}{{{(h{{u}_{0}})}^{2}}-{{(eV)}^{2}}}\\\\right].}',\n u'{{{A}_{1}}/{{A}_{2}}=C\\\\cosh\\\\left(\\\\frac{2{{\\\\pi}^{2}}{{k}_{B}}T}{\\\\hbar{{\\\\omega}_{c}}}\\\\right)\\\\exp\\\\left(\\\\frac{\\\\pi}{{{\\\\omega}_{c}}\\\\tau}\\\\right).}',\n u'\\\\mathrm{F}_{ij}\\\\circ\\\\mathrm{F}_{st}=\\\\mathrm{F}_{it}^{\\\\oplus\\\\dim(e_jAe_s)}.',\n u'\\\\mathrm{F}\\\\circ\\\\mathrm{F}\\\\cong\\\\mathrm{F}^{\\\\oplus\\\\dim(A)}',\n u\"\\\\mathrm{Hom}_Q(\\\\mathrm{K}P,{}_-)\\\\cong\\\\mathrm{Hom}_Q(P,\\\\mathrm{K}'{}_-).\",\n u'V\\\\otimes_Q\\\\left(X\\\\otimesY\\\\right)\\\\cong\\\\left(V\\\\otimes_QX\\\\right)\\\\otimesY.',\n u'\\\\begin{array}{c||c|c|c|c}\\\\circ&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}\\\\\\\\\\\\hline\\\\hline\\\\mathrm{F}_{11}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{12}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}\\\\\\\\\\\\hline\\\\mathrm{F}_{21}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{22}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}\\\\\\\\\\\\end{array}',\n u'\\\\mathrm{Hom}_{A\\\\text{-}A}(Ae_i\\\\otimese_jA,Ae_s\\\\otimese_tA)\\\\conge_iAe_s\\\\otimese_tAe_j,',\n u'\\\\begin{array}{c||c|c|c|c}X\\\\setminusY&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}\\\\\\\\\\\\hline\\\\hline\\\\mathrm{F}_{11}&\\\\Bbbk&\\\\Bbbk&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{12}&0&\\\\Bbbk&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{21}&\\\\Bbbk&\\\\Bbbk&\\\\Bbbk&\\\\Bbbk\\\\\\\\\\\\hline\\\\mathrm{F}_{22}&0&\\\\Bbbk&0&\\\\Bbbk\\\\\\\\\\\\end{array}',\n u'\\\\begin{aligned}M_1:=\\\\left(3\\\\right),\\\\quadM_2:=\\\\left(\\\\begin{array}{cc}2&1\\\\\\\\2&1\\\\end{array}\\\\right),\\\\quadM_3:=\\\\left(\\\\begin{array}{cc}2&2\\\\\\\\1&1\\\\end{array}\\\\right),\\\\quadM_4:=\\\\left(\\\\begin{array}{cc}1&1\\\\\\\\2&2\\\\end{array}\\\\right),\\\\\\\\M_5:=\\\\left(\\\\begin{array}{cc}1&2\\\\\\\\1&2\\\\end{array}\\\\right),\\\\quadM_6:=\\\\left(\\\\begin{array}{ccc}1&1&1\\\\\\\\1&1&1\\\\\\\\1&1&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{cc}1&0\\\\\\\\0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{cc}1&1\\\\\\\\0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{21}=\\\\left(\\\\begin{array}{cc}0&0\\\\\\\\1&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{cc}0&0\\\\\\\\1&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{cc}0&1\\\\\\\\0&1\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{cc}1&0\\\\\\\\1&0\\\\end{array}\\\\right),\\\\,\\\\,M_{21}=\\\\left(\\\\begin{array}{cc}0&1\\\\\\\\0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{cc}1&0\\\\\\\\0&0\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&0&0\\\\\\\\1&0&0\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&1&1\\\\\\\\0&1&1\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\1&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\0&1&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&*&*\\\\\\\\*&0&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&*&*\\\\\\\\*&1&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&*&*\\\\\\\\*&0&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&*&*\\\\\\\\*&0&*\\\\\\\\*&*&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&*&0\\\\\\\\*&0&0\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&*&1\\\\\\\\*&1&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\*&0&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\*&0&*\\\\\\\\*&*&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&*&0\\\\\\\\1&0&0\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&*&1\\\\\\\\0&1&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&*\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&*\\\\\\\\*&*&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&0&0\\\\\\\\1&0&0\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&1&1\\\\\\\\0&1&1\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\*&*&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\*&*&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&0&0\\\\\\\\1&0&0\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&1&1\\\\\\\\0&1&1\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\*&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\*&1&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{aligned}M_{11}=\\\\left(\\\\begin{array}{ccc}1&0&0\\\\\\\\1&0&0\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{12}=\\\\left(\\\\begin{array}{ccc}0&1&1\\\\\\\\0&1&1\\\\\\\\0&0&0\\\\end{array}\\\\right),\\\\\\\\M_{21}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\1&0&0\\\\end{array}\\\\right),\\\\,\\\\,M_{22}=\\\\left(\\\\begin{array}{ccc}0&0&0\\\\\\\\0&0&0\\\\\\\\0&1&1\\\\end{array}\\\\right).\\\\end{aligned}',\n u'\\\\begin{array}{c||c|c|c|c|c|c|c|c|c}\\\\circ&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}\\\\\\\\\\\\hline\\\\hline\\\\mathrm{F}_{11}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}&0&0&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{12}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{13}&0&0&0&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}\\\\\\\\\\\\hline\\\\mathrm{F}_{21}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}&0&0&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{22}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{23}&0&0&0&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}\\\\\\\\\\\\hline\\\\mathrm{F}_{31}&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}&0&0&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{32}&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{33}&0&0&0&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}\\\\\\\\\\\\end{array}',\n u'\\\\begin{array}{c||c|c|c|c|c|c|c|c|c}X\\\\setminusY&\\\\mathrm{F}_{11}&\\\\mathrm{F}_{12}&\\\\mathrm{F}_{13}&\\\\mathrm{F}_{21}&\\\\mathrm{F}_{22}&\\\\mathrm{F}_{23}&\\\\mathrm{F}_{31}&\\\\mathrm{F}_{32}&\\\\mathrm{F}_{33}\\\\\\\\\\\\hline\\\\hline\\\\mathrm{F}_{11}&\\\\Bbbk&\\\\Bbbk&0&0&0&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{12}&0&\\\\Bbbk&\\\\Bbbk&0&0&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{13}&0&0&\\\\Bbbk&0&0&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{21}&\\\\Bbbk&\\\\Bbbk&0&\\\\Bbbk&\\\\Bbbk&0&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{22}&0&\\\\Bbbk&\\\\Bbbk&0&\\\\Bbbk&\\\\Bbbk&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{23}&0&0&\\\\Bbbk&0&0&\\\\Bbbk&0&0&0\\\\\\\\\\\\hline\\\\mathrm{F}_{31}&0&0&0&\\\\Bbbk&\\\\Bbbk&0&\\\\Bbbk&\\\\Bbbk&0\\\\\\\\\\\\hline\\\\mathrm{F}_{32}&0&0&0&0&\\\\Bbbk&\\\\Bbbk&0&\\\\Bbbk&\\\\Bbbk\\\\\\\\\\\\hline\\\\mathrm{F}_{33}&0&0&0&0&0&\\\\Bbbk&0&0&\\\\Bbbk\\\\end{array}',\n u'\\\\begin{array}{ccc}M_{11}&M_{12}&M_{13}\\\\\\\\M_{21}&M_{22}&M_{23}\\\\\\\\M_{31}&M_{32}&M_{33}.\\\\end{array}',\n u'\\\\Vert\\\\varphi\\\\Vert^2=\\t\\\\int_{-h}^0\\\\Vert\\\\varphi(\\\\theta)\\\\Vert^2\\\\,d\\\\theta.',\n u'\\\\begin{aligned}x\\\\in\\\\mathcal{O}(R)&\\\\Leftrightarrow\\\\Vertx\\\\Vert^2\\\\leqR^2,\\\\\\\\(x,\\\\varphi)\\\\in\\\\mathcal{O}(R)&\\\\Leftrightarrow\\\\Vertx\\\\Vert^2+\\\\Vert\\\\varphi\\\\Vert^2\\\\leqR^2.\\\\end{aligned}',\n u'\\\\begin{multline}\\\\dot{x}(t)=f\\\\big(x(t)\\\\big)+B_0\\\\big(x(t)\\\\big)u(t)+B_1\\\\big(x(t)\\\\big)u(t-h)\\\\\\\\\\t+\\\\int_{-h}^0B_\\\\text{int}\\\\big(\\\\theta,x(t)\\\\big)u(t+\\\\theta)\\\\,d\\\\theta,\\\\end{multline}',\n u'\\\\begin{aligned}\\\\Vertf(x)\\\\Vert&\\\\leqM_f\\\\Vertx\\\\Vert,\\\\\\\\f(x)&=f(x_0)+A(x_0)(x-x_0)+o(x-x_0),\\\\\\\\A&\\\\inC^0\\\\big(\\\\mathcal{O}(R),R^{n\\\\timesn}\\\\big);\\\\end{aligned}',\n u'\\\\begin{aligned}B_1&\\\\text{isboundedon}\\\\mathcal{O}(R),\\\\\\\\B_1(x)&=B_1(x_0)+\\\\Big(\\\\mathcal{B}_1^1(x_0)(x-x_0),\\\\dots,\\\\mathcal{B}_1^m(x_0)(x-x_0)\\\\Big)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+o(x-x_0),\\\\\\\\\\\\mathcal{B}_1^i&\\\\inC^0\\\\big(\\\\mathcal{O}(R),R^{n\\\\timesn}\\\\big)\\\\quad\\\\foralli\\\\in\\\\overline{1,m};\\\\end{aligned}',\n u'\\\\begin{aligned}B_\\\\text{int}&\\\\text{isboundedon}[-h,0]\\\\times\\\\mathcal{O}(R),\\\\\\\\B_\\\\text{int}(\\\\cdot,x)&\\\\inPC\\\\big([-h,0],R^{n\\\\timesm}\\\\big),\\\\\\\\B_\\\\text{int}(\\\\theta,x)&=B_\\\\text{int}(\\\\theta,x_0)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\Big(\\\\mathcal{B}_\\\\text{int}^1(\\\\theta,x_0)(x-x_0),\\\\dots,\\\\mathcal{B}_\\\\text{int}^m(\\\\theta,x_0)(x-x_0)\\\\Big)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+o(x-x_0),\\\\\\\\\\\\mathcal{B}_\\\\text{int}^i(\\\\theta,\\\\cdot)&\\\\inC^0\\\\big(\\\\mathcal{O}(R),R^{n\\\\timesn}\\\\big)\\\\quad\\\\foralli\\\\in\\\\overline{1,m}.\\\\end{aligned}',\n u'\\\\dot{x}(t)=Ax(t)+B_1u(t-h).',\n u'Y\\\\big(x(t),u_t\\\\big)=e^{Ah}x(t)+\\\\int_{-h}^0e^{-A\\\\theta}B_1u(t+\\\\theta)\\\\,d\\\\theta;',\n u'y(t)=Y\\\\big(x(t),u_t\\\\big);',\n u'\\\\dot{y}(t)=Ay(t)+B_1u(t);',\n u'\\\\dot{x}(t)=Ax(t)+B_0u(t)+B_1u(t-h)+\\t\\\\int_{-h}^0B_\\\\text{int}(\\\\theta)u(t+\\\\theta)\\\\,d\\\\theta.',\n u\"\\\\begin{aligned}Y\\\\big(x(t),u_t\\\\big)&=\\\\xi(h),\\\\\\\\\\\\xi'(s)&=A\\\\xi(s)+B_1u(t+s-h)onumber\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\int_{-h}^{-s}B_\\\\text{int}(\\\\theta)u(t+s+\\\\theta)\\\\,d\\\\theta,\\\\\\\\\\\\xi(0)&=x(t)\\\\end{aligned}\",\n u'Y\\\\big(x(t),u_t\\\\big)=e^{Ah}x(t)+\\\\int_{-h}^0Q(\\\\theta)u(t+\\\\theta)\\\\,d\\\\theta,',\n u'Q(\\\\theta)=e^{-A\\\\theta}B_1+\\\\int_{-h}^\\\\thetae^{A(h-\\\\theta+\\\\tau)}B_\\\\text{int}(\\\\tau)\\\\,d\\\\tau;',\n u'y(t)=Y\\\\big(x(t),u_t\\\\big);',\n u'\\\\dot{y}(t)=Ay(t)+\\\\big(e^{Ah}B_0+Q(0)\\\\big)u(t);',\n u'u(t)=KY\\\\big(x(t),u_t\\\\big).',\n u'v(x,\\\\varphi)=Y^T(x,\\\\varphi)VY(x,\\\\varphi)\\t+\\\\int_{-h}^{\\\\,0}e^{\\\\sigma\\\\theta}\\\\Vert\\\\varphi(\\\\theta)\\\\Vert^2\\\\,d\\\\theta,',\n u'\\\\dot{x}(t)=f\\\\big(x(t),u(t-h)\\\\big).',\n u'\\\\dot{y}(t)=f\\\\big(y(t),u(t)\\\\big)',\n u'y(t)=Y\\\\big(x(t),u_t\\\\big)',\n u\"\\\\begin{aligned}Y(x,\\\\varphi)&=\\\\xi(h),\\\\\\\\\\\\xi'(s)&=f\\\\big(\\\\xi(s)\\\\big)+B_1\\\\big(\\\\xi(s)\\\\big)\\\\varphi(s-h)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\int_{-h}^{-s}B_\\\\textrm{int}\\\\big(\\\\theta,\\\\xi(s)\\\\big)\\\\varphi(s+\\\\theta)\\\\,d\\\\theta,\\\\\\\\\\\\xi(0)&=x.\\\\end{aligned}\",\n u'(x,\\\\varphi)\\\\in\\\\mathcal{O}\\\\left(\\\\frac{R}{\\\\rho}\\\\right),',\n u'\\\\begin{aligned}\\\\Vertx\\\\Vert^2\\\\leq\\t\\\\rho^2\\\\big(\\\\VertY(x,\\\\varphi)\\\\Vert^2+\\\\Vert\\\\varphi\\\\Vert^2\\\\big),\\\\\\\\\\\\VertY(x,\\\\varphi)\\\\Vert^2\\\\leq\\t\\\\rho^2\\\\big(\\\\Vertx\\\\Vert^2+\\\\Vert\\\\varphi\\\\Vert^2\\\\big).\\\\end{aligned}',\n u'\\\\Vert\\\\xi(s)\\\\Vert^2\\\\leq\\t\\\\rho^2\\\\big(\\\\Vertx\\\\Vert^2+\\\\Vert\\\\varphi\\\\Vert^2\\\\big)',\n u'\\\\dot{y}(t)=f\\\\big(y(t)\\\\big)+B\\\\big(y(t),u_t\\\\big)u(t)',\n u\"\\\\begin{aligned}B(y,\\\\varphi)&=B_1\\\\big(\\\\xi(h)\\\\big)+\\\\beta(h),\\\\\\\\\\\\beta'(s)&=\\\\tilde{A}\\\\big(s,\\\\xi(s),\\\\varphi\\\\big)\\\\beta(s)+B_\\\\text{int}\\\\big(-s,\\\\xi(s)\\\\big),\\\\\\\\\\\\beta(0)&=B_0\\\\big(\\\\xi(0)\\\\big),\\\\\\\\\\\\xi'(s)&=f\\\\big(\\\\xi(s)\\\\big)+B_1\\\\big(\\\\xi(s)\\\\big)\\\\varphi(s-h)otag\\\\\\\\\\t&\\\\phantom{=\\\\;}+\\\\int_{-h}^{-s}B_\\\\textrm{int}\\\\big(\\\\theta,\\\\xi(s)\\\\big)\\\\varphi(s+\\\\theta)\\\\,d\\\\theta,\\\\\\\\\\\\xi(h)&=y,\\\\\\\\\\\\tilde{A}(s,\\\\xi,\\\\varphi)&=A(\\\\xi)+\\\\sum_{i=1}^m\\\\mathcal{B}_1^i(\\\\xi)\\\\varphi_i(s-h)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\sum_{i=1}^m\\\\int_{-h}^{-s}\\\\mathcal{B}_\\\\text{int}^i(\\\\theta,\\\\xi)\\\\varphi_i(s+\\\\theta)\\\\,d\\\\theta\\\\end{aligned}\",\n u\"\\\\begin{aligned}\\\\xi'(s)&=f\\\\big(\\\\xi(s)\\\\big)+B_1\\\\big(\\\\xi(s)\\\\big)u(t+s-h)onumber\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\int_{-h}^{-s}B_\\\\text{int}\\\\big(\\\\theta,\\\\xi(s)\\\\big)u(t+s+\\\\theta)\\\\,d\\\\theta,\\\\\\\\\\\\xi(0)&=x(t).\\\\end{aligned}\",\n u\"\\\\begin{aligned}\\\\tilde{\\\\xi}'(s)&=f\\\\big(\\\\tilde{\\\\xi}(s)\\\\big)+B_1\\\\big(\\\\tilde{\\\\xi}(s)\\\\big)u(t+\\\\Delta+s-h)onumber\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\int_{-h}^{-s}B_\\\\text{int}\\\\big(\\\\theta,\\\\tilde{\\\\xi}(s)\\\\big)u(t+\\\\Delta+s+\\\\theta)\\\\,d\\\\theta,\\\\\\\\\\\\tilde{\\\\xi}(0)&=x(t+\\\\Delta).\\\\end{aligned}\",\n u'\\\\zeta(0)=x(t+\\\\Delta)-\\\\xi(\\\\Delta)=B_0\\\\big(\\\\xi(0)\\\\big)u(t)\\\\Delta+o(\\\\Delta),',\n u\"\\\\begin{aligned}\\\\zeta'(s)&=\\\\tilde{\\\\xi}'(s)-\\\\xi'(s+\\\\Delta)onumber\\\\\\\\\\t&=f\\\\big(\\\\tilde{\\\\xi}(s)\\\\big)-f\\\\big(\\\\xi(s+\\\\Delta)\\\\big)onumber\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\Big(B_1\\\\big(\\\\tilde{\\\\xi}(s)\\\\big)-B_1\\\\big(\\\\xi(s+\\\\Delta)\\\\big)\\\\Big)u(t+\\\\Delta+s-h)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\int_{-h}^{-s}B_\\\\text{int}\\\\big(\\\\theta,\\\\tilde{\\\\xi}(s)\\\\big)u(t+\\\\Delta+s+\\\\theta)\\\\,d\\\\thetaotag\\\\\\\\\\t&\\\\phantom{=}\\\\:-\\\\int_{-h}^{-s-\\\\Delta}B_\\\\text{int}\\\\big(\\\\theta,\\\\xi(s+\\\\Delta)\\\\big)u(t+\\\\Delta+s+\\\\theta)\\\\,d\\\\thetaonumber\\\\\\\\\\t&=A\\\\big(\\\\xi(s)\\\\big)\\\\zeta(s)+\\\\sum_{i=1}^m\\\\mathcal{B}_1^i\\\\big(\\\\xi(s)\\\\big)\\\\zeta(s)u_i(t+s-h)otag\\\\\\\\\\t&\\\\phantom{=}\\\\:+\\\\sum_{i=1}^m\\\\int_{-h}^{-s}\\\\mathcal{B}_\\\\text{int}^i\\\\big(\\\\theta,\\\\xi(s)\\\\big)\\\\zeta(s)u_i(t+s+\\\\theta)\\\\,d\\\\thetaotag\\\\\\\\\\t&\\\\phantom{=}\\\\:+B_\\\\text{int}\\\\big(-s,\\\\xi(s)\\\\big)u(t)\\\\Delta+o(\\\\Delta)otag\\\\\\\\\\t&=\\\\tilde{A}\\\\big(s,\\\\xi(s),u_t\\\\big)\\\\zeta(s)+B_\\\\text{int}\\\\big(-s,\\\\xi(s)\\\\big)u(t)\\\\Delta+o(\\\\Delta).\\\\end{aligned}\",\n u'\\\\begin{aligned}\\\\zeta(h-\\\\Delta)&=\\\\beta(h)u(t)\\\\Delta+o(\\\\Delta).\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\frac{y(t+\\\\Delta)-y(t)}{\\\\Delta}&=\\\\frac{\\\\tilde{\\\\xi}(h)-\\\\xi(h)}{\\\\Delta}onumber\\\\\\\\\\t&=\\\\frac{\\\\tilde{\\\\xi}(h)-\\\\tilde{\\\\xi}(h-\\\\Delta)+\\\\zeta(h-\\\\Delta)}{\\\\Delta}onumber\\\\\\\\\\t&=f\\\\big(y(t)\\\\big)+B\\\\big(y(t),u_t\\\\big)u(t)+\\\\frac{o(\\\\Delta)}{\\\\Delta},\\\\end{aligned}',\n u'\\\\begin{aligned}m_{v_0}\\\\Verty\\\\Vert^2\\\\leqv_0(y)\\\\leqM_{v_0}\\\\Verty\\\\Vert^2,\\\\\\\\w_0(y)\\\\geqm_{w_0}\\\\Verty\\\\Vert^2,\\\\\\\\\\\\Vert\\\\kappa(y,\\\\varphi)\\\\Vert\\\\leqM_\\\\kappa\\\\Verty\\\\Vert,\\\\\\\\\\\\big(f(y)+B(y,\\\\varphi)\\\\kappa(y,\\\\varphi)\\\\big)^Tablav_0(y)\\\\leq\\t-w_0(y),\\\\end{aligned}',\n u'u(t)=\\\\kappa\\\\big(Y(x,u_t),u_t\\\\big);',\n u'\\\\big(x(t),u_t\\\\big)\\\\in\\\\mathcal{O}\\\\left(\\\\sqrt{\\\\frac{m_v}{M_v}}\\\\frac{R}{\\\\rho}\\\\right),',\n u'\\\\begin{aligned}m_v&=\\\\frac{1}{2\\\\rho^2}\\\\min\\\\big\\\\lbracem_{v_0},\\\\gammae^{-\\\\sigmah},\\t\\\\rho^2\\\\gammae^{-\\\\sigmah}\\\\big\\\\rbrace,\\\\\\\\M_v&=\\\\gamma+\\\\rho^2M_{v_0},\\\\\\\\\\\\gamma&=\\\\frac{m_{w_0}}{2M_\\\\kappa^2},\\\\\\\\\\\\sigma&=\\\\frac{m_{w_0}}{2M_{v_0}};\\\\end{aligned}',\n u'\\\\Vertx(t)\\\\Vert^2+\\\\Vertu_t\\\\Vert^2\\\\leq\\t\\\\frac{M_v}{m_v}e^{-\\\\sigmat}\\\\big(\\t\\t\\\\Vertx(0)\\\\Vert^2+\\\\Vertu_0\\\\Vert^2\\t\\\\big).',\n u'v(x,\\\\varphi)=v_0\\\\big(Y(x,\\\\varphi)\\\\big)+\\t\\\\gamma\\\\int_{-h}^0e^{\\\\sigma\\\\theta}\\\\Vert\\\\varphi(\\\\theta)\\\\Vert^2\\\\,d\\\\theta.',\n u'm_v\\\\big(\\\\Vertx\\\\Vert^2+\\\\Vert\\\\varphi\\\\Vert^2\\\\big)\\\\leq\\tv(x,\\\\varphi)\\\\leq\\tM_v\\\\big(\\\\Vertx\\\\Vert^2+\\\\Vert\\\\varphi\\\\Vert^2\\\\big)',\n u'v(t)=v\\\\big(x(t),u_t\\\\big).',\n u'\\\\begin{aligned}\\\\dot{v}(t)&\\\\leq\\t\\\\big(-m_{w_0}+\\\\gammaM_\\\\kappa^2\\\\big)\\\\big\\\\VertY\\\\big(x(t),u_t\\\\big)\\\\big\\\\Vert^2onumber\\\\\\\\&\\\\phantom{\\\\leq}\\\\:-\\\\sigma\\\\gamma\\\\int_{-h}^0e^{\\\\sigma\\\\theta}\\t\\\\Vertu(t+\\\\theta)\\\\Vert^2\\\\,d\\\\thetaonumber\\\\\\\\&\\\\leq-\\\\sigmav(t).\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\Vertablav_0(y)\\\\Vert\\\\leqM_{ablav_0}\\\\Verty\\\\Vert,\\\\\\\\f^T(y)ablav_0(y)-k\\\\VertB^Tablav_0(y)\\\\Vert^2\\\\leq-w_0(y)\\\\end{aligned}',\n u'\\\\kappa(y,\\\\varphi)=-kB^T(y,\\\\varphi)ablav_0(y)',\n u'M_\\\\kappa=|k|\\\\max_{B\\\\in\\\\mathbb{B}}\\\\VertB\\\\VertM_{ablav_0}.',\n u'\\\\dot{x}(t)=f\\\\big(x(t)\\\\big)+b_0u(t)+b_1u(t-h)+\\\\int_{-h}^0b_\\\\text{int}(\\\\theta)u(t+\\\\theta)\\\\,d\\\\theta',\n u'\\\\kappa(y,\\\\varphi)=\\\\frac{-f(y)-y}{B(y,\\\\varphi)}.',\n u'\\\\left\\\\lbrace\\\\begin{array}{l}\\t\\\\dot{x}_1(t)=x_2^2(t)+u(t-h),\\\\\\\\\\t\\\\dot{x}_2(t)=x_2(t)+u(t)\\\\end{array}\\\\right.',\n u'\\\\begin{aligned}y_1&=x_1+\\\\frac{e^{2h}-1}{2}x_2^2+\\\\int_{-h}^0u(t+\\\\theta)\\\\,d\\\\theta,\\\\\\\\y_2&=e^hx_2\\\\end{aligned}',\n u'\\\\left\\\\lbrace\\\\begin{array}{l}\\t\\\\dot{y}_1=y_2^2+\\\\big(1+\\\\big(e^h-e^{-h}\\\\big)y_2\\\\big)u,\\\\\\\\\\t\\\\dot{y}_2=y_2+e^hu.\\\\end{array}\\\\right.',\n u'\\\\begin{aligned}z_1&=y_1-e^{-h}y_2+\\\\frac{e^{-2h}-1}{2}y_2^2,\\\\\\\\z_2&=e^{-h}y_2,\\\\\\\\u&=-2z_2+\\\\tilde{u}\\\\end{aligned}',\n u'\\\\left\\\\lbrace\\\\begin{array}{l}\\t\\\\dot{z}_1=z_2^2-z_2,\\\\\\\\\\t\\\\dot{z}_2=-z_2+\\\\tilde{u}.\\\\end{array}\\\\right.',\n u'V(z)=\\\\big(z_1+\\\\tfrac{1}{2}z_2(z_2-2)\\\\big)^2+z_2^2.',\n u'\\\\dot{V}=-2z_2^2+\\\\frac{\\\\partialV}{\\\\partialz_2}\\\\tilde{u}',\n u'\\\\tilde{u}=-\\\\frac{\\\\partialV}{\\\\partialz_2}',\n u'\\\\begin{aligned}z_1&=x_1-x_2+\\\\int_{-h}^0u(t+\\\\theta)\\\\,d\\\\theta,\\\\\\\\z_2&=x_2,\\\\\\\\u&=-2x_2+\\\\tilde{u}.\\\\end{aligned}',\n u'\\\\left\\\\lbrace\\\\begin{array}{l}\\t\\\\dot{x}_1(t)=x_2(t),\\\\\\\\\\t\\\\dot{x}_2(t)=\\\\sinx_1(t)+u(t)+u(t-h),\\\\quadh=\\\\pi/4.\\\\end{array}\\\\right.',\n u'f(x)=\\\\begin{pmatrix}\\tx_2\\\\\\\\\\t\\\\sinx_1\\\\end{pmatrix},\\\\quadB_0=B_1=\\\\begin{pmatrix}\\t0\\\\\\\\\\t1\\\\end{pmatrix}.',\n u'A(x)=\\\\begin{pmatrix}\\t0&1\\\\\\\\\\t\\\\cosx_1&0\\\\end{pmatrix},\\\\quadM_f=1,\\\\quadR=\\\\infty.',\n u\"\\\\begin{aligned}\\\\beta'(s)&=A\\\\big(\\\\xi(s)\\\\big)\\\\beta(s),\\\\\\\\\\\\beta(0)&=\\\\begin{pmatrix}\\t0\\\\\\\\1\\\\end{pmatrix}.\\\\end{aligned}\",\n u'\\\\begin{aligned}\\\\frac{d}{ds}\\\\big(\\\\beta_1^2+\\\\beta_2^2\\\\big)&\\\\in\\\\big[0,2\\\\big(\\\\beta_1^2+\\\\beta_2^2\\\\big)\\\\big],\\\\\\\\\\\\frac{d}{ds}\\\\left(\\\\frac{\\\\beta_1}{\\\\beta_2}\\\\right)&\\\\in\\\\left[\\t1-\\\\left(\\\\frac{\\\\beta_1}{\\\\beta_2}\\\\right)^2,\\t1+\\\\left(\\\\frac{\\\\beta_1}{\\\\beta_2}\\\\right)^2\\\\right]\\\\end{aligned}',\n u'\\\\begin{aligned}\\\\beta_1^2(h)+\\\\beta_2^2(h)&\\\\in\\\\Big[1,e^{2h}\\\\Big],\\\\\\\\\\\\frac{\\\\beta_1(h)}{\\\\beta_2(h)}&\\\\in\\\\big[\\\\tanhh,\\\\tanh\\\\big],\\\\end{aligned}',\n u'v_0(y)=y^TVy',\n u'2f^T(y)Vy-4k(Vy)^TBB^TVy\\\\leq-w_0(y).',\n u'f(y)=F(y)y,',\n u'\\\\begin{aligned}F(y)=\\\\begin{pmatrix}\\t0&1\\\\\\\\\\t\\\\alpha(y)&0\\\\end{pmatrix},\\\\\\\\\\\\alpha(y)=\\\\frac{\\\\siny_1}{y_1}\\\\in[-0.22,1],\\\\end{aligned}',\n u'V^{-1}F^T(y)+F(y)V^{-1}-4kBB^T',\n u'\\\\kappa(y,\\\\varphi)=-B^T(y,\\\\varphi)y.',\n u'\\\\int_a^b{f^p(x)dx\\\\geqslant}\\\\left(\\\\int_a^b{f(x)dx}\\\\right)^{p-1}',\n u'\\\\int_a^b{f^{p+2}(x)dx\\\\geqslant}\\\\frac{1}{{(b-a)^{p-1}}}\\\\left(\\\\int_a^b{f(x)dx}\\\\right)^{p+1}.',\n u'\\\\int_a^b{f^{p+2}(x)d_qx\\\\geqslant}\\\\frac{1}{{(b-a)^{p-1}}}\\\\left(\\\\int_a^b{f(qx)d_qx}\\\\right)^{p+1}.',\n u'\\\\int_a^b{f^t(x)dx-}\\\\left({\\\\int_a^b{f(x)dx}}\\\\right)^{t-1}\\\\geqslantf^{t-1}(a)\\\\int_a^b{f(x)dx}.',\n u'\\\\int_a^b{f^{p+2}(x)dx-}\\\\frac{1}{{(b-a)^{p-1}}}\\\\left(\\\\int_a^b{f(x)dx}\\\\right)^{p+1}\\\\geqslantf^{p+1}(a)\\\\int_a^b{f(x)dx}.',\n u'\\\\sigma(t)=\\\\inf\\\\left\\\\{{s\\\\in{\\\\mathbb{T}}:s>t}\\\\right\\\\},',\n u'\\\\rho(t)=\\\\sup\\\\left\\\\{{s\\\\in{\\\\mathbb{T}}:s\n\n\n\n\n```python\ndictionary\n```\n\n\n\n\n \n\n\n\n\n```python\nq = Query(index, docs, dictionary, tokenize_latex, [\"neighbor\", \"similarity_score\"])\nq.query(\"\\\\frac\")\n```\n\n 2017-12-01 11:17:28,732 : INFO : creating matrix with 4 documents and 44 features\n 2017-12-01 11:17:28,736 : INFO : creating dense shard #0\n 2017-12-01 11:17:28,741 : INFO : saving index shard to index/.0\n 2017-12-01 11:17:28,745 : INFO : saving MatrixSimilarity object under index/.0, separately None\n 2017-12-01 11:17:28,748 : INFO : saved index/.0\n 2017-12-01 11:17:28,751 : INFO : loading MatrixSimilarity object from index/.0\n 2017-12-01 11:17:28,752 : INFO : loaded index/.0\n\n\n\n\n\n {'neighbors': [{'neighbor': {'data': u'\\\\begin{aligned}\\\\min_{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\gamma\\\\|L\\\\|_{1}+\\\\lambda\\\\|L\\\\|^{2}_{F}\\\\\\\\\\\\end{aligned}',\n 'fmt': 'math'},\n 'similarity_score': {'data': 0.0750708281993866}},\n {'neighbor': {'data': u'\\\\begin{aligned}\\\\min_{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\mu\\\\sum_{k=1}^{K}\\\\sum_{g=1}^{G}\\\\|s_{k}^{g}\\\\|_{2}\\\\\\\\\\\\end{aligned}',\n 'fmt': 'math'},\n 'similarity_score': {'data': 0.061607733368873596}},\n {'neighbor': {'data': u'\\\\begin{aligned}\\\\min_{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\mu\\\\sum_{k=1}^{K}\\\\sum_{g=1}^{G}\\\\|s_{k}^{g}\\\\|_{2}+\\\\gamma\\\\|L\\\\|_{1}+\\\\lambda\\\\|L\\\\|^{2}_{F}\\\\\\\\\\\\end{aligned}',\n 'fmt': 'math'},\n 'similarity_score': {'data': 0.052263256162405014}}]}\n\n\n\n\n```python\nfrom mathviz_hopper.src.table import Table\nt = Table(q)\nt.print_ipython()\n\n# TODO: lambda function to convert each column\n# Schema:\n# also, enable non-autocomplete selections (the models should be able to handle this)\n# also, add a warning if the settings are still loading, and other notifications.\n# Data: [{Column A: {name: A, index: [], filter_func: lambda x : f(x)}} , {Column B: {name: B, index: [], filter_func: lambda x : f(x)}} \n```\n\n Bottle v0.13-dev server starting up (using MyWSGIRefServer())...\n Listening on http://localhost:8081/\n Hit Ctrl-C to quit.\n \n\n\n\nReact App
\n\n\n 127.0.0.1 - - [01/Dec/2017 11:17:30] \"GET /settings HTTP/1.1\" 200 1007\n\n\n\n```python\nimport requests\nr = requests.post('http://localhost:8081/query', json={\"query\": \"\\\\begin{equation}\\n\\\\Phi_{z}(L) = \\\\sum_{i=1}^{N} \\\\frac{1}{C_{i} \\\\times V_{\\\\rm max, i}} ,\\n\\\\label{EQ1}\\n\\\\end{equation}\\n\"})\n```\n\n 127.0.0.1 - - [01/Dec/2017 11:17:30] \"POST /query HTTP/1.1\" 200 915\n\n\n\n```python\nr.json()\n```\n\n\n\n\n {u'neighbors': [{u'neighbor': {u'data': u'\\\\begin{aligned}\\\\min_{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\gamma\\\\|L\\\\|_{1}+\\\\lambda\\\\|L\\\\|^{2}_{F}\\\\\\\\\\\\end{aligned}',\n u'fmt': u'math'},\n u'similarity_score': {u'data': 0.2967531681060791}},\n {u'neighbor': {u'data': u'\\\\begin{aligned}\\\\min_{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\mu\\\\sum_{k=1}^{K}\\\\sum_{g=1}^{G}\\\\|s_{k}^{g}\\\\|_{2}\\\\\\\\\\\\end{aligned}',\n u'fmt': u'math'},\n u'similarity_score': {u'data': 0.29066944122314453}},\n {u'neighbor': {u'data': u'\\\\begin{aligned}\\\\min_{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\mu\\\\sum_{k=1}^{K}\\\\sum_{g=1}^{G}\\\\|s_{k}^{g}\\\\|_{2}+\\\\gamma\\\\|L\\\\|_{1}+\\\\lambda\\\\|L\\\\|^{2}_{F}\\\\\\\\\\\\end{aligned}',\n u'fmt': u'math'},\n u'similarity_score': {u'data': 0.2799034118652344}}]}\n\n\n\n\n```python\nimport requests\nr = requests.get('http://localhost:8081/settings')\n```\n\n 127.0.0.1 - - [30/Nov/2017 14:03:54] \"GET /settings HTTP/1.1\" 200 1007\n\n\n\n```python\nr.json()\n```\n\n\n\n\n {u'columns': [{u'Header': u'neighbor', u'accessor': u'neighbor'},\n {u'Header': u'similarity_score', u'accessor': u'similarity_score'}],\n u'docs': {u'\\\\': {u'b': {u'e': {u'g': {u'i': {u'n': {u'{': {u'a': {u'l': {u'i': {u'g': {u'n': {u'e': {u'd': {u'}': {u'\\\\': {u'm': {u'i': {u'n': {u'_': {u'{': {},\n u'{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\gamma\\\\|L\\\\|_{1}+\\\\lambda\\\\|L\\\\|^{2}_{F}\\\\\\\\\\\\end{aligned}': {u'full_word': 1},\n u'{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\mu\\\\sum_{k=1}^{K}\\\\sum_{g=1}^{G}\\\\|s_{k}^{g}\\\\|_{2}+\\\\gamma\\\\|L\\\\|_{1}+\\\\lambda\\\\|L\\\\|^{2}_{F}\\\\\\\\\\\\end{aligned}': {u'full_word': 1},\n u'{L,S}\\\\sum_{m=1}^{M}\\\\sum_{i=1}^{N_{m}}&\\\\frac{1}{2}[max(0,1-Y_{m}^{i}(Ls^{m})^{T}X_{m}^{i})]^{2}\\\\\\\\&+\\\\mu\\\\sum_{k=1}^{K}\\\\sum_{g=1}^{G}\\\\|s_{k}^{g}\\\\|_{2}\\\\\\\\\\\\end{aligned}': {u'full_word': 1}}}}}},\n u'w': {u'^': {u'{': {u'm': {u'}': {u'=': {},\n u'=Ls^{m}\\\\end{aligned}': {u'full_word': 1}}}}}}}}}}}}}}}}}}}}}},\n u'port': 8081}\n\n\n\n\n```python\n\ndef insert(st, trie):\n i = 0\n for s in st:\n if s not in trie.keys(): \n trie[s] = {}\n if i == 20:\n break\n trie = trie[s]\n i+=1\n \n if i == 20: \n trie[st[i:]] = {}\n trie = trie[st[i:]]\n trie[\"full_word\"] = 1\n \n \ndef construct_trie(list_of_str):\n trie = {}\n for st in list_of_str:\n insert(st, trie)\n return trie\n \n```\n\n\n```python\ndocs_trie = construct_trie(clean_docs)\n\n```\n\n\n```python\n\nopts = {\n \"columns\": [\n {\n \"Header\": \"Word\",\n \"accessor\": \"word\"\n },\n {\n \"Header\": \"Similarity\",\n \"accessor\": \"sim\"\n }\n ],\n \"port\": \"8081\",\n \"docs\": docs_trie\n}\n```\n\n\n```python\nimport json\nwith open(\"mathviz_hopper/webpage/mathviz-js-components/public/settings.json\", \"w+\") as f:\n json.dump(opts, f)\n```\n\n\n```python\ndef word_exists(trie, word):\n \n for i, s in enumerate(word): \n if s in trie.keys(): \n trie = trie[s]\n else: return False\n \n if i == 19: \n break\n \n if i == 19:\n s = word[i+1:]\n if s not in trie.keys(): return False\n trie = trie[s]\n\n return True if 'full_word' in trie.keys() else False\n \n \n```\n\n\n```python\nword_exists(trie, \"fdakfkajshdfjkahsdfkjhadfdfdfdffdfdsdjkfhaskj\")\n```\n\n\n```python\ndocs = [\"\".join(eq) for eq in df[\"processed\"].tolist()]\ndocs_trie = construct_trie(docs)\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "8e771236528bb40ab9c3f89c086361c2a4a6387d", "size": 211806, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "examples/example.ipynb", "max_stars_repo_name": "samghelms/mathviz", "max_stars_repo_head_hexsha": "30fe89537379faea4de8c8b568ac6e52e4d15353", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-04-12T07:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T03:31:20.000Z", "max_issues_repo_path": "examples/example.ipynb", "max_issues_repo_name": "samghelms/mathviz", "max_issues_repo_head_hexsha": "30fe89537379faea4de8c8b568ac6e52e4d15353", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2020-03-24T15:41:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T22:06:36.000Z", "max_forks_repo_path": "examples/example.ipynb", "max_forks_repo_name": "samghelms/mathviz", "max_forks_repo_head_hexsha": "30fe89537379faea4de8c8b568ac6e52e4d15353", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 127.1344537815, "max_line_length": 1507, "alphanum_fraction": 0.45193715, "converted": true, "num_tokens": 76990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.30957582814909296}} {"text": "```python\nimport gym\nfrom torch.optim import Adam\nimport torch as th\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nfrom torch import nn\nfrom storage import Buffer\nfrom torch.distributions import Uniform\nfrom torch.distributions import Normal\nfrom torch.nn import functional as f\nfrom copy import deepcopy\nimport random\n```\n\n[Pendulum - OpenAI GYM](https://github.com/openai/gym/wiki/Pendulum-v0)\n\n\n[Pendulum problem](https://www.youtube.com/watch?v=1IoN6yCb21s)\n\n### storage.py\n\n\n```python\nclass Buffer:\n def __init__(self, buffer_size):\n\n self.clear()\n self.buffer_size=buffer_size\n\n def add(self,\n state,\n action,\n reward,\n next_state,\n terminal\n ):\n\n if len(self.states) == self.buffer_size:\n self.clear_earliest_entry()\n\n self.states.append(state)\n self.actions.append(action)\n self.rewards.append(reward)\n self.next_states.append(next_state)\n self.terminals.append(terminal)\n\n\n def clear(self):\n\n self.states = []\n self.actions = []\n self.rewards = []\n self.next_states = []\n self.terminals = []\n\n\n def clear_earliest_entry(self):\n\n self.states = self.states[1:]\n self.actions = self.actions[1:]\n self.rewards = self.rewards[1:]\n self.next_states = self.next_states[1:]\n self.terminals = self.terminals[1:]\n\n\n def random_batch(self, batch_size=None):\n\n combined = list(zip(self.states,\n self.actions,\n self.rewards,\n self.next_states,\n self.terminals))\n\n random.shuffle(combined)\n\n if batch_size is not None:\n combined = combined[:batch_size]\n\n states, actions, rewards, next_states, terminals = zip(*combined)\n\n batch = {}\n batch['states'] = th.stack(states)\n batch['actions'] = th.stack(actions)\n batch['rewards'] = th.stack(rewards)\n batch['next_states'] = th.stack(next_states)\n batch['terminals'] = th.stack(terminals)\n\n return batch\n\n def whole_batch(self,):\n\n batch = {}\n batch['states'] = th.stack(self.states)\n batch['actions'] = th.stack(self.actions)\n batch['rewards'] = th.stack(self.rewards)\n batch['next_states'] = th.stack(self.next_states)\n batch['terminals'] = th.stack(self.terminals)\n\n return batch\n```\n\n### networks.py\n\n\n```python\nclass ValueFunction(nn.Module):\n\n def __init__(\n self,\n input_size,\n ):\n super(ValueFunction, self).__init__()\n self.input_size = input_size\n\n self.fc1 = nn.Linear(self.input_size, 256)\n self.fc2 = nn.Linear(256, 256)\n self.fc3 = nn.Linear(256, 1)\n\n def forward(self, activation):\n activation = f.relu(self.fc1(activation))\n activation = f.relu(self.fc2(activation))\n activation = self.fc3(activation)\n\n return activation\n\nclass GaussianPolicy(nn.Module):\n\n def __init__(\n self,\n output_size,\n input_size,\n max_action,\n min_action,\n soft_clamp_function=None\n ):\n super(GaussianPolicy, self).__init__()\n self.input_size = input_size\n self.output_size = output_size\n self.soft_clamp_function = soft_clamp_function\n self.max_action = max_action\n self.min_action = min_action\n self.max_log_sig = 2\n self.min_log_sig = -20\n\n self.fc1 = nn.Linear(self.input_size, 256)\n self.fc2 = nn.Linear(256, 256)\n self.mu_head = nn.Linear(256, self.output_size)\n self.log_sig_head = nn.Linear(256, self.output_size)\n\n def forward(self, activation):\n\n activation = f.relu(self.fc1(activation))\n activation = f.relu(self.fc2(activation))\n mu = self.mu_head(activation)\n log_sig = self.log_sig_head(activation)\n log_sig = log_sig.clamp(min=self.min_log_sig, max=self.max_log_sig)\n sig = th.exp(log_sig)\n\n return mu, sig\n\n def get_action(self, state, eval_deterministic=False):\n\n mu, sig = self.forward(state)\n if eval_deterministic:\n action = mu\n else:\n gauss = Normal(loc=mu, scale=sig)\n action = gauss.sample()\n action.detach()\n\n action = self.max_action * th.tanh(action / self.max_action)\n return action\n\n def get_action_and_log_prob(self, state):\n\n mu, sig = self.forward(state)\n gauss = Normal(loc=mu, scale=sig)\n action = gauss.sample()\n action.detach()\n action = action.clamp(min=self.min_action, max=self.max_action)\n log_prob = gauss.log_prob(action)\n\n return action, log_prob\n\n def r_sample(self, state):\n\n mu, sig = self.forward(state)\n loc = th.zeros(size=[state.shape[0], 1], dtype=th.float32)\n scale = loc + 1.0\n unit_gauss = Normal(loc=loc, scale=scale)\n gauss = Normal(loc=mu, scale=sig)\n epsilon = unit_gauss.sample()\n action = mu + sig * epsilon\n action = action.requires_grad_()\n action = self.max_action * th.tanh(action / self.max_action)\n log_prob = gauss.log_prob(action.data)\n\n return action, log_prob\n\nclass TanhGaussianPolicy(nn.Module):\n\n def __init__(\n self,\n output_size,\n input_size,\n max_action,\n min_action,\n soft_clamp_function=None\n ):\n super(TanhGaussianPolicy, self).__init__()\n self.input_size = input_size\n self.output_size = output_size\n self.soft_clamp_function = soft_clamp_function\n self.max_action = max_action\n self.min_action = min_action\n self.max_log_sig = 2\n self.min_log_sig = -20\n self.a_diff = 0.5 * (self.max_action - self.min_action)\n self.a_shift = 0.5 * (self.max_action + self.min_action)\n self.epsilon = 1e-6\n\n self.fc1 = nn.Linear(self.input_size, 256)\n self.fc2 = nn.Linear(256, 256)\n self.mu_head = nn.Linear(256, self.output_size)\n self.log_sig_head = nn.Linear(256, self.output_size)\n\n def forward(self, activation):\n\n activation = f.relu(self.fc1(activation))\n activation = f.relu(self.fc2(activation))\n mu = self.mu_head(activation)\n log_sig = self.log_sig_head(activation)\n log_sig = log_sig.clamp(min=self.min_log_sig, max=self.max_log_sig)\n sig = th.exp(log_sig)\n\n return mu, sig\n\n def tanh_function(self, a):\n\n a = self.a_diff * th.tanh(a / self.a_diff) + self.a_shift\n\n return a\n\n def tanh_function_derivative(self, a):\n\n return 1 - (th.tanh(a / self.a_diff) ** 2) + self.epsilon\n\n def get_action(self, state, eval_deterministic=False):\n\n mu, sig = self.forward(state)\n if eval_deterministic:\n action = self.tanh_function(mu)\n else:\n gauss = Normal(loc=mu, scale=sig)\n action = gauss.sample()\n action = self.tanh_function(action)\n\n return action\n\n def get_action_and_log_prob(self, state):\n\n mu, sig = self.forward(state)\n gauss = Normal(loc=mu, scale=sig)\n pre_tanh_action = gauss.sample()\n pre_tanh_log_prob = gauss.log_prob(pre_tanh_action)\n action = self.tanh_function(pre_tanh_action)\n log_prob = pre_tanh_log_prob - th.log(self.tanh_function_derivative(pre_tanh_action))\n\n return action, log_prob\n\n def r_sample(self, state):\n\n mu, sig = self.forward(state)\n loc = th.zeros(size=[state.shape[0], 1], dtype=th.float32)\n scale = loc + 1.0\n unit_gauss = Normal(loc=loc, scale=scale)\n epsilon = unit_gauss.sample()\n pre_tanh_action = mu + sig * epsilon\n action = self.tanh_function(pre_tanh_action)\n\n gauss = Normal(loc=mu, scale=sig)\n pre_tanh_log_prob = gauss.log_prob(pre_tanh_action)\n log_prob = pre_tanh_log_prob - th.log(self.tanh_function_derivative(pre_tanh_action))\n\n return action, log_prob\n```\n\n### Deep Actor-Critic\n\nLet's examine the policy gradient theorem for continuous domains. Recall the reinforcement learning objective, which we write here in full:\n\\begin{align}\nJ(\\theta)=\\int p_0(s)\\int \\pi_\\theta(a\\vert s) Q(a,s) da ds. \\label{eq:rl_objective}\n\\end{align}\n\n+ Actor-Critic : Learn Q-function\n\n\\begin{align}\nJ(\\theta)=\\int p_0(s) \\int \\pi_\\theta(a\\vert s) Q_{\\omega}(a, s) dads.\n\\end{align}\n\n+ Add baseline (Value Function)\n\\begin{align}\nA_{\\omega}(a, s) = Q_{\\omega}(a, s) - V_{\\omega}(s)\n\\end{align}\n\\begin{align}\n\\nabla_\\theta J(\\theta)= \\nabla_\\theta \\int p_0(s) \\int \\pi_\\theta(a\\vert s) A_{\\omega}(a, s) dads.\n\\end{align}\n\n+ Add more exploration\n\n\\begin{align}\n\\nabla_\\theta J(\\theta)= \\nabla_\\theta \\int p_0(s) \\int \\pi_\\theta(a\\vert s) \\left(A_{\\omega}(a, s) -\\log\\pi_\\theta(a\\vert s)\\right) dads.\n\\end{align}\n\nII.2a) Why does the additional entropy term in encourages exploration? Hint: What happens when the policy is very confident about a particular action? What about when all actions have equal probability?\nTaking derivatives of entropy objective using the policy gradient theorem with the log-derivative trick then yields the gradient update:\n\\begin{align}\n\\nabla_\\theta J(\\theta)=&\\int \\rho^\\pi(s)\\nabla_\\theta \\int \\pi_\\theta(a\\vert s) \\left(A_{\\omega}(a, s) -\\log\\pi_\\theta(a\\vert s)\\right) dads, \\\\\n=&\\mathbb{E}_{s\\sim\\rho^\\pi(s), a\\sim\\pi_\\theta(a\\vert s)}\\Big[\\nabla_\\theta\\Big(\\log\\pi_\\theta(a\\vert s) \\left(A_{\\omega}(a, s)-\\log\\pi_\\theta(a\\vert s)\\right)\\Big)\\Big]. \\label{eq:entropy_expectation}\n\\end{align}\nII.2b) Implement the score function gradient update with entropy as derived above, uncommenting line to allow gradient updates to the policy. If it is implemented correctly, you should start to see the average test return rise above -1000 for a least one epoch by 25 epochs of training. If the agent is training, remove the entropy term and test for 1 trial to show that it doesn't learn to improve it's policy within 30 epochs. Then let it run for the full 5 trials with the entropy term and move on to the next part while it completes (it should take around 20 minutes).\n\n\n```python\nclass ActorCritic:\n def __init__(\n self,\n policy,\n qf,\n env,\n discount,\n qf_optimiser,\n policy_optimiser,\n max_evaluation_episode_length=200,\n num_evaluation_episodes=5,\n num_training_episode_steps=1000,\n batch_size=128,\n buffer_size = 10000,\n eval_deterministic = True,\n training_on_policy = False,\n vf=None,\n vf_optimiser=None\n ):\n\n self.policy = policy\n self.qf = qf\n self.vf = vf\n self.target_vf = deepcopy(vf)\n self.tau = 1e-2\n self.vf_optimiser = vf_optimiser\n self.qf_optimiser = qf_optimiser\n self.policy_optimiser = policy_optimiser\n self.env = env\n self.discount = discount\n self.batch_size = batch_size\n self.max_evaluation_episode_length = max_evaluation_episode_length\n self.num_evaluation_episodes = num_evaluation_episodes\n self.num_training_episode_steps = num_training_episode_steps\n self.training_on_policy = training_on_policy\n self.buffer = Buffer(buffer_size=buffer_size)\n self.loss = nn.MSELoss()\n self.pretraining_policy = Uniform(high=th.Tensor([policy.max_action]), low=th.Tensor([policy.min_action]))\n self.eval_deterministic = eval_deterministic\n\n self.R_av = None\n self.R_tot = 0\n\n def reset(self):\n self.state = th.from_numpy(self.env.reset()).float()\n\n def evaluate(self, render=False):\n\n total_return = 0\n\n for _ in range(self.num_evaluation_episodes):\n state = th.from_numpy(self.env.reset()).float()\n episode_return = 0\n\n for _ in range(self.max_evaluation_episode_length):\n action = self.policy.get_action(state, self.eval_deterministic)\n action = np.array([action.item()])\n\n if render:\n self.env.render()\n state, reward, terminal, _ = self.env.step(action)\n state = th.from_numpy(state).float()\n\n episode_return += reward\n\n if terminal:\n break\n\n total_return += episode_return\n\n self.average_return = total_return/self.num_evaluation_episodes\n\n def sample_episode(self, exploration_mode=False):\n\n self.reset()\n state = self.state\n\n for _ in range(self.num_training_episode_steps):\n\n if exploration_mode:\n action = self.pretraining_policy.sample()\n else:\n action = self.policy.get_action(state)\n next_state, reward, terminal, _ = self.env.step(action.numpy())\n next_state = th.from_numpy(next_state).float()\n reward = th.Tensor([reward])\n terminal = th.Tensor([terminal])\n\n self.buffer.add(state=state,\n action=action,\n reward=reward,\n next_state=next_state,\n terminal=terminal)\n\n state = next_state\n if terminal:\n self.reset()\n state = self.state\n\n def env_step(self):\n\n state = self.state\n action = self.policy.get_action(state)\n next_state, reward, terminal, _ = self.env.step(action.numpy())\n next_state = th.from_numpy(next_state).float()\n reward = th.Tensor([reward])\n terminal = th.Tensor([terminal])\n\n self.buffer.add(state=state,\n action=action,\n reward=reward,\n next_state=next_state,\n terminal=terminal)\n\n self.state = next_state\n\n def train_score(self):\n if self.training_on_policy:\n batch = self.buffer.whole_batch()\n self.buffer.clear()\n else:\n batch = self.buffer.random_batch(self.batch_size)\n states = batch['states']\n actions = batch['actions']\n rewards = batch['rewards']\n next_states = batch['next_states']\n terminals = batch['terminals']\n\n new_actions, log_pis = self.policy.get_action_and_log_prob(states)\n values = self.vf(states)\n state_actions = th.cat((states, actions), 1)\n q_values = self.qf(state_actions)\n next_values = self.target_vf(next_states)\n new_state_actions = th.cat((states, new_actions), 1)\n new_q_values = self.qf(new_state_actions)\n\n \"\"\"\n Value (Critic) Losses:\n \"\"\"\n v_targets = new_q_values\n vf_loss = (v_targets.detach() - values).pow(2).mean()\n\n q_targets = rewards + self.discount * (1 - terminals) * next_values\n qf_loss = (q_targets.detach() - q_values).pow(2).mean()\n\n\n \"\"\"\n Policy (Actor) Losses: TO COMPLETE IN EXERCISE II.2b\n \"\"\"\n advantage = new_q_values - values\n policy_loss = (log_pis * (log_pis - advantage.detach())).mean()\n\n \"\"\"\n Gradient Updates\n \"\"\"\n self.qf_optimiser.zero_grad()\n qf_loss.backward()\n self.qf_optimiser.step()\n\n self.vf_optimiser.zero_grad()\n vf_loss.backward()\n self.vf_optimiser.step()\n\n self.policy_optimiser.zero_grad()\n policy_loss.backward()\n self.policy_optimiser.step()\n\n self.soft_update()\n\n def train_reparametrisation(self):\n\n if self.training_on_policy:\n batch = self.buffer.whole_batch()\n self.buffer.clear()\n else:\n batch = self.buffer.random_batch(self.batch_size)\n states = batch['states']\n actions = batch['actions']\n rewards = batch['rewards']\n next_states = batch['next_states']\n terminals = batch['terminals']\n\n state_actions = th.cat((states, actions), 1)\n q_pred = self.qf(state_actions)\n v_pred = self.vf(states)\n new_actions, log_pis = self.policy.r_sample(states)\n\n \"\"\"\n Value (Critic) Losses:\n \"\"\"\n target_v_values = self.target_vf(next_states)\n q_target = rewards + (1. - terminals) * self.discount * target_v_values\n qf_loss = self.loss(q_pred, q_target.detach())\n\n new_state_actions = th.cat((states, new_actions), 1)\n q_new_actions = self.qf(new_state_actions)\n v_target = q_new_actions\n vf_loss = self.loss(v_pred, v_target.detach())\n\n \"\"\"\n Policy (Actor) Loss: TO COMPLETE IN EXERCISE II.3c \n \"\"\"\n policy_loss = (log_pis - q_new_actions).mean()\n\n\n \"\"\"\n Gradient Updates\n \"\"\"\n self.qf_optimiser.zero_grad()\n qf_loss.backward()\n self.qf_optimiser.step()\n\n self.vf_optimiser.zero_grad()\n vf_loss.backward()\n self.vf_optimiser.step()\n\n self.policy_optimiser.zero_grad()\n policy_loss.backward()\n self.policy_optimiser.step()\n\n self.soft_update()\n\n\n def soft_update(self):\n for target_param, param in zip(self.target_vf.parameters(), self.vf.parameters()):\n target_param.data.copy_(\n target_param.data * (1.0 - self.tau) + param.data * self.tau\n )\n```\n\n### Exercise II.3: Reducing Variance using the Reparametrisation Trick\n\nEstimators like the score function estimator from II.1 often have very high variance for their gradient updates, even when a baseline is used. We now see how performance can be further improved by using the reparametrisation trick to exploit the low variance properties of using an update with the first order derivative $\\nabla_aQ_\\omega(a,s)$. The results are analogous to those derived for variational auto-encoders (\\href{https://arxiv.org/pdf/1312.6114.pdf}{Kingma and Welling, 2013})\n\nInstead of sampling an action directly from our policy $a\\sim \\pi_\\theta(a\\vert s)$, we sample a variable $\\epsilon$ from a zero-mean Gaussian distribution with standard deviation of unity $\\epsilon\\sim p(\\epsilon)=\\mathcal{N}(0,1)$. An action is then constructed using $a_\\theta=\\tanh{(\\epsilon\\sigma_\\theta + \\mu_\\theta)}$. Although not strictly justified in the case of the classic policy gradient theorem, as we have used function approximators for the value functions, to aid our analysis we can shift the derivative outside of the inner integral:\n\\begin{align}\n\\nabla_\\theta J(\\theta)=\\int\\rho^\\pi(s)\\nabla_\\theta\\int\\pi_\\theta(a\\vert s) (A_\\omega(a,s)-\\log\\pi_\\theta(a\\vert s)\\pi_\\theta(a\\vert s)) da ds \\label{eq:shifted_derivative}\n\\end{align}\n\nII.3a) Using the substitution $a=a_\\theta=\\tanh{(\\epsilon\\sigma_\\theta + \\mu_\\theta)}$, show that derivative can be written as\n\\begin{align}\n\\nabla_\\theta J(\\theta)=\\mathbb{E}_{s\\sim\\rho^\\pi(s), \\epsilon\\sim p(\\epsilon)}\\Big[\\nabla_\\theta(A_\\omega(a_\\theta ,s)-\\log\\pi_\\theta(a_\\theta\\vert s))\\Big], \\label{eq:reparam}\n\\end{align}\nII.3b) Implement the reparametrisation gradient update with entropy as derived in \\cref{eq:reparam2} in the function \\code{train\\_reparametrisation()}. If implemented correctly, you should start to see the average test return rise above -1000 at an earlier epoch than when the score function estimator is used. Compare the performance of your new plot against the score function plot from II.1b by running the file 'plot\\_all.py'.\n\nHints:\n* Don't forget to change \"training\\_mode\" to \"reparam\" before running.\n* \"new\\_actions\" and \"log\\_pis\" have now been calculated for you using the function \"r\\_sample\", sampling $\\epsilon$ first from $p(\\epsilon)$ and then calculating $a_\\theta=\\tanh{(\\epsilon\\sigma_\\theta + \\mu_\\theta)}$. This means that they have dependency on policy parameters $\\theta$.\n* \"q\\_new\\_actions\" now also have dependency on policy parameters $\\theta$, so gradients will automatically flow through these q-values back to the network parameters when \"backward()\" is called.\n\n\n```python\ndef run_experiment(s):\n\n policy = TanhGaussianPolicy(\n max_action=max_action,\n min_action=min_action,\n input_size=state_dim,\n output_size=action_dim\n )\n policy_optimiser = Adam(policy.parameters(), lr=lr)\n\n qf = ValueFunction(\n input_size=state_dim + action_dim,\n )\n qf_optimiser = Adam(qf.parameters(), lr=lr)\n\n vf = ValueFunction(\n input_size=state_dim,\n )\n vf_optimiser = Adam(vf.parameters(), lr=lr)\n\n algorithm = ActorCritic(\n policy=policy,\n policy_optimiser=policy_optimiser,\n qf=qf,\n qf_optimiser=qf_optimiser,\n vf=vf,\n vf_optimiser=vf_optimiser,\n env=env,\n discount=discount\n )\n\n for _ in range(num_pretrain_episodes):\n algorithm.sample_episode(exploration_mode=True)\n\n for e in range(num_epochs):\n\n algorithm.evaluate()\n print('Epoch: {}, Average Test Return: {}'.format(e, algorithm.average_return))\n results[e, s] = algorithm.average_return\n algorithm.reset()\n\n for n in range(num_training_updates_per_epoch):\n algorithm.env_step()\n if training_mode == 'Score':\n algorithm.train_score()\n else:\n algorithm.train_reparametrisation()\n\n\n algorithm.evaluate(render=render_agent)\n print('Epoch: {}, Average Test Return: {}'.format(e+1, algorithm.average_return))\n results[e+1, s] = algorithm.average_return\n```\n\n\n```python\ndef write_to_file(mean, std):\n with open('PartII_{}_{}_trials_{}_epochs.csv'.format(training_mode, number_of_trials, num_epochs), 'w') as resultFile:\n wr = csv.writer(resultFile)\n mean.insert(0, 'Mean Returns')\n std.insert(0, 'Standard Deviation')\n data = [mean, std]\n data = list(map(list, zip(*data)))\n wr.writerows(data)\n```\n\n\n```python\n# Initialise Environment\nenv = gym.make(\"Pendulum-v0\").unwrapped\nmax_action = env.action_space.high[0]\nmin_action = env.action_space.low[0]\nstate_dim = int(env.observation_space.shape[0])\naction_dim = int(env.action_space.shape[0])\n# Options: 'Score' trains the policy using the score function and 'Reparam' trains using the reparametrisation trick.\ntraining_mode = 'Reparam' \nnumber_of_trials = 1\nsave_data = True\nrender_agent = False\n\n# Set parameters\nnum_epochs = 30\nnum_pretrain_episodes = 1\nnum_training_updates_per_epoch = 200\nlr = 3e-4\ndiscount = 0.99\n\n# Initialise data logger\nresults = np.zeros((num_epochs + 1, number_of_trials))\n```\n\n\n```python\nif __name__ == \"__main__\":\n\n for s in range(number_of_trials):\n th.manual_seed(s+1)\n run_experiment(s)\n\n mean_returns = results.mean(axis=1)\n std_returns = results.std(axis=1)\n training_steps = np.linspace(0, num_epochs * num_training_updates_per_epoch, num=num_epochs+1)\n plt.plot(training_steps, mean_returns)\n plt.fill_between(training_steps, mean_returns + std_returns, mean_returns - std_returns, alpha=0.3)\n plt.show()\n\n if save_data:\n write_to_file(mean_returns.tolist(), std_returns.tolist())\n```\n", "meta": {"hexsha": "bc429280b3edad637c6d91cae9008c0bd8ca1e99", "size": 31190, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Machine Learning Summer School 2019 (Moscow, Russia)/tutorials/reinforcement_learning3/part_ii_solution.ipynb", "max_stars_repo_name": "xuedong/rlss2019", "max_stars_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine Learning Summer School 2019 (Moscow, Russia)/tutorials/reinforcement_learning3/part_ii_solution.ipynb", "max_issues_repo_name": "xuedong/rlss2019", "max_issues_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning Summer School 2019 (Moscow, Russia)/tutorials/reinforcement_learning3/part_ii_solution.ipynb", "max_forks_repo_name": "xuedong/rlss2019", "max_forks_repo_head_hexsha": "d7468c2fcf269d8afd6fb0f44993aa9797867944", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6315120712, "max_line_length": 578, "alphanum_fraction": 0.5223789676, "converted": true, "num_tokens": 5541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.30955791734402915}} {"text": "# ModelFlow, A library to manage and solve Models\n\n## Why Model flow?\n**Specify very large (or small) models** as concise and intuitive equations. The python code to calculate/solve the model is automatic generated. The user don't have to do the household chores and can concentrate on the economic content. \n\n**Large models**. 1 million equation and more can be handled. Models with many banks or other agents and granular data can get very large. \n\n**Agile model development** Model are specified at a high level of abstraction and are processed fast. Also solving/calculating models are fast. This makes experiments with model specification agile and fast. \n\n**Get rid of models models implemented in Excel**. Large models in Excel are difficult to maintain, revise and quality check. Excel is also very slow in calculating models. Moreover Excel don't handle models with contemporaneous feedback well. \n\n**Onboarding models and combining from different sources**. Creating a Macro prudential model often entails recycling several models specified in different ways: Excel, Latex, Dynare, Python or other languages. Python's ecosystem makes it possible to transform many different models into ModelFlow models or to wrap them into functions which can be called from ModelFlow models. \n\n**Onboarding data from different sources**. Pythons Pandas Library and other tools are fast and efficient for data management.\n\n**A rich set of analytical tools for model and result analytic** helps to understand the model and its results. \n\n**The user can extend and modify the tools** to her or his needs. All code is in Python and the core is quite small. \n\n\n## Use ModelFlow on your local machine\n\nThe easy way to install ModelFlow libraries are located in a Github repo which you can download. It is located here:\n\n[https://github.com/IbHansen/ModelFlow2](https://github.com/IbHansen/ModelFlow2) \n\n\nYou need Python 3.8+ with associated libraries. The easy way to get Python is to install Anaconda Python from here:\n\n[https://www.anaconda.com/distribution](https://www.anaconda.com/distribution)\n\n\n\n## Run this notebook on a virtual machine. \n\n \n\nTo get access to the jupyter notebooks in the repo, run this: \n\nhttps://mybinder.org/v2/gh/Ibhansen/ModelFlow2/master\n\nThis will open a Home tab in your browser. The notebooks are the .ipynb files. \n\nThe virtual machine is created using [Binder](https://mybinder.readthedocs.io/en/latest) .\n\nUsing the toolbar you can toggle the Table of content, and you can activate the RISE. RISE will allow you to view the notebook as a slideshow. \n\nTo benefit fully of the notebook look into how Jupyter works:\n\nhttps://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html \n\n## Introduction \nThe main purpose of ModelFlow is to bring a model and a data set together. Then the model can be solved, and the results analyzed and\ncompared. The user can do this either with the Python methods that ModelFlow will wrap around the model, or by by using the many datascience tools provided by the Python ecosystem. \n\n**Models can be specified in a high level Business logic language (a Domain Specific language)**. This allows the formulation of a model in a concise and expressive language which is close to the economic of the model. The user can concentrate on the economic or financial content - not the coding of the solution. The code for solving the model is generated by the tool. \n\n - a model can be *simultaneous* or *non-simultaneous*\n - a model can be specified as a normalized model - $y = F(y,x)$,or a general form model - $0=G(y,x)$ \n - simultaneous models can be solved by:\n - Gauss-Seidle or Newton-Raphson algorithmes if no leads - ie the formulas are recurrence \n - Fair-Taylor or stacked Newton-Raphson if the model contains leads \n - The jacobian matrice used by Newton-Raphson solvers will can be calculated either by symbolic differentiation or by numerical differentiation \n - non-simultaneous models will be sequenced and calculated. \n - variables in a model can be scalars or matrices.\n\nIf the\nmodel is not initially specified in the Business logic language, Python\noffers a wide range of possibilities to grab a model and transform it to\nthe Business logic language. Also, models in the form of Matlab\nfunctions can be wrapped and called from ModelFlow. This allows for the recycling and integration models sourced from a number of different origins. \n\nThus a model **flows** through a number of phases, from a formulation in business logic language to a Python program which can solve the model. \n\n**ModelFlow is written in Python**. Python comes \"batteries included\" and is\nthe basis of a very rich ecosystem, which consists of a wide array of\nlibraries. ModelFlow is just another library. It supplements the existing\nlibraries regarding modeling language and solving and allows the use of\nPython as a model management framework.\n\n**Data handling and wrangling is done in the Pandas library**. This\nlibrary is the Swiss army knife of data science in Python. It can import and export data to most systems and it is very powerful in manipulating and transforming data.\nThe core\nelement of Pandas is the *Dataframe*. A Dataframe is a two-dimensional\ntabular data structure. Each *column* consists of cells of the same type\n-- it can be a number, a string, a matrix or another Python data object.This includes matrices and other dataframes. Each *row is indexed.* The index can basically be any type of variable\nincluding dates, which is especially relevant for economic and financial models.\n\n**ModelFlow gives the user tools for more than solving models**. This\nincludes:\n\n- *Visualization* and comparison of results\n\n- *Integration* of models from different sources\n\n- *Analyze the logical structure of a model*. By applying graph theory, \n ModelFlow can find data lineage, find a suitable calculating sequence and trace \n causes of changes through the calculations.\n\n- *Inverting* the model to calculating the necessary instruments to\n achieve a desired target.\n\n- Calculating the *attributions* from input to the results of a model.\n\n- Calculating the *attribution* from input to the result of each\n formula.\n\n- Finding and calculating partial *derivatives* of formulas\n\n- *Integrating user defined python functions* in the Business logic\n language (like optimization, calculating risk weights or to make a matrices consistent with the RAS algorithm )\n\n- *Wrap matlab* models so they can be used in the Business logic\n language.\n\n- *Speed up* solving using \"Just in time compilation\"\n\n- Analyze the model structure through tools from graph theory\n\n- Handle *large models.* 1,000,000 formulas is not a problem.\n\n- Integrate model management in Jupyter notebooks for *agile and user\n friendly model use*\n\n\n**The core code of ModelFlow is small and\ndocumented.** Thus it can easily be modified and expanded to the specific need of the user. *ModelFlow is a toolset*. It can handle models, which conform to the tools.\n\nIf you need a feature or have a model which can't be handled in ModelFlow,\nyou are encouraged to improve ModelFlow. Please share the\nimprovement, other users may have the same need, or can be inspired by\nyour work.\n\nAlso bear in mind that ModelFlow is experimental. It is provided ”as is”, without any representation or warranty of any kind either express or implied. \n\nThe code is located here: [https://github.com/IbHansen/ModelFlow2](https://github.com/IbHansen/ModelFlow2)\n\nThe rest of this document will start with a simple example, then it will go into more detail regarding how to use (some of) the features. \n\n## Import relevant libraries\nHere the nessecary libraries are imported. Imports starting with *model* are \npart of the ModelFlow library \n\n\n```python\n%matplotlib inline\n```\n\n\n```python\nimport matplotlib.pyplot as plt \nimport pandas as pd # Python data science library\nimport numpy as np\nimport re\nimport sys\n\nimport modelclass as mc # ModelFlow, model handeling module \nfrom modelclass import model\nimport modelmanipulation as mp # Module for model text processing\nimport modelpattern as pt\nfrom modelmanipulation import explode\nimport modeldekom as md\nimport modelvis as mv\nimport modelinvert as mi\nimport modelnet as mn \nimport modeldiff as mdif\n```\n\n## Create model equations / formulas \nThe model equations are a Python string. In a simple model the calculations are specified just as formulas. Time is implicit and lags are marked by (-). \n\nEach formula starts with a \"FRML\" and ends with a $. Also each formula has formula options enclosed in <>. In this simple model we don't use any advanced features.\n\nYou will notice, that the formulas do not have to be ordered in the logical calculation sequence. This will be done by ModelFlow. \n\n\n```python\nfmodel = '''\nfrml <> a = c(-1) + b $ \nfrml <> d1 = x + 3 * a(-1)+ c **2 +a $ \nfrml <> d3 = x + 3 * a(-1)+c **3 $ \nFrml <> x = 0.5 * c $'''\n```\n\n## Create a model instance\n**Now we want to take the formulas (equations) and create a devise which can run the model.** This device is an instance of the **model class**. \n\nAfter the creation the instance can solve the model, visualize results and \nprovide information regarding the model \n\n\n\n```python\nmmodel = model(fmodel,modelname = 'My first model')\n```\n\n## Create a Dataframe\n**The model needs some data to run**. So we create a pandas dataframe. \n\nA dataframe is a matrix, where the columns designate variables in the model, and rows are time dimensions. \n\n\n```python\ndf = pd.DataFrame({'B': [1,1,1,1],'C':[1,2,3,6],'E':[4,4,4,4]},index=[2018,2019,2020,2021])\ndf \n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
BCE
2018114
2019124
2020134
2021164
\n
\n\n\n\n## Run the model \n**We can now run the model using the data.** The result is a new dataframe. \n\nIf the dataframe don't contain all the variables from the model, the dataframe will be padded with the missing \nvariables. Their values are set to 0.0. \n\nThe model can be solved for the rows in the dataframe for which it is possible. This means that the maximal lags has to be taken into account. In this example the maximal lag is 1, so the model can be solved from 2019 to 2021. \n\n\n```python\nmmodel(df) \n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
BCED1XAD3
20181.01.04.00.00.00.00.0
20191.02.04.07.01.02.09.0
20201.03.04.019.51.53.034.5
20211.06.04.052.03.04.0228.0
\n
\n\n\n\n## Make a new experiment\nOne experiment is useful, but usually we want to compare the results of several experiments.\n\nSo the C variable is updated to new values, and the model is run again. \n\n\n```python\ndf.C = [4,5,7,9]\ndf.B = [1,2,3,4]\nmmodel(df)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
BCED1XAD3
20181.04.04.00.00.00.00.0
20192.05.04.033.52.56.0127.5
20203.07.04.078.53.58.0364.5
20214.09.04.0120.54.511.0757.5
\n
\n\n\n\n## Visualizing\nA model run returns a dataframe with the results. These can be analyzed and visualized by python libraries like pandas and matplotlib. \n\nHowever, the results are also saved as propertied in the model instance. By using the information regarding both the model and the results a number of tools for visualizing, analyzing and debugging can applied. \n\nPer default the first result dataframe and the last result dataframe are retained in the model instance. The first is called:**basedf** the last is called:**lastdf**. \n\nBy setting or accessing **model.basedf** and **model.lastdf**, these properties can also be set or retrieved by the user.\n\n### Single variable\n\nAll model variable can be accessed with model_instance.variable_name notation. The resulting object will return information regarding the variable. \n \nThe python feature \"Tab-completion\" can be used to select which variable to show. So when the user \npres the tab-key, a list of matching variable names will be displayed, and the user can those\nfrom the list. \n\nFor a single variable there are a number of methods for gaining insight in both the dependencies and the results. If we just give the variable as attribute like in the cell below. We will get a some basic information regarding the variable. \n\n\n```python\nmmodel.D1\n```\n\n\n\n\n Endogeneous: D1: \n Formular: FRML <> D1 = X + 3 * A(-1)+ C **2 +A $\n \n D1: \n A : \n C : \n X : \n \n Values : \n 2019 2020 2021\n Base 7.0 19.5 52.0\n Last 33.5 78.5 120.5\n Diff 26.5 59.0 68.5\n \n Input last run: \n 2019 2020 2021\n A 6.0 8.0 11.0\n A(-1) 0.0 6.0 8.0\n C 5.0 7.0 9.0\n X 2.5 3.5 4.5\n\n\n\nSome methods are available to use after the variable name: One such is **draw**, the next cell shows the parent and child's of the X variable, and also the values of each of the variables. Both in the baseline run (default: the first run of the model) and in the last run of the model. \n\nSo in this model X depends on C, and X is contributing to D1 and D3. \n\nOutput from **draw** can become quite large for complex and deep models. Therefor the user can control both the amount of information for the variables and how many generations the graph has to cover. \n\n\n```python\nmmodel.draw('X',all=1,size=(2,2))\n```\n\n\n \n\n \n\n\n### We can also explain the change in the variable\nHaving two runs of the model, it is useful to find the attribution to the change in values from the first to the second run. This is done by the explain method. \n\nThe width of arrows reflects how much of the change in a variable can be explained by the change in each incoming variable. \n\n\n```python\n_=mmodel.D1.explain(up=2)\n```\n\n\n \n\n \n\n\nThis can become a very busy graph for large models where there are really many nodes. \nLike shocks for all countries in an EBA stress test. So take care what you ask for. \n\nThe output can also be produced in PDF or svg format. These formats are vector based, and it is possible to zoom into a large graph without loosing information. \n\n### Slices of variables\nIn order to make life easy when using models with consistent and structured variable naming conventions wildcards can be used to select the variables to visualize through ModelFlow. \nSome are displayed below. \n\nIf this is not sufficient the whole suite of Python visualization libraries (as Matplotlib, Seaborn, Plotly) can be used on top of the resulting Dataframes. \n\n#### The values\n\n\n```python\n_=mmodel['*'].plot(title='Values')\n```\n\n#### The values\n\n\n```python\n_=mmodel['*'].dif.plot(title='The differences')\n```\n\n#### The differences between the runs, as heatmap\n\n\n```python\n_=mmodel['*'].dif.heat(size=(4,4),title='The differences')\n```\n\n### Structure\nAs the structure of the model is in the model instance, we can visualize the structure of the whole model. \n\n\n```python\nmmodel.drawmodel(size=(2,2))\n```\n\n\n \n\n \n\n\n### The model structure with values \nAlso we can combine the structure and the model in order to get the complete picture. \n\nHowever take care for large models. \n\n\n```python\nmmodel.drawmodel(all=1,size=(2,2))\n```\n\n\n \n\n \n\n\nThis was a quick walk through how to define a simple model, make some mock data, run the model and visualize the structure and the results. \n\nNow we can explore the features of ModelFlow. \n\n## What is a Model in ModelFlow\nModelFlow is created to handle models. The term [**model**](https://en.wikipedia.org/wiki/Model) can mean a lot of different concepts. \n\nThe scope of models handled by ModelFlow is discrete models which is the same for each time frame, can be formulated as mathematical equations and *can* have lagged and leaded variables. This allows the system to handle quite a large range of models.\n\nA model with:\n\n - $\\textbf n$ number of endogeneous variables\n - $\\textbf k$ number of exogeneous variables \n - $\\textbf u$ max lead of endogeneous variables\n - $\\textbf r$ max lag of endogeneous variables \n - $\\textbf s$ max lag of exogeneous variables \n - $t$ time frame (year, quarter, day second or another another unit)\n \ncan be written in two ways, normalized or un-normalized form\n\n### normalized form\n\n\\begin{eqnarray}\ny_t^1 & = & f^1(y_{t+u}^1...,y_{t+u}^n...,y_t^2...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\ny_t^2 & = & f^2(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\n\\vdots \\\\\ny_t^n & = & f^n(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^{n-1}...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^r,x..._{t-s}^1...,x_{t-s}^k)\n\\end{eqnarray}\n\n\nMany stress test, liquidity, macro or other models conforms to this pattern. Or the can easily be transformed to thes pattern. \n\nWritten in matrix notation where $\\textbf{y}_t$ and $\\textbf{x}_t$ are vectors of endogenous/exogenous variables for time t\n\n\\begin{eqnarray} \n\\textbf{y}_t & = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-s})\n\\end{eqnarray}\n\nThe functions are normalized, meaning: \n\n- Each endogenous variable is on the left hand side one time - and only one time.\n- An endogenous variable without lags can **not** be on the right hand side in an equation, which has the variable on the left hand side. \n\n### Un-normalized form\nSome economic models can not easy be specified as normalized formulas. Especially models with equilibrium conditions can more suitable be specified in the more generalized un-normalized form.\n\n\n\\begin{eqnarray}\n0 & = & f^1(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\n0 & = & f^2(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^k,...x_{t-s}^1...,x_{t-s}^k) \\\\\n\\vdots \\\\\n0 & = & f^n(y_{t+u}^1...,y_{t+u}^n...,y_t^1...,y_{t}^n...y_{t-r}^1...,y_{t-r}^n,x_t^1...x_{t}^r,x..._{t-s}^1...,x_{t-s}^k)\n\\end{eqnarray}\n\n\n\nWritten in matrix notation like before:\n\n\\begin{eqnarray} \n\\textbf{0}& = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-s})\n\\end{eqnarray}\n\nThe number of endogenous variables and equations should still be the same.\n\nModelFlow allows variable (the $\\textbf x$'es and the $\\textbf y$'es the to be scalars, matrices, arrays or pandas dataframes.\n\n## Model solution \nFor a normalized model:\n\n\\begin{eqnarray} \n\\textbf{y}_t & = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-r}) \n\\end{eqnarray}\n\na solution is $\\textbf{y}_t^*$ so that:\n\n\n\\begin{eqnarray} \n\\textbf{y}_t^* & = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t^* \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-r}) \n\\end{eqnarray}\n\nFor the un-normalized model:\n\\begin{eqnarray} \n\\textbf{0}& = & \\textbf{F}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-s})\n\\end{eqnarray}\n\n\na solution $\\textbf{y}_t^*$ is \n\n\\begin{eqnarray} \n\\textbf{0} & = & \\textbf{G}(\\textbf{y}_{t+u} \\cdots \\textbf{y}_t^* \\cdots \\textbf{y}_{t-r},\\textbf{x}_t \\cdots \\textbf{x}_{t-r}) \n\\end{eqnarray}\n\nSome models can have more than one solution. In this case the solution can depend on the starting point of the solution algorithm. \n\n## Model derivatives \n\nBoth for solving and for analyzing the causal structure of a model it can be useful to define different matrices of derivatives for a model $\\textbf F()$ like this:\n\n\\begin{align} \n\\textbf{A}_t & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_t^T} \\hphantom{\\hspace{5 mm} i=1, \\cdots , r} \n &\\hspace{1 mm}\\mbox{Derivatives with respect to current endogeneous variables} \\\\ \\\\\n\\textbf{E}_t^i & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_{t-i}^T } \\hspace{5 mm} i=1, \\cdots , r &\\hspace{1 mm}\\mbox{ Derivatives with respect to lagged endogeneous variables } \\\\ \\\\\n\\textbf{D}_t^j & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_{t+j}^T } \\hspace{5 mm} j=1, \\cdots , u &\\hspace{1 mm}\\mbox{ Derivatives with respect to leaded endogeneous variables } \\\\ \\\\\n\\textbf{F}_t^k & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{x}_{t-i} ^T} \\hspace{5 mm} k=0, \\cdots , s &\\hspace{1 mm}\\mbox{ Derivatives with respect to current and lagged exogeneous variables }\\\\ \n\\end{align}\n\nFor un-normalized models the derivative matrices are just the dervatives of $\\textbf G$ instead of $\\textbf F$\n\nSolving the model with a Newton-Raphson method requires the calculation of a matric of derivatives. This is done by creating an additional model which calculates all the non-zero derivatives. The derivative calculation model can be created both by symbolic differentiation or by numerical differentiation. \n\n## Model solutions\n\nThere are numerous methods to solve models (systems) as mentioned above. ModelFlow can apply 3 different types of model solution methods: \n\n 1. If the model has **no contemporaneous feedback**, the equations can be sorted \n [Topological](https://en.wikipedia.org/wiki/Topological_sorting) and then the equations can be calculated in the topological order. This is the same as a spreadsheet would do. \n 2. If the model has **contemporaneous feedback** model is solved with an iterative method. Here variants of well known solution methods are used: \n 1. [Gauss-Seidle](https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method) (**Gauss**) which can handle large systems, is fairly robust and don't need the calculation of derivatives\n 2. [Newthon-Raphson](https://en.wikipedia.org/wiki/Newton%27s_method) (**Newton**) which requires the calculation of derivatives and solving of a large linear system but typically converges in fewer iterations. \n \nNearly all of the models solved by ModelFlow don't contain leaded endogenous variables. Therefor they can be solved one period at a time. For large sparse nonlinear models Gauss works fine. It solves a model quite fast and we don't need the additional handiwork of handling derivatives and large linear systems that Newton methods require. Moreover many models in question do not have smooth derivatives. The order in which the equation are calculated can have a large impact on the convergence speed. \n\nFor some models the Newton algorithm works better. Some models are not able to converge with Gauss-Seidle other models are just faster using Newton. Also the ordering of equations does not matter for the convergence speed. \n\nHowever some models like FRB/US and other with **rational expectations** or **model consistent expectations** contains leaded endogenous variables. Such models typical has to be solved as one system for for all projection periods. In this case, the Gauss variation [Fair-Taylor](https://fairmodel.econ.yale.edu/rayfair/pdf/1983A.PDF) or Stacked-Newton Method. The **stacked Newton** methods can be used in all cases, but if not needed, it will usually use more memory and be slower. \n\n\n**Summary of prefered solution methods**\n\n| Model | No contemporaneous feedback | Contemporaneous feedback | Leaded variables |\n| --- | --- | --- |--- | \n|Normalized | Calculate | Gauss or
Newton | Fair Taylor or
Stacked Newton|\n|Un-normalized | Newton | Newton | Stacked Newton |\n\n\n \n\n### Normalized model\n\n\n#### Calculation, No contemporaneous feedback\n\nIn systems with no lags each period can be solved in succession\nThe equations has to be evaluated in a logical (topological sorted) order. \n\nLet $z$ be all predetermined values: all exogenous variable and lagged endogenous variable.\n\nOrder the $n$ endogeneous variables in topological order.\n \nFor each time period we can find a solution by\n\nfor $i$ = 1 to $n$ \n\n>$y_{i}^{k} = f_i(y_1^{k},\\cdots,y_{i-1}^{k},y_{i+1}^{k-1},\\cdots,y_{n}^{k-1},z)$\n\n\n#### The Gauss-Seidel algorithm. Models with contemporaneous feedback\nThe Gauss-Seidel algorithm is quite straight forward. It basically iterate over the formulas, until convergence. \n\nLet $z$ be all predetermined values: all exogenous variable and lagged endogenous variable.\nLet $n$ be the number of endogenous variables.\n \nFor each time period we can find a solution by doing Gauss-Seidel iterations: \n\nfor $k = 1$ to convergence\n\n>for $i$ = 1 to $n$ \n>\n>>$y_{i}^{k} = (1-\\alpha) * y_{i}^{{k-1}} + \\alpha f_i(y_1^{k},\\cdots,y_{i-1}^{k},y_{i+1}^{k-1},\\cdots,y_{n}^{k-1},z)$\n\n#### Convergence \nConvergence has been reached when the solution don't change to much between each iteration. \nThere is no need to check all variable for convergence. So the user can define a \nset $\\{$convergence variable$\\}$ Then all relative changes from one iteration to has to be smaller than a convergence criteria $\\epsilon_{relative}$. It does not make sense to calculate relative changes in values close to 0, so the test is only performed on values larger than a small number $\\epsilon_{absolute}$ \n\n$\\forall y_{j}$ where $y_{j} \\in \\{$convergence variable$\\}\\land \\mid y_{j}^{k-1}\\mid \\geq \\epsilon_{absolute}$ we calculate $\\mid \\frac{y_{j}^{k}-y_{j}^{k-1}}{y_{j}^{k-1}}\\mid \\leq \\epsilon_{relative}$\n\n\nUnder some circumstances the the iterations will diverge, even if there is a solution. This can (mostly) be handled by introducing the dampening factor $\\alpha$ in the algorithm. $\\alpha$ is usually only needed for a few variables - if any. To select an equation for dampening the formula option damp has to be used. \n\n#### The Newton-Raphson algorithme. Models with contemporaneous feedback\n\nLet $\\bf z$ be a vector all predetermined values: all exogenous variable and lagged endogenous variable.\n\nFor each time period we can find a solution by doing Newton-Raphson iterations: \n\nfor $k = 1$ to convergence\n\n>$\\bf y = \\bf {F(y^{k-1},z) }$\n>\n>$\\bf y^{k} = \\bf y - \\bf{(A-I)}^{-1} \\times ( \\bf {y - y^{k-1} })$\n\n\n\nThe expression: $\\bf{(A-I)}^{-1}\\times ( \\bf {y - y^{k-1} })$ is the same as the solution to: \n\n$\\bf {y- y^{k-1} } = \\bf (A-I) \\times \\bf x$\n\nThis problem can be solved much more efficient than performing $\\bf{(A-I)}^{-1}\\times ( \\bf {y - y^{k-1} })$\n\nThe Scipy library provides a number of solvers to this linear set of equations. There are both solvers using factorization and iterative methods, and there are solvers for dense and sparce matrices. Theese linear solvers can easily be incorporated into ModelFlows Newton-Raphson nonlinear solver.\n\n#### Stacked Newton-Raphson all periods in one go. Models with both leaded and lagged endogeneous variable\n\nIf the model has leaded endogenous variables it can in general not be solved one time period at a time. We have to solve the model for all time frames as one large model. \n\nFor the Newton-Raphson algorithme we now have to stack all the derivative matrices. For a model with a max lag of 3 which has to be solved for 8 time periods the stacked matrices looks like this. \n\n$$\\bf{\\bar A} =\\begin{bmatrix} \n\t\t\\bf{A_1} & \\bf{D_1^1} & \\bf{D_1^2} & \\bf{0} &\\bf{0} &\\bf{0} &\\bf{0} &\\bf{0} \\\\\n \\bf{E_2^1} & \\bf{A_2} & \\bf{D_2^1} & \\bf{D_2^2} &\\bf{0} &\\bf{0} &\\bf{0} &\\bf{0} \\\\ \n \\bf{E_3^2} & \\bf{E_3^1} & \\bf{A_3} & \\bf{D_3^1} & \\bf{D_3^2} &\\bf{0} &\\bf{0} &\\bf{0} \\\\ \n \\bf{E_4^3} & \\bf{E_4^2} & \\bf{E_4^1} & \\bf{A_4} & \\bf{D_4^1} & \\bf{D_4^2} &\\bf{0} & \\bf{0} \\\\ \n \\bf{0} & \\bf{E_5^3} & \\bf{E_5^2} & \\bf{E_5^1} & \\bf{A_5} & \\bf{D_5^1} & \\bf{D_5^2} &\\bf{0}\\\\ \n \\bf{0} & \\bf{0} & \\bf{E_6^3} & \\bf{E_6^2} & \\bf{E_6^1} & \\bf{A_6} & \\bf{D_6^1} & \\bf{D_6^2}\\\\ \n \\bf{0} & \\bf{0} & \\bf{0} & \\bf{E_7^3} & \\bf{E_7^2} & \\bf{E_7^1} & \\bf{A_7} & \\bf{D_7^1} \\\\ \n \\bf{0} & \\bf{0} & \\bf{0} & \\bf{0} & \\bf{E_8^3} & \\bf{E_8^2} & \\bf{E_8^1} & \\bf{A_8} \\\\ \n\\end{bmatrix} \\bar y = \\begin{bmatrix}\\bf{y_1}\\\\\\bf{y_2}\\\\\\bf{y_3}\\\\ \\bf{y_4} \\\\\\bf{y_5} \\\\\\bf{y_6} \\\\ \\bf{y_7} \\\\ \\bf{y_8} \\end{bmatrix} \\bar F = \\begin{bmatrix}\\bf{F}\\\\\\bf{F}\\\\\\bf{F}\\\\ \\bf{F} \\\\\\bf{F} \\\\\\bf{F} \\\\ \\bf{F} \\\\ \\bf{F} \\end{bmatrix}$$\n\n\nAgain let $\\bf z$ be a vector all predetermined values: all exogenous variable and lagged endogenous variable.\n\nNow the solution algorithme looks like this. \n\nfor $k = 1$ to convergence\n\n>$\\bf{\\bar y} = \\bf {\\bar F(\\bar y^{k-1},\\bar z) }$\n\n>$\\bf {\\bar y^{k}} = \\bf{\\bar y} - \\bf{(\\bar A-I)}^{-1}\\times ( \\bf {\\bar y - \\bar y^{k-1} })$\n\nNotice that the model $\\bf F$ is the same for all time periods\n\nAgain we solve the problem: $$( \\bf {\\bar y - \\bar y^{k-1} }) = \\bf{(\\bar A-I)}\\times \\bf x $$\n\n\n##### Stacked Newton with no leaded endogenous variables. \n\nIn this case all the $\\bf{D}$ submatrices in the above algorithm disappear. \n\n#### Fair-Taylor algorithm, Models with both leaded and lagged endogeneous variable \n\nAnother way to solve the model as one system is the Fair-Taylor algorithm. It can be seen as an extension to the gauss algorithm for the whold system, with the added twist that each period is solved. \n\n\nfor $f$ = 1 to convergence\n>for $t = 1$ to end time\n>>$\\textbf{y}_t^f= solve( \\textbf{F}(\\textbf{y}_{t+u}^{f-1} \\cdots \\textbf{y}_{t-r}^{f},\\textbf{x}_t \\cdots, \\textbf{x}_{t-r}))$\n\nWhere $solve$ in the inner loop can be either a Gauss or a Newton one period solve algorithm. ModelFlow use the Gauss solver in the inner loop. But it would be straight forward to implement a Newton inner loop. \n\n\n### Un-normalized model \n\n### The simultaneous model, with leaded variables\n**If F has contemporaneous feedback and leaded endogeneous variables, it has to be solved for all timeframes - again with an iterative method.** Modelflow can use the Fair-Taylor algorithme - which is a Gauss-Seidle derivative or solve the model for all periods with a (stacked) Newton-Raphson algorithme. \n\nIn general the Newton-Raphson algorithme is faster and more stable for this kind of models.\n\n### Stacked Newton-Raphson algorithm\n\nIf the model has leaded endogenous variables it can in general not be solved one time period at a time. We have to solve the model for all time frames as one large model. \n\nFor the Newton-Raphson algorithme we now have to stack all the derivative matrices. For a model with a max lag of 3 and a max lead of 2 which has to be solved for 8 time periods the stacked matrices looks like this. \n\n$$\\bf{\\bar A} =\\begin{bmatrix} \n\t\t\\bf{A_1} & \\bf{D_1^1} & \\bf{D_1^2} & \\bf{0} &\\bf{0} &\\bf{0} &\\bf{0} &\\bf{0} \\\\\n \\bf{E_2^1} & \\bf{A_2} & \\bf{D_2^1} & \\bf{D_2^2} &\\bf{0} &\\bf{0} &\\bf{0} &\\bf{0} \\\\ \n \\bf{E_3^2} & \\bf{E_3^1} & \\bf{A_3} & \\bf{D_3^1} & \\bf{D_3^2} &\\bf{0} &\\bf{0} &\\bf{0} \\\\ \n \\bf{E_4^3} & \\bf{E_4^2} & \\bf{E_4^1} & \\bf{A_4} & \\bf{D_4^1} & \\bf{D_4^2} &\\bf{0} & \\bf{0} \\\\ \n \\bf{0} & \\bf{E_5^3} & \\bf{E_5^2} & \\bf{E_5^1} & \\bf{A_5} & \\bf{D_5^1} & \\bf{D_5^2} &\\bf{0}\\\\ \n \\bf{0} & \\bf{0} & \\bf{E_6^3} & \\bf{E_6^2} & \\bf{E_6^1} & \\bf{A_6} & \\bf{D_6^1} & \\bf{D_6^2}\\\\ \n \\bf{0} & \\bf{0} & \\bf{0} & \\bf{E_7^3} & \\bf{E_7^2} & \\bf{E_7^1} & \\bf{A_7} & \\bf{D_7^1} \\\\ \n \\bf{0} & \\bf{0} & \\bf{0} & \\bf{0} & \\bf{E_8^3} & \\bf{E_8^2} & \\bf{E_8^1} & \\bf{A_8} \\\\ \n\\end{bmatrix} \\bar y = \\begin{bmatrix}\\bf{y_1}\\\\\\bf{y_2}\\\\\\bf{y_3}\\\\ \\bf{y_4} \\\\\\bf{y_5} \\\\\\bf{y_6} \\\\ \\bf{y_7} \\\\ \\bf{y_8} \\end{bmatrix} \\bar F = \\begin{bmatrix}\\bf{F}\\\\\\bf{F}\\\\\\bf{F}\\\\ \\bf{F} \\\\\\bf{F} \\\\\\bf{F} \\\\ \\bf{F} \\\\ \\bf{F} \\end{bmatrix}$$\n\n\n$$\\bf \\bar z$$ contains all predetermined variable. \n\nNow the solution algorithme looks like this. \n\nfor $k = 1$ to convergence\n\n>$\\bf{\\bar y\\_residual} = \\bf {\\bar G(\\bar y^{k-1},\\bar z) }$\n>\n>$\\bf {\\bar y^{k}} = \\bf{\\bar y} - \\bf{\\bar A}^{-1} \\times \\bf {\\bar y\\_residual}$\n\nNotice that the model $\\bf G$ is the same for all time periods\n\nAgain we don't compute $\\bf{\\bar y} - \\bf{\\bar A}^{-1} \\times \\bf {\\bar y\\_residual}$ which requires the \"expensiv\" inversion of a matrix but solve the problem: $\\bf{\\bar y\\_residual}=\\bf{\\bar A} \\times \\bf x$ which can be done much faster.\n\n# Implementation of solving algorithms in Python\nSolving a model entails a number of steps:\n\n1. Specification of the model \n2. Create a dependency graph. \n2. Establish a solve order and separate the the model into smaller sub-models\n2. Create a python function which can evaluating $f_i(y_1^{k},\\cdots,y_{i-1}^{k},y_{i+1}^{k-1},\\cdots,y_{n}^{k-1},z)$\n3. If needed, create a python function which can evaluate the Jacobimatrices: $\\bf{A,E,D}$ or $\\bf{\\bar A,\\bar E,\\bar D}$ \n3. Apply a solve function using the elements above to the data. \n\n## Specification of model in Business Logic Language\nThe Business logic Language is a Python like language, where each function $f_i$ from above is specified as:\n\n```\nFRML = $ ... \n```\n\nThe `````` should not contain transformations, but can be a tuple which match the ``````. A \\$ separates each formular.\n\nTime is implicit, so $var_t$ is written as ```var```, while $var_{t-1}$ is written as ```var(-1)``` and $var_{t+1}$ is written as ```var(+1)```. Case does not matter. everything is eventual made into upper case. \n\nIt is important to be able to create short and expressive models, therefor. Stress test models should be able to handle many bank and sectors without repeating text. So on top of the **Business logic language**. there is a **Macro Business Logic language**. The primary goal of this is to allow (conditional) looping and normalization of formulas. \n\n\n# Onboarding a model \n\nWe want to present a model to the transpiler, so it can create a model instance including a python function which can solve/calculate the model. The primary method for this is to formulate the model in a Business logic Language. \n\nThe purpose of the Business logic language is to enable a clear and\nconcise specification of the models at hand.\n\nA *macro model* can flow through a *macro-processor* which returns *business logic*. This is then processed by\ntranspiler to create a python function which can solve the model.\n\nThe macro-processer performs text processing:\n\n- Normalize formulas\n\n- Decorate formulas\n\n- Expand arrays\n\n- Expand matrices\n\n- Unlooping do-loops\n\nThe inspiration is the modeling language of venerable programs like\nTSP, Eviews, Troll and SAS/ETS combined with the rules of Python.\n\nIf you launch this notebook as Jupyter notebook, you can play around with the business logic language.\n\nThere are three types of statements:\n\n1. Formula statement:\\\n Defines transformation of variables in the Dataframe\n\n2. List statement:\\\n Defines lists and associated sub lists. Lists can be\n used to define repetitive items and to define mappings\n\n3. DO/END DO statements\\\n Defines repetitive formulas in which the content of list are\n interpolated\n\n## A Flexible language \nThe example above shows how to specify a simple model. It looks like python, except that variable names are substituted to references to pandas dataframe cells after Transpiling. \nThis is fine for some problems. \n\nHowever a **macro** expanding phase enhance the language in order to make it more powerful, agile, and and still parsimonious. \n\nThe expanded business logic language introduce a little more. It consists of commands and comments: \n\n- frml: Define formulas \n- list: Define sublist to explode over \n- do: start exploding \n- enddo: end exploding\n\n### Variables\n\n**Variable names has to start with a letter or _ then any number of\nletters _ or digits. Time t is implicit.** \n\n**A lag** can be specified right after a variable as: ```(-)```, meaning:\n```horse(-1)``` is the variable ```horse``` lagged one period\n\nA variable can contain a number or a Python object. The Python object can be for instance be a cvxopt matric, a numpy array or even a Pandas dataframe. \n\nCase does not matter. All variables are translated to upper case. And in\nthe Dataframe all variables should be upper case.\n\nLags cannot be specified at the left hand side of =.\n\n## FRML command, defines calculations\n\n```frml left hand side = right hand side $```\n\nIf it is done for the whole model, the word frml and the <> clause and $ can be ignored. In this case commands including formulas are separated by newline.\n\n### Right hand side\n\nOperators: \n\nStandard: ```= + - * / ** ( ) @ ```\n\nComparison: ```>= <= == !=``` \\# evaluates to 0 if false, 1 if true\n\nSpecial: ```$ > < , . [ ] ``` # used in different python constructions.\n\n### Several variables on the left hand side\n\nThere can be several left hand variables. Python rules for tuple\nunpacking apply.\n\n```a, b, c = 1, 2, 3 ```\n\nor\n\n```a, b, b = some_function_which returns_3 values(x,y,z,42)```\n\nBe aware that normalization cannot be combined with this feature.\n\nThe feature is useful when packing and unpacking matrices and when\napplying optimization.\n\n### Text processing functions on the right hand side \n\nThe functions DIFF and DLOG will be expanded on the right hand side. Their argument can be expressions involving lagged variable, therefore they can't be evaluated directly, so they are expanded in the pre-processing phase. \n\n\n```python\nexplode('a = alfa * diff(b)')\n```\n\n\n\n\n 'FRML <> A = ALFA * ((B)-(B(-1))) $'\n\n\n\n\n```python\nexplode('a = alfa * dlog(b)')\n```\n\n\n\n\n 'FRML <> A = ALFA * ((LOG(B))-(LOG(B(-1)))) $'\n\n\n\n\n```python\nexplode('a = alfa * dlog(a+b+c)')\n```\n\n\n\n\n 'FRML <> A = ALFA * ((LOG(A+B+C))-(LOG(A(-1)+B(-1)+C(-1)))) $'\n\n\n\n### Text processing functions on the left hand of a formular \n\nIn some models, it can be useful to specify a function of the endogenous variable as the target on the left-hand side. In order to do the calculation, the endogenous variable has to be isolated on the left-hand side. This is done in a pre-processing step by applying the inverse of the function to the right-hand side. Functions allowed on left-hand side: **diff, log, dlog, logit**.\n\nThese functions are only allowed when there are just one left-hand side variable.\n\n#### Only current or lagged endogeneous variables.\nIn systems with no lags each period can be solved in succestion\n\n\n```python\nexplode('diff(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n 'FRML <> LHV=LHV(-1)+(42 * (A+B+C))$'\n\n\n\n\n```python\nexplode('log(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n 'FRML <> LHV=EXP(42 * (A+B+C))$'\n\n\n\n\n```python\nexplode('logit(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n 'FRML <> LHV=(EXP(42 * (A+B+C))/(1+EXP(42 * (A+B+C))))$'\n\n\n\n\n```python\nexplode('dlog(lhv) = 42 * (a+b+c) ')\n```\n\n\n\n\n 'FRML <> LHV=EXP(LOG(LHV(-1))+42 * (A+B+C))$'\n\n\n\n### Formula name, enhancing formular calculations \nThe purpose of the formula name/control is to enable relevant additions to the formulas, but avoid boilerplate noise to the formulas. \n\nThe control is placed between <> after the 'FRML'. different controls can be separated by ','\n\n#### Absolute adjustment \n\n\n```python\nmp.explode(' lhv = rhs ')\n```\n\n\n\n\n 'FRML LHV = RHS +LHV_J$'\n\n\n\n#### Relative adjustment \n\n\n```python\nmp.explode(' lhv = rhs ')\n```\n\n\n\n\n 'FRML LHV = ( RHS )*(1+LHV_JR )$'\n\n\n\n#### Fixing results \n\n\n```python\nmp.explode('frml lhv = rhs ')\n```\n\n\n\n\n 'FRML LHV =( RHS )*(1-LHV_D)+LHV_X*LHV_D$'\n\n\n\nBy setting LHV_D the user controls wether LHV is set to the value of the RHS exression or the value LHV_X.\n\n#### Extract model for calculating identities in before projection period\n\n\n```python\ntmodel = '''\\\nfrml <> horse = 1.3 * cow +dgdp(-1)$ \nfrml dgdp = gdp/gpd(-1) $\nfrml dinv = inv/inv(-1) $ '''\nprint( mp.explode(tmodel))\n```\n\n FRML <> HORSE = 1.3 * COW +DGDP(-1)$\n FRML DGDP = GDP/GPD(-1) $\n FRML DINV = INV/INV(-1) $\n\n\n\n```python\nmp.find_hist_model(tmodel)\n```\n\n\n\n\n 'frml dgdp = gdp/gpd(-1) $\\nfrml dinv = inv/inv(-1) $'\n\n\n\n#### Make dampening a formular possible\n\nZ : When solving a model with the Gauss-Seidel algorithm the evaluation\nof this formula can be damped.\n\n\n### Incorporating user defined functions into formulas\n\nThe user can incorporate her own routines in the BL language. \nThis is giving the user defined functions as the funks argument to the model creation. \n\nThe tokenizer will recognize the name of the function and place call to the function in the solving routine. \n\n\n```python\ndef f1(x):\n return 42\n\nf2model = '''\\\na = c * 42 \nf = c(-1) >=2 \nanswer = f1(a)'''\n\nm2model = mc.model(f2model,funks=[f1])\n\n```\n\n## LIST command, define list and sublists \n\nLists are used to direct how the do command explodes a template model. \nAnd to define sum functions, and for matrix packing and unpacking. \n\n``` \nList = : .. / \n : .. /\n .............................]\n $\n```\n**There should always be the same number of elements in sublists**\n\nExample with one sublist: \n\n```\nLIST BANKLIST = BANK : ATBAW DEHAS DEHSH LUPCK DELBY DEVWF ESSAB $\n```\n\nExample with two sublist: \n\n```\nLIST CRCOLIST = CRCOUNTRY : UK DE CH NL BE CA JP KY LU HK / \n CRMODELGEO : UK DE CH NL BE CA JP R20 LU HK $\n``` \n\nIf a list name is created several times, the first time is the used. This makes it more easy to make prototypes for a few banks.\n\n\n## DO ... ENDDO, loop over lists \n\n```\ndo $\nstuff \nenddo $\n```\n\nWill take take the stuff and make a copy for each element of the sublists in list name. \n\n\n```python\nmtest = ''' \nlist banklist = bank : ib soren $\ndo banklist $\n profit_{bank} = revenue_{bank} - expenses_{bank} $\nenddo $ \n'''\n\nprint(explode(mtest))\n```\n\n LIST BANKLIST = BANK : IB SOREN $\n PROFIT_IB = REVENUE_IB - EXPENSES_IB $\n PROFIT_SOREN = REVENUE_SOREN - EXPENSES_SOREN $\n\n\n### Use of sublist to inject additional information \n\n\n```python\nmtest = ''' \nlist banklist = bank : ib soren marie /\n country : denmark sweden denmark $\n \ndo banklist $\n frml <> profit_{bank} = revenue_{bank} - expenses_{bank} $\n frml <> expenses_{bank} = factor_{country} * revenue_{bank} $\nenddo $ \n'''\n\nprint(mp.explode(mtest))\n```\n\n LIST BANKLIST = BANK : IB SOREN MARIE /\n COUNTRY : DENMARK SWEDEN DENMARK $\n FRML <> PROFIT_IB = REVENUE_IB - EXPENSES_IB $\n FRML <> EXPENSES_IB = FACTOR_DENMARK * REVENUE_IB $\n FRML <> PROFIT_SOREN = REVENUE_SOREN - EXPENSES_SOREN $\n FRML <> EXPENSES_SOREN = FACTOR_SWEDEN * REVENUE_SOREN $\n FRML <> PROFIT_MARIE = REVENUE_MARIE - EXPENSES_MARIE $\n FRML <> EXPENSES_MARIE = FACTOR_DENMARK * REVENUE_MARIE $\n\n\n### Nested do\n\nDo loops can be nested.\n\nOne just have to take care that there is no duplication of sublist names. \n\n\n```python\nmtest = ''' \nlist banklist = bank : ib soren marie /\n country : denmark sweden denmark $\n \nlist assetlist = asset : nfc sme hh $\n \n \ndo banklist $\n ! bank = {bank}\n profit_{bank} = revenue_{bank} - expenses_{bank}-loss_{bank} $\n expenses_{bank} = factor_{country} * revenue_{bank} $\n do assetlist $\n loss_{asset}_{bank} = 0.02 * stock_{asset}_{bank} $\n enddo $\n ! find the sum \n loss_{bank} = sum(assetlist,loss_{asset}_{bank}) $\n\nenddo $ \n'''\n\nprint(explode(mtest))\n```\n\n LIST BANKLIST = BANK : IB SOREN MARIE /\n COUNTRY : DENMARK SWEDEN DENMARK $\n LIST ASSETLIST = ASSET : NFC SME HH $\n BANK = IB\n PROFIT_IB = REVENUE_IB - EXPENSES_IB-LOSS_IB $\n EXPENSES_IB = FACTOR_DENMARK * REVENUE_IB $\n LOSS_NFC_IB = 0.02 * STOCK_NFC_IB $\n LOSS_SME_IB = 0.02 * STOCK_SME_IB $\n LOSS_HH_IB = 0.02 * STOCK_HH_IB $\n FIND THE SUM \n LOSS_IB = (LOSS_NFC_IB+LOSS_SME_IB+LOSS_HH_IB) $\n BANK = SOREN\n PROFIT_SOREN = REVENUE_SOREN - EXPENSES_SOREN-LOSS_SOREN $\n EXPENSES_SOREN = FACTOR_SWEDEN * REVENUE_SOREN $\n LOSS_NFC_SOREN = 0.02 * STOCK_NFC_SOREN $\n LOSS_SME_SOREN = 0.02 * STOCK_SME_SOREN $\n LOSS_HH_SOREN = 0.02 * STOCK_HH_SOREN $\n FIND THE SUM \n LOSS_SOREN = (LOSS_NFC_SOREN+LOSS_SME_SOREN+LOSS_HH_SOREN) $\n BANK = MARIE\n PROFIT_MARIE = REVENUE_MARIE - EXPENSES_MARIE-LOSS_MARIE $\n EXPENSES_MARIE = FACTOR_DENMARK * REVENUE_MARIE $\n LOSS_NFC_MARIE = 0.02 * STOCK_NFC_MARIE $\n LOSS_SME_MARIE = 0.02 * STOCK_SME_MARIE $\n LOSS_HH_MARIE = 0.02 * STOCK_HH_MARIE $\n FIND THE SUM \n LOSS_MARIE = (LOSS_NFC_MARIE+LOSS_SME_MARIE+LOSS_HH_MARIE) $\n\n\n### Use of sublist to do conditional Loop\n\nBy using \n\n`DO listname sublist = value $`\n\nthe looping will only be performed on the members of list where the value of the corresponding sublist match the value in the do statement.\n\nThis can be useful for instance when treating portfolios differently depending on some information. An example could be the different treatment of portfolios depending on regulatory approach. \n\n\n```python\nmtest='''\nlist portdic = port : households , NFC , RE, sov /\n reg : AIRB , AIRB , STA, STA $\n do portdic reg = airb $ \n frml x {port}_REA_W = calc_rw({port}_pd ,{port}_lgd) $\n enddo $ \n do portdic reg = sta $ \n frml x {port}_REA_W = {port}_REA_W(-1) $\n enddo $ \n '''\nprint(explode(mtest))\n```\n\n LIST PORTDIC = PORT : HOUSEHOLDS , NFC , RE, SOV /\n REG : AIRB , AIRB , STA, STA $\n FRML X HOUSEHOLDS_REA_W = CALC_RW(HOUSEHOLDS_PD ,HOUSEHOLDS_LGD) $\n FRML X NFC_REA_W = CALC_RW(NFC_PD ,NFC_LGD) $\n FRML X RE_REA_W = RE_REA_W(-1) $\n FRML X SOV_REA_W = SOV_REA_W(-1) $\n\n\n### Dynamic defined lists to utilize sparsity\nOften not all the potential dimensions in a model contains data. For instance all banks don't have positions in all potential countries. \n\nIn order to speed up calculations and to avoid bloating dataframes, we want to avoid calculating and carrying a lot of zeros around. \n\nThis can be achieved by using dynamic naming of lists. For instance create a separate list of countries for each bank. \n\nThe list for each country can be created by using the pandas library to identify in which countries \nthere are non-zero positions - straight forward but beyond the scope of this notebook. \n\nBelow is an example where there are two banks which each has exposures in different countries. \n\n\n```python\n stest='''\n list BANKDIC = bank : Danske , Nordea $ \n list country_danske_dic = country : uk , DK, IR $\n list country_nordea_dic = country: SE , DK $\n do bankdic $ \n frml x {bank}_income = {bank}_a +{bank}_b $\n do country_{bank}_dic $\n frml x value_{bank}_{country} = 42 $\n enddo $ \n frml <> total_{bank} = sum(country_{bank}_dic,value_{bank}_{country}) $\n enddo $ '''\n \n print(explode(stest))\n```\n\n LIST BANKDIC = BANK : DANSKE , NORDEA $\n LIST COUNTRY_DANSKE_DIC = COUNTRY : UK , DK, IR $\n LIST COUNTRY_NORDEA_DIC = COUNTRY: SE , DK $\n FRML X DANSKE_INCOME = DANSKE_A +DANSKE_B $\n FRML X VALUE_DANSKE_UK = 42 $\n FRML X VALUE_DANSKE_DK = 42 $\n FRML X VALUE_DANSKE_IR = 42 $\n FRML <> TOTAL_DANSKE = (VALUE_DANSKE_UK+VALUE_DANSKE_DK+VALUE_DANSKE_IR) $\n FRML X NORDEA_INCOME = NORDEA_A +NORDEA_B $\n FRML X VALUE_NORDEA_SE = 42 $\n FRML X VALUE_NORDEA_DK = 42 $\n FRML <> TOTAL_NORDEA = (VALUE_NORDEA_SE+VALUE_NORDEA_DK) $\n\n\n## Pack values into matrices (a cvxopt class)\n\n\n```python\nmtest2 = ''' \nlist banklist = bank : ib soren $\nlist banklist2 = bank2 : ib soren $\n! vector \nfrml vbank = to_matrix(banklist,profit_{bank}) $\n! matrices \nfrml Mbank = to_matrix(banklist,banklist2,loanfrom_{bank}_to_{bank2}) $\n'''\n\nprint(mp.explode(mtest2))\n```\n\n LIST BANKLIST = BANK : IB SOREN $\n LIST BANKLIST2 = BANK2 : IB SOREN $\n VECTOR FRML VBANK = MATRIX(\n [PROFIT_IB,PROFIT_SOREN]) $\n MATRICES FRML MBANK = MATRIX(\n [[LOANFROM_IB_TO_IB,LOANFROM_IB_TO_SOREN],\n [LOANFROM_SOREN_TO_IB,LOANFROM_SOREN_TO_SOREN]]) $\n\n\n## Pack values into arrays (a numpy class)\n\n\n```python\nmtest2 = ''' \nlist banklist = bank : ib soren $\nlist banklist2 = bank2 : ib soren $\n! vector \nfrml vbank = to_array(banklist,profit_{bank}) $\n! matrices \nfrml Mbank = to_array(banklist,banklist2,loanfrom_{bank}_to_{bank2}) $\n'''\n\nprint(mp.explode(mtest2))\n```\n\n LIST BANKLIST = BANK : IB SOREN $\n LIST BANKLIST2 = BANK2 : IB SOREN $\n VECTOR FRML VBANK = ARRAY(\n [PROFIT_IB,PROFIT_SOREN]) $\n MATRICES FRML MBANK = ARRAY(\n [[LOANFROM_IB_TO_IB,LOANFROM_IB_TO_SOREN],\n [LOANFROM_SOREN_TO_IB,LOANFROM_SOREN_TO_SOREN]]) $\n\n\n## Unpack values - Argexpand \n\n\n```python\nmtest2 = ''' \nlist banklist = bank : ib soren $\nlist banklist2 = bank2 : ib soren $\n! vector \nfrml <> argexpand(banklist,test_{bank}) = to_matrix(banklist,profit_{bank}) $\n! matrices \nfrml <> argexpand(banklist,argexpand(banklist2,loanfrom_{bank2}_{bank})) = 0 $\n'''\n\nprint(mp.explode(mtest2))\n```\n\n LIST BANKLIST = BANK : IB SOREN $\n LIST BANKLIST2 = BANK2 : IB SOREN $\n VECTOR FRML <> TEST_IB,TEST_SOREN = MATRIX(\n [PROFIT_IB,PROFIT_SOREN]) $\n MATRICES FRML <> LOANFROM_IB_IB,LOANFROM_SOREN_IB,LOANFROM_IB_SOREN,LOANFROM_SOREN_SOREN = 0 $\n\n\n\n```python\nmtest2 = ''' \nlist listdevs = devs : dev_yer dev_uts $\nlist listshocks = shocks : ib soren $\n frml ARGEXPAND(listdevs,{devs}) = STE(to_matrix(LISTSHOCKS,{SHOCKS}(-3)),\\\n to_matrix(LISTSHOCKS,{SHOCKS}(-2 )), \\\n to_matrix(LISTSHOCKS,{SHOCKS}(-1)),\n to_matrix(LISTSHOCKS,{SHOCKS}) ) $\n '''.upper() \n\nprint(mp.explode(mtest2))\n```\n\n LIST LISTDEVS = DEVS : DEV_YER DEV_UTS $\n LIST LISTSHOCKS = SHOCKS : IB SOREN $\n FRML DEV_YER,DEV_UTS = STE(MATRIX(\n [IB(-3),SOREN(-3)]), MATRIX(\n [IB(-2 ),SOREN(-2 )]), MATRIX(\n [IB(-1),SOREN(-1)]),\n MATRIX(\n [IB,SOREN]) ) $\n\n\n\n\n## Create an array of lagged or leaded variables - lag_array\nlag_array(,) will create an numpy array with length = |number|, positive number \n will give an array of leaded values, negative numbers an array of lagged values \n\n\n```python\nmtest3 = '''\npd_pit_array_leaded = lag_array(3,pd_pit) $ \n'''\nprint(mp.explode(mtest3))\n```\n\n PD_PIT_ARRAY_LEADED = ARRAY([PD_PIT(+1),PD_PIT(+2),PD_PIT(+3)]) $\n\n\n\n```python\nmtest3 = '''\npd_pit_array_lagged = lag_array(-3,pd_pit) $ \n'''\nprint(mp.explode(mtest3))\n```\n\n PD_PIT_ARRAY_LAGGED = ARRAY([PD_PIT(-1),PD_PIT(-2),PD_PIT(-3)]) $\n\n\n## Sum, sum over list \nsum(LIST,expression) = sums expression over the elements of a list substitution the sublist names. \n\n\n```python\nmtest = ''' \nlist banklist = bank : ib soren marie /\n country : denmark sweden denmark $\n \nlist assetlist = asset : nfc sme hh $\n \n \ndo banklist $\n !\n ! bank = {bank}\n do assetlist $\n loss_{asset}_{bank} = 0.02 * stock_{asset}_{bank} $\n enddo $\n ! find the sum \n loss_{bank} = sum(assetlist,loss_{asset}_{bank}) $\n\nenddo $ \n \nloss_total = sum(banklist,sum(assetlist,loss_{asset}_{bank}))$\n'''\n\nprint(explode(mtest))\n```\n\n LIST BANKLIST = BANK : IB SOREN MARIE /\n COUNTRY : DENMARK SWEDEN DENMARK $\n LIST ASSETLIST = ASSET : NFC SME HH $\n BANK = IB\n DO ASSETLIST $\n LOSS_{ASSET}_IB = 0.02 * STOCK_{ASSET}_IB $\n BANK = SOREN\n DO ASSETLIST $\n LOSS_{ASSET}_SOREN = 0.02 * STOCK_{ASSET}_SOREN $\n BANK = MARIE\n DO ASSETLIST $\n LOSS_{ASSET}_MARIE = 0.02 * STOCK_{ASSET}_MARIE $\n FIND THE SUM \n LOSS_{BANK} = (LOSS_NFC_{BANK}+LOSS_SME_{BANK}+LOSS_HH_{BANK}) $\n LOSS_TOTAL = ((LOSS_NFC_IB+LOSS_SME_IB+LOSS_HH_IB)+(LOSS_NFC_SOREN+LOSS_SME_SOREN+LOSS_HH_SOREN)+(LOSS_NFC_MARIE+LOSS_SME_MARIE+LOSS_HH_MARIE))$\n\n\n## Onboarding models from other sources \n\n**Python has incredible strong tools both for interacting with other systems like Excel and Matlab, and for text processing.** This allows for *recycling* of models from different sources and make them live together (hopefully happy). Some of the sources, from which models has been recycled are: \n\n- Latex, \n - Code from Dynare \n - Model written in Latex - with some rules to allow text processing. \n- Excel \n - Calculation model from Excel workbook \n - Grabbing coefficients from excel workbooks \n- Matlab \n - Wrapping matlab models into python functions, which can be used in ModelFlow \n - Grabbing coefficients from matlab .mat files. \n- Aremos models \n- TSP models \n\nGrabbing models and transforming them to Business logic language usually requires a tailor-made Python program. However in the ModelFlow folder there are different examples of such grabbing. \n\n# From model equations to solution\n\nThe core of ModelFlow is a transpiler. The purpose of the transpiler\nis two fold.\n\n - To convert a **Business Logic Language** model to a python function. This function can then evaluates the model, and thus be called from the solving routine. Both Gauss-Seidle and Newton-Raphson solvers need as input a function to which can evaluate the model. \n \n - To analyze the model. Find the dependencies **graph** of the formulas. The depencency graph can be used for analyzing the causal structure of a model. This is used to speed up solving and to enable model and model result analytic. \n\nPython come batteries included, so a number of powerful tools are available. Therefore, it is not necessary to design a full-fledged compiler/interpreter in order to solve a model. Some of the tough jobs are outsourced to the Python ecosystem. \n\n\n```python\n\n```\n\n## A syntax checker. \n***Formulas must be legal Python expressions.***\n This allows us to outsource syntax checking of formulas to the Python ecosystem. The ***ast*** Python standard library can check the syntax, and it is easy to make a function which catch syntax errors in the formulas.\n\n\n```python\nmp.check_syntax_frml('frml <> a = b $')\n```\n\n\n\n\n True\n\n\n\n\n```python\nmp.check_syntax_frml('frml <> a = b + = c$')\n```\n\n\n\n\n False\n\n\n\n## A tokenizer. \nThe model is chopped into tokens. This\n is done by using the regular expressing (***re***) Python standard library. \n The tokenizer delivers an expression ad a list of tokens in the form of named tuple's (terms). Each token can be either of four types:\n\n- A variable perhaps with lag or lead\n- A number\n- An operator, function.\n\n\n\n```python\n\n```\n\n\n```python\npt.udtryk_parse('a=b(-1)+3')\n```\n\n\n\n\n [nterm(number='', op='', var='A', lag=''),\n nterm(number='', op='=', var='', lag=''),\n nterm(number='', op='', var='B', lag='-1'),\n nterm(number='', op='+', var='', lag=''),\n nterm(number='3', op='', var='', lag='')]\n\n\n\n\n```python\npt.model_parse('''\\\nfrml <> a=b+2$\nfrml <> v=x+y(-1))$\n''')\n```\n\n\n\n\n [(fatoms(whole='FRML <> A=B+2$', frml='FRML', frmlname='<>', expression='A=B+2$'),\n [nterm(number='', op='', var='A', lag=''),\n nterm(number='', op='=', var='', lag=''),\n nterm(number='', op='', var='B', lag=''),\n nterm(number='', op='+', var='', lag=''),\n nterm(number='2', op='', var='', lag=''),\n nterm(number='', op='$', var='', lag='')]),\n (fatoms(whole='FRML <> V=X+Y(-1))$', frml='FRML', frmlname='<>', expression='V=X+Y(-1))$'),\n [nterm(number='', op='', var='V', lag=''),\n nterm(number='', op='=', var='', lag=''),\n nterm(number='', op='', var='X', lag=''),\n nterm(number='', op='+', var='', lag=''),\n nterm(number='', op='', var='Y', lag='-1'),\n nterm(number='', op=')', var='', lag=''),\n nterm(number='', op='$', var='', lag='')])]\n\n\n\nThe pattern defining operators and functions is defined\n\n### Define pattern for variable names and lags \n\n\n```python\nnamepat_ng = r'(?:[A-Za-z_{][A-Za-z_{}0-9]*)' # a name non grouped\nnamepat = r'(' + namepat_ng + ')' # a name grouped\nlagpat = r'(?:\\(([+-][0-9]+)\\))?'\nnamepat+lagpat\n```\n\n\n\n\n '((?:[A-Za-z_{][A-Za-z_{}0-9]*))(?:\\\\(([+-][0-9]+)\\\\))?'\n\n\n\n### Define pattern for numbers\n\n\n```python\nnumpat = r'((?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]\\d+)?)'\nnumpat\n```\n\n\n\n\n '((?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:[eE][+-]\\\\d+)?)'\n\n\n\n### Define pattern for operators \nThis includes both ordinary python operators and functions. It is important that \n\n\n#### Include names for functions defines in module \n\nUsing introspection functions from a module can be included in the language. The Module **modelBLfunk** contains useful functions. \n\n\n```python\nimport inspect \nimport modelBLfunk # a module from which all functions are included BLL \nBLfunk = [o.upper() for o,t in inspect.getmembers(modelBLfunk)\n if not o.startswith('__') ]\nBLfunk\n```\n\n\n\n\n ['ARRAY',\n 'CLASSFUNK',\n 'CLOGNORM',\n 'EXP',\n 'GAMMA',\n 'INSPECT',\n 'JIT',\n 'LIFETIME_CREDIT_LOSS',\n 'LOG',\n 'LOGIT',\n 'LOGIT_INVERSE',\n 'LOGNORM',\n 'MATRIX',\n 'MV_OPT',\n 'MV_OPT_PROP',\n 'NORM',\n 'NORMCDF',\n 'QGAMMA',\n 'SQRT',\n 'SUM_EXCEL',\n 'TRANSPOSE']\n\n\n\n#### Include names for user specified functions \nIn order to make the language agile. The user can specify functions when creating a model instance. Functions specifies at model creation will be included in the language, and in the model instance. This is done by including the function in a list: funks. \n\nFirst define the a couple of functions to illustrate, how they can be included: \n\n\n```python\ndef the_answer():\n '''The answer to the ultimate question of life, the universe and everything'''\n return 42.0\n\ndef the_ultimate_forward_rate():\n '''Calculate the ultimate forward rate cf. Solvency 2 regulation of insurance'''\n return the_answer/10.0\nfunks = [the_answer, the_ultimate_forward_rate] \n```\n\nNow find the names of the from the list of user defined functions. \n\n\n```python\nnewfunks = [f.__name__.upper() for f in funks]\nnewfunks\n```\n\n\n\n\n ['THE_ANSWER', 'THE_ULTIMATE_FORWARD_RATE']\n\n\n\n#### A list of patterns to match each function\n\n\n```python\nfunkname = 'LOG EXP'.split() + BLfunk + newfunks\nfunkname2 = [i+r'(?=\\()' for i in funkname] # a function is followed by a (\nfunkname2\n```\n\n\n\n\n ['LOG(?=\\\\()',\n 'EXP(?=\\\\()',\n 'ARRAY(?=\\\\()',\n 'CLASSFUNK(?=\\\\()',\n 'CLOGNORM(?=\\\\()',\n 'EXP(?=\\\\()',\n 'GAMMA(?=\\\\()',\n 'INSPECT(?=\\\\()',\n 'JIT(?=\\\\()',\n 'LIFETIME_CREDIT_LOSS(?=\\\\()',\n 'LOG(?=\\\\()',\n 'LOGIT(?=\\\\()',\n 'LOGIT_INVERSE(?=\\\\()',\n 'LOGNORM(?=\\\\()',\n 'MATRIX(?=\\\\()',\n 'MV_OPT(?=\\\\()',\n 'MV_OPT_PROP(?=\\\\()',\n 'NORM(?=\\\\()',\n 'NORMCDF(?=\\\\()',\n 'QGAMMA(?=\\\\()',\n 'SQRT(?=\\\\()',\n 'SUM_EXCEL(?=\\\\()',\n 'TRANSPOSE(?=\\\\()',\n 'THE_ANSWER(?=\\\\()',\n 'THE_ULTIMATE_FORWARD_RATE(?=\\\\()']\n\n\n\n#### And finally the pattern for functions are combined with the pattern for standard operators in Python. \n\n\n```python\nopname = r'\\*\\* != >= <= == [=+-/*@|()$><,.\\]\\[]'.split() # list of ordinary operators \noppat = '('+'|'.join(['(?:' + i + ')' for i in funkname2+opname])+')'\noppat\n```\n\n\n\n\n '((?:LOG(?=\\\\())|(?:EXP(?=\\\\())|(?:ARRAY(?=\\\\())|(?:CLASSFUNK(?=\\\\())|(?:CLOGNORM(?=\\\\())|(?:EXP(?=\\\\())|(?:GAMMA(?=\\\\())|(?:INSPECT(?=\\\\())|(?:JIT(?=\\\\())|(?:LIFETIME_CREDIT_LOSS(?=\\\\())|(?:LOG(?=\\\\())|(?:LOGIT(?=\\\\())|(?:LOGIT_INVERSE(?=\\\\())|(?:LOGNORM(?=\\\\())|(?:MATRIX(?=\\\\())|(?:MV_OPT(?=\\\\())|(?:MV_OPT_PROP(?=\\\\())|(?:NORM(?=\\\\())|(?:NORMCDF(?=\\\\())|(?:QGAMMA(?=\\\\())|(?:SQRT(?=\\\\())|(?:SUM_EXCEL(?=\\\\())|(?:TRANSPOSE(?=\\\\())|(?:THE_ANSWER(?=\\\\())|(?:THE_ULTIMATE_FORWARD_RATE(?=\\\\())|(?:\\\\*\\\\*)|(?:!=)|(?:>=)|(?:<=)|(?:==)|(?:[=+-/*@|()$><,.\\\\]\\\\[]))'\n\n\n\n### Now the expression pattern is created\n\n\n```python\nudtrykpat = numpat + '|' + oppat + '|' + namepat + lagpat\nudtrykpat\n```\n\n\n\n\n '((?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:[eE][+-]\\\\d+)?)|((?:LOG(?=\\\\())|(?:EXP(?=\\\\())|(?:ARRAY(?=\\\\())|(?:CLASSFUNK(?=\\\\())|(?:CLOGNORM(?=\\\\())|(?:EXP(?=\\\\())|(?:GAMMA(?=\\\\())|(?:INSPECT(?=\\\\())|(?:JIT(?=\\\\())|(?:LIFETIME_CREDIT_LOSS(?=\\\\())|(?:LOG(?=\\\\())|(?:LOGIT(?=\\\\())|(?:LOGIT_INVERSE(?=\\\\())|(?:LOGNORM(?=\\\\())|(?:MATRIX(?=\\\\())|(?:MV_OPT(?=\\\\())|(?:MV_OPT_PROP(?=\\\\())|(?:NORM(?=\\\\())|(?:NORMCDF(?=\\\\())|(?:QGAMMA(?=\\\\())|(?:SQRT(?=\\\\())|(?:SUM_EXCEL(?=\\\\())|(?:TRANSPOSE(?=\\\\())|(?:THE_ANSWER(?=\\\\())|(?:THE_ULTIMATE_FORWARD_RATE(?=\\\\())|(?:\\\\*\\\\*)|(?:!=)|(?:>=)|(?:<=)|(?:==)|(?:[=+-/*@|()$><,.\\\\]\\\\[]))|((?:[A-Za-z_{][A-Za-z_{}0-9]*))(?:\\\\(([+-][0-9]+)\\\\))?'\n\n\n\n\n```python\nre.findall(udtrykpat,'a=b+c(-1)')\n```\n\n\n\n\n [('', '', 'a', ''),\n ('', '=', '', ''),\n ('', '', 'b', ''),\n ('', '+', '', ''),\n ('', '', 'c', '-1')]\n\n\n\n\n```python\n\n```\n\nA number of functions are predefined in the modelpattern module.\n\n\n```python\npt.udtryk_parse('a=b(-1)+the_answer()',funks=[the_answer,the_ultimate_forward_rate])\n```\n\n\n\n\n [nterm(number='', op='', var='A', lag=''),\n nterm(number='', op='=', var='', lag=''),\n nterm(number='', op='', var='B', lag='-1'),\n nterm(number='', op='+', var='', lag=''),\n nterm(number='', op='THE_ANSWER', var='', lag=''),\n nterm(number='', op='(', var='', lag=''),\n nterm(number='', op=')', var='', lag='')]\n\n\n\nAnd a model which consists of several formulas is parsed to a structure like this \n\n\n```python\npt.model_parse('''frml <> a = b+2 $ frml <> v = log(x) $''')\n```\n\n\n\n\n [(fatoms(whole='FRML <> A = B+2 $', frml='FRML', frmlname='<>', expression='A = B+2 $'),\n [nterm(number='', op='', var='A', lag=''),\n nterm(number='', op='=', var='', lag=''),\n nterm(number='', op='', var='B', lag=''),\n nterm(number='', op='+', var='', lag=''),\n nterm(number='2', op='', var='', lag=''),\n nterm(number='', op='$', var='', lag='')]),\n (fatoms(whole='FRML <> V = LOG(X) $', frml='FRML', frmlname='<>', expression='V = LOG(X) $'),\n [nterm(number='', op='', var='V', lag=''),\n nterm(number='', op='=', var='', lag=''),\n nterm(number='', op='LOG', var='', lag=''),\n nterm(number='', op='(', var='', lag=''),\n nterm(number='', op='', var='X', lag=''),\n nterm(number='', op=')', var='', lag=''),\n nterm(number='', op='$', var='', lag='')])]\n\n\n\nThe model_parse function takes a model and returns a list of tuples, Each tuple contains:\n\na named (fatoms) tuple of: \n- the complete formula\n- FRML\n- Formula name\n- The expression\n- a list of \n- A list of terms from the expression\n\nCare has been taken to optimize the speed of the tokenizing function. By tokenizing the whole model in one python list comprehension, even quite large models (number of formulas > 600,000) can be tokenized in a few seconds. \n\n\n## An analyzer\nThis function extract information needed to handle the model such as.\n\n- Endogenous and exogenous variables\n- Starting positions in calculating vector. \n- The dependency graphs TG and TE.\n\nThese objects are stored as property in the class instance. Some of the properties like TG and TG can be time consuming to calculate. In these cases \nlazy evaluation is used. This means that computing of the properties is delayed until \nthe property is requested (perhaps implicit) by the user. \n\n## Code generation\nThis phase converts the tokenized model to python code, which can solve the model.\n\nThe purpose is to substitute variable names in the the model formulas to an access to a DataFrame.\n\nIt is\n quite straight forward to write a function, which generates solving\n routines in other languages than Python.\n \nThe code generation phase produces a factory function, which will return the actual calculating function. This methods is chosen in order to manage the namespace in which the calculation function is operating. \n\nIn order to catch calculation errors, the code performing the calculation is braced by a error catching clause. Thus if numerical error such as taking the log of a negative number raises an error, we can identify the offending formula. \n\nFor our little model the factory function looks like this:\n\n## The model structure\n\nThe logival structure of a model is useful for several reasons. The structure of contemperaneous endogenous variable is used to stablish the calculation sequence and identify simultaneous systems. The structure of a model can be seen as a directed graph. All variables are node in the graph. \nIf a variable $b$ is on the right side of the formula defining variable $a$ there is an edge from $a$ to $b$. \n\n### First we define the nodes (vertices) of the dependency graph.\n\nThe set of nodes is the set of relevant variables. Actually we want to look \nat **two dependency graphs**: one containing *all variables*, \nand one only containing *endogenous contemporaneous variable* (the $y^j_t$'s). So we define two sets S and E:\n\n**All endogenous, exogenous, contemporaneous and lagged variables**\n\n$S=\\{y^j_{t-i}|j=1..n,i=1..r \\} \\cup \\{x^j_{t-i}|j=1..k,i=1..s \\}$ \n\n**Contemporaneous endogenous variables**\n\n$E=\\{y^j_{t}|j=1..n \\}$ contemporaneous endogenous variables \n\nNaturally:\n\n$E \\subseteq S$\n\n### Then we define the edges of the dependency graph. \nAgain two sets are relevant: \n\n**From all variables to contemporaneous endogenous variables**\n\n$T = \\{(a,b) | a \\in E, b \\in S\\}$ a is on the right side of b \n\n**From contemporaneous endogenous variables to contemporaneous endogenous variables** \n\n$T_e = \\{(a,b) | a \\in E, b \\in E\\}$ a is on the right side of b \n\n### And we can construct useful dependency graphs\nThe we can define a graph TG which defines the data dependency of the model:\n\n$TG = (S,T)$ The graph defined by nodes S and edges T.\n\nTG can be used when exploring the dependencies in the model. This is useful for the user when drilling down the results. \n\nHowever for preparing the solution a smaller graph has to be used. When solving the model for a specific period both exogenous and lagged endogenous variables are predetermined. Therefor we define the the dependency graph for contemporaneous endogenous variables:\n\n$TE = (E,T_e)$ The graph defined by nodes $S$ and edges $T_e$.\n\nTE is used to determine if the model is simultaneous or not. \n\nIf the model is not simultaneous, then TE have no cycles, that is, it is a \nDirected Acyclical Graph (DAG). Then we can find an order in which the formulas can\nbe calculated. This is called a topological order. \n\nThe topological order is a linear ordering of nodes (vertices) such that for every edge (v,u), node v comes before u in the ordering. \n\nA topological order is created by doing a topological sort of TE. \n\nIf TE, the dependency graph associated with F is **not** a Directed Acyclical Graph (A DAG).\nThen F has contemporaneous feedback and is simultaneous. Or - in Excel speak - the \nmodel has circular references. And we need to use an iterative methods to solve the model. Sometime a model contains several simultaneous blocks. Then each block is a strong element of the graph. Each formula which is not part of a simultaneous bloc is in itself a strong element. \n\nA condensed graph where each strong element is condensed to a node is a DAG. \nSo the condensed graph have a topological order. This can be used when solving the model. \n\nThe dependency graphs are constructed, analyzed and manipulated through the **Networkx** Python library. \n\n### Example dependency graphs\nTo illustrate the different graphs this small model is used.\n\n#### Total dependency graphs\nThis shows $TG$ mentioned above. \n\n\n```python\nmmodel.drawmodel(size=(0.8,0.8),title='Total graph')\n```\n\n\n \n\n \n\n\n### The dependency graph for contemporaneous endogenous variables (TE)\n\n\n```python\nmmodel.drawendo(size=(0.5,0.5),title='Contemporaneous endo')\n```\n\n\n \n\n \n\n\n#### And the adjacency matrix of the graph\nThe graph can also be represented as a adjacency matrix. This is a is a square matrix A. $A_{i,j}$ is one when there is an edge from node i to node j, and zero when there is no edge.\n\nIf the graph is a DAG the adjacency matrix, and the elements are in a topological order, is a lover triangular matrix. \n\n\n```python\na = mn.draw_adjacency_matrix(mmodel.endograph,mmodel.strongorder,mmodel.strongblock,\n mmodel.strongtype,size=(4,4))\n```\n\n### A topological sorted list of contemporaneous endogenous variables (the solve order) \nAlso a property of the model \n\n\n```python\nmmodel.topo\n```\n\n### The dependency graph for contemporaneous endogenous variables, with feedback\nNow lets look at another small model. This time with feedback. \n\n\n```python\nfms = '''\nFRML xx Y = C+I+E-M $ \nFRML xx C = 0.9*Y+Y0 $ \nFRML xx C1 = 0.2*C $\nFRML xx C2 = 0.2*C1 $\nFRML xx M = 0.1*Y + 0.2 * c $\nFRML xx M1 = 0.2*M $\nFRML xx E = 0.1*E0 $\n'''\nmms = mc.model(fms) # make a model instance \nmms.drawendo(size=(0.9,0.9))\n```\n\n### And the adjacency matrix of the graph \nWhen the model has contemporaneous feedback the TE will not be a DAG. There will be strong components with more than 1 node. This mean that the adjacency matix will have elements above the diagonal - like below. \n\nA graph where each strong component is condensed to a node will be a DAG. This can be calculated by ModelFlow. And the user can choose this as solving order. Else the model will be solved in the order in which the model is specified. \n\n\n```python\nmms.plotadjacency(size=(7,7));\n```\n\n\n```python\n# the strong components of the model, DAG's (recursive elements) are condensed\nprint(f'Strong blocks : {mms.strongblock}')\nprint(f'Type of strong blocks : {mms.strongtype}')\n```\n\n## Solution ordering \n\n### For normalized models: \nFor a model **without contemporaneous feedback**, the topoligical sorted order (mentioned abbove) is then used as calculating order. \n\nFor a model **with contemporaneous feedback** and no leaded variables, ModelFlow divides a model into three parts. A recursive **prolog** model, a recursive **epilog** model, the rest is the simultaneous **core** model. Inside the core model the ordering of the equations are preserved. It may be that the core model contains several strong componens, which eachcould be solved as a simultanous system, however it is solved as one simultanous system. \n\nOnly the core model is solved as a simultaneous system. The prolog model is calculated once before the solving og the simultaneous system, the epilog model is calculated once after the solution of the simultanous system. \nFor most models this significantly reduce the computational burden of solving the model. \n\nFor Gauss type solution the ordering of the equations in the core model can be important for the speed of convergence. \n\nFor a model with leaded variables the model is stacked, and a all equations are created equal. For some models it could probably be useful split the model, but it has not been needed yes. \n\nThe cell below displays the variables in the three parts.\n\n\n```python\n# The preorder\nprint(f'The prolog variables {mms.preorder}')\nprint(f'The core variables {mms.coreorder}')\nprint(f'The epilog variables {mms.epiorder}')\n```\n\n### For un-normalized models: \nThe models are solved as one simultanous model. Either by newton - if no leaded variables - or by stacked-newton if the model has leaded variables. \n\n## Construction of Jacobi matrices.\nTo use a Newton type solver the matrix ($\\bf{A}$/$\\bf{\\bar A}$) the derivatives of all formulas with respect to all endogeneous variables is needed. \n\n$\\bf{A}$ but especially $\\bf{\\bar A}$ can be quite large (more than $10.000 \\times 10.000$). So it can look like a daunting task to find the all the values and solve the linear model. However for most economic models $\\bf{A}$ is quite sparse, and by construct $\\bf{\\bar A}$ is very very sparse. Fortunately Python gives access to very efficient sparse libraries. The [Scipy library](https://scipy.org/scipylib/index.html) utilizes the [Intel® Math Kernel Library](https://software.intel.com/en-us/mkl).\nFirst step is to create a new model which calculates the values for all the relevant derivatives. In ModelFlow this can be done by **symbolic**, by **numerical differentiation** or by a combination. \n\nThis entails specifying a model in the business logic language which calculate all the non-zero elements of the $\\bf{A}$/$\\bf{\\bar A}$ \n\nThis is done by in the Newton class, which vil generate a new model instance which can perform the calculations of all the relevant derivatives (non zero derivatives). As an instance of the model class, it will have all the capabilities of this class. In the this derivative model the formula for calculating $\\dfrac{\\partial{numerator }}{{\\partial denominator(-lag)}}$ is written as: \n\n\\< numerator \\>\\_\\_p\\_\\_\\< denominator >\\_\\_lag\\_\\_\\< lag\\> = derivative expression\n\n### A small Solow model \nAn example can be helpful \nFirst a small model is defined - in this case a solow growth model: \n\n\n```python\nfsolow = '''\\\nY = a * k**alfa * l **(1-alfa) \nC = (1-SAVING_RATIO) * Y \nI = Y - C \ndiff(K) = I-depreciates_rate * K(-1)\ndiff(l) = labor_growth * L(-1) \nK_i= K/L '''\nmsolow = model.from_eq(fsolow)\nprint(msolow.equations)\n```\n\n### Create some data and solve the model \n\n\n```python\nN = 100\ndf = pd.DataFrame({'L':[100]*N,'K':[100]*N})\ndf.loc[:,'ALFA'] = 0.5\ndf.loc[:,'A'] = 1.\ndf.loc[:,'DEPRECIATES_RATE'] = 0.05\ndf.loc[:,'LABOR_GROWTH'] = 0.01\ndf.loc[:,'SAVING_RATIO'] = 0.05\nmsolow(df,max_iterations=100,first_test=10,silent=1);\n```\n\n### Create an diffirentiation instance of the model\nActually 2 instances are made, one which use symbolic differentiation one which use numerical differentiation. \n\n\n```python\nfrom modelnewton import newton_diff\nmsolow.smpl(3,4) # we only want a few years \nnewton = newton_diff(msolow)\nnewton2 = newton_diff(msolow,forcenum=1)\n```\n\n\n```python\nprint(newton.diff_model.equations)\n```\n\n\n```python\nprint(newton2.diff_model.equations)\n```\n\n### Display the full stacked matrix\nTo make the sparcity clear all zero values are shown as blank \n\n\n\n```python\nstacked_df = newton2.get_diff_df_tot()\nstacked_df.applymap(lambda x:f'{x:,.2f}' if x != 0.0 else ' ')\n```\n\n### Display the element of the sparse matrix\n\n### The results can also be displayed in a more user friendly way\n\n\n```python\nnewton.show_diff_latex()\n```\n\n## Speeding up solving through Just In Time compilation (Numba)\nPython is an interpreted language. Therefor the calculation speed can be improved. There are several avenues to speed up calculations. \n\nFirstly, use the matrix extensions if possible. This will force the use of the highly optimized routines in the \nNumpy library. \n\nSecondly, python code can be compiled. The most straight forward way is to use the \n**Numba** library. For simultaneous models which only operates on numerical data the \nuser can specify jit=1. This will engage the numba Just In \nTime Compiler and the model will solve significantly faster. However the compilation will \ntake some time and for large models Numba will choke on the model. Experience with a Danish model (1700 equations) shows a speedup from 5 million floating point \noperations per second (MFlops) to 800 MFlops. \n\nAlso experiments with the **Cython** library has been performed. This library will translate the Python code to C++ code. Then a C++ compiler can compile the code and the run time will be improved a lot. \n\n### Optimizing access to DataFrame values\n**Execution speed is crucial.** Values in a DataFrame can be\naccessed in a number of ways. Some are fast, others are not. Therefore, some care has been exercised\nwhen accessing each value. \n\nIf we have a DataFrame df and a column with the name 'FY', the value in 2018 can be\naccessed like this: df.loc\\[2018,'FY'\\], This works fine for small models. However it is quite slow as the DataFrame\nhas to look up the position (row,column) of 2018 and 'FY' before it can\naccess the value in an underlying structure. When looking for the value for 2019 the Dataframe again has to to the lookup. \n\nWhen calculating simple (non simultaneous) models, the row and column of each value is\nresolved before the code generation and the value is accessed directly\nin an underlying property of dataframes called values. So if FY is the 42 column of the DataFrame and the position of 2018 is assigned to the variable row. The value is accessed as df.values\\[row,42\\]. In this case no time is wasted for looking up the row and column of the position. \n\nWhen using the iterative Gauss-Seidel solution method, all necessary\nvalues are transferred to a one-dimensional numpy calculation array - called a. So the value would just be accessed like: a\\[84\\]. This requires some overhead to stuff and unstuff the values from df. But data access is faster, as accessing elements in a one-dimensional array\nis faster than in a two-dimensional array. Also, the locality of data is\nincreased, thus the chance of a cache miss is reduced. This is especially important if the model is compiled. \n\n# Some Model manipulation capabilities \n\n## Model inversion aka Target/instruments or Goal Seek \nIn ordet to answer questions like: \n\n- How much capital has to be injected in order to maintain a certain GDP level in a stressed scenario? \n- How much loans has to be shredded by the banks in order to maintain a minimum level of capital (slim to fit)? \n- How much capital has to be injected in order to keep all bank above a certain capital threshold ?\n\nThe model instance is capable to **\"invert\"** a model. To use the terminology of Tinbergen(1955) that is to calculate the value of some exogenous variables - **the instruments** which is required in order to achieve a certain target value for some endogenous variables - **the targets**. \n\nTo use the terminology of Excel it is a goal/seek functionality with multiple cells as goals and multiple cells as targets. \n\nThe problem can be thought as follows: From the generic description of a model: $\\textbf{y}_t= \\textbf{F}(\\textbf{x}_{t})$. Here $\\textbf{x}_{t}$ are all predetermined variables - lagged endogenous and all exogenous variables. \n\nIn some models the result depends on the level of exogenous variables with a lag. For instance in a disease spreading model, the *number of infected* on a day depends on the *probability of transmission* some days before. If the *probability of transmission* is the instrument and the *number of infected* is the target. Therefor it can be useful to allow a **delay**, when finding the instruments. In this case we want to look at $\\textbf{y}_t= \\textbf{F}(\\textbf{x}_{t-delay})$ \n\nThink of a condensed model ($\\textbf{G}$) with a few endogenous variables($\\bar{\\textbf{y}}_t$):\nthe targets and a few exogenous variables($\\bar{\\textbf{x}}_{t-delay}$): the instrument variables. All the rest of the predetermined variables are fixed: \n$\\bar{\\textbf{y}}_t= \\textbf{G}(\\bar{\\textbf{x}}_{t-delay})$\n\nIf we invert G we have a model where instruments are functions of targets:\n$\\bar{\\textbf{x}_{t-delay}}= \\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}})$. Then all we have to do is to find\n$\\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}})$\n\n### And how to solve for the instruments \nFor most models $\\bar{\\textbf{x}}_{t-delay}= \\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}})$ do not have a nice close form solution. However it can be solved numerically. We turn to Newton–Raphson method.\n\nSo $\\bar{\\textbf{x}}_{t-delay}= \\textbf{G}^{-1}(\\bar{\\textbf{y}_{t}^*})$ will be found using :\n\nfor $k$ = 1 to convergence \n\n>$\\bar{\\textbf{x}}_{t-delay,end}^k= \\bar{\\textbf{x}}_{t-delay,end}^{k-1}+ \\textbf{J}^{-1}_t \\times (\\bar{\\textbf{y}_{t}^*}-\n\\bar{\\textbf{y}_{t}}^{k-1})$\n\n>$\\bar{\\textbf{y}}_t^{k}= \\textbf{G}(\\bar{\\textbf{x}}_{t-delay}^{k})$\n\nconvergence: $\\mid\\bar{\\textbf{y}_{t}^*}-\n\\bar{\\textbf{y}_{t}}\n\\mid\\leq \\epsilon$\n\nNow we just need to find: \n\n$\\textbf{J}_t = \\frac{\\partial \\textbf{G} }{\\partial \\bar{\\textbf{x}}_{t-delay}}$\n\nA number of differentiation methods can be used (symbolic, automated or numerical). ModelFlow uses numerical differentiation, as it is quite simple and fast.\n\n$\\textbf{J}_t \\approx \\frac{\\Delta \\textbf{G} }{\\Delta \\bar{\\textbf{x}}_{t-delay}}$\n\nThat means that we should run the model one time for each instrument, and record the \neffect on each of the targets, then we have $\\textbf{J}_t$ \n\nIn order for $\\textbf{J}_t$ to be invertible there has to be the same number of targets and instruments. \n\nHowever, each instrument can be a basket of exogenous variable. They will be adjusted in fixed proportions. This can be useful for instance when using bank leverage as instruments. Then the leverage instrument can consist of several loan types. \n\nYou will notice that the level of $\\bar{\\textbf{x}}$ is updated (by $\\textbf{J}^{-1}_t \\times (\\bar{\\textbf{y}_{t}^*}-\n\\bar{\\textbf{y}_{t}}^{k-1})$) in all periods from $t-delay$ to $end$, where $end$ is the last timeframe in the dataframe. This is useful for many applications including calibration of disease spreading models and in economic models, where the instruments are level variable (i.e. not change variables). If this is not suitable, it can be changed in a future release. \n\nThe target/instrument functionality is implemented in the python class `targets_instruments` specified in **ModelFlows** `modelinvert` module. \n\n### An example\nThe workflow is as follow:\n\n1. Define the targets\n2. Define the instruments \n3. Create a target_instrument class istance\n4. Solve the problem \n\nStep one is to define the targets. This is done by creating a dataframe where the target values are set. In this case it can be done like this. \n\n\n```python\nmmodel.basedf\n```\n\n\n```python\ntarget = mmodel.basedf.loc[2020:,['D3','D1']]+[1,10]\ntarget\n```\n\nThen we have to provide the instruments. This is **a list of list of tuples**. \n- Each element in the outer list is an instrument. \n- Each element in the inner list is an instrument variable \n- Each element of the tuple contains a variable name and the associated impulse $\\Delta$. \n\nThe $\\Delta variable$ is used in the numerical differentiation. Also if one instrument contains several variables, the proportion of each variable will be determined by the relative $\\Delta variable$. \n\nFor this experiment the inner list only contains one variable. \n\n\n```python\ninstruments = [ [('C',1)] , [('B',1)]]\n```\n\nNow we run the eksperiment \n\nFor models which are relative linear we don't need to update 𝐉𝑡 for each iteration and time frame. As our small toy model is nonlinear, the jacobi matrix has to be updated frequently. This is controlled by the nonlin=True option below.\n\n\n```python\nresult = mmodel.invert(mmodel.lastdf,target,instruments,nonlin=True)\nresult\n```\n\nAnd do the result match the target?\n\n\n```python\nresult-target\n```\n\nSo we got results for the target variable very close to the target values. \n\n### Shortfall targets\nAbove the target for each target variable is a certain values. Sometime we we need targets being above a certain shortfall value. In this case an instrument should be used to make the achieve the target threshold only if the target is belove the target. This is activated by an option:**shortfall=True**.\n\nThis feature can be useful calculating the amount of deleverage needed for banks to achieve a certain threshold of capital. \n\n## Attribution / Explanation \n\nExperience shows that it is useful to be able to explain the difference between the result from two runs. \nThe first level of understanding the difference is to look at selected formulas and find out, how much each input variables accounts for. \nThe second level of understanding the difference is to look at the attribution of the \nexogenous variables to the results of the model. \n\nIf we have:\n\n$y = f(a,b)$\n\nand we have two solutions where the variables differs by $\\Delta y, \\Delta a, \\Delta b$\n\nHow much of $\\Delta y$ can be explained by $\\Delta a$ and $\\Delta b$ ?\n\nAnalytical the attributions $\\Omega a$ and $\\Omega b$ can be calculated like this: \n\n$\\Delta y = \\underbrace{\\Delta a \\dfrac{\\partial {f}}{\\partial{a}}(a,b)}_{\\Omega a} + \n\\underbrace{\\Delta b \\dfrac{\\partial {f}}{\\partial{b}}(a,b)}_{\\Omega b}+Residual$\n\nModelFlow will do a numerical approximation of $\\Omega a$ and $\\Omega b$. This is done by looking at the two runs of the model:\n\n\\begin{eqnarray} \ny_0&=&f(a_{0},b_{0}) \\\\\ny_1&=&f(a_0+\\Delta a,b_{0}+ \\Delta b)\n\\end{eqnarray}\n\nSo $\\Omega a$ and $\\Omega b$ can be determined:\n\n\\begin{eqnarray} \n\\Omega f_a&=&f(a_1,b_1 )-f(a_1-\\Delta a,b_1) \\\\\n\\Omega f_b&=&f(a_1,b_1 )-f(a_1,b_1-\\Delta b)\n\\end{eqnarray}\n\n\n\nAnd: \n\n\\begin{eqnarray}\nresidual = \\Omega f_a + \\Omega f_b -(y_1 - y_0) \n\\end{eqnarray}\nIf the model is fairly linear, the residual will be small. \n\n### Formula attribution\nAttribution analysis on the formula level is performed by the method **.dekomp**. \n\nThis method utilizes that two attributes .basedf and .lastdf containing the first and the last run are contained in the model instance. Also all the formulas are contained in the instance. Therefore a model, just with one formula - is created. Then experiments mentioned above is run for each period and each right hand side variable. \n\n\n```python\n_ = mmodel.dekomp('D1')\n```\n\nIf the baseline dataframe is set to the lagged variable of the last dataframe. We can \ncalculate the attributions to the change of results from time period to time period. \n\n### Walk the explanations. \nSometime we want to trace the attributions to variables in higher in the dependency graph. \n\nUsing the dependency graph TG, we can walk up the graph, and do an attribution calculation for each of the parents, grand parents and so on. \n\nIt should be mentioned that for *lagged* endogenous variable an attribution calculation will not be performed. \n\nSo we use the **.explain** method. \n\nThe result will also be made into a vector graphic both in .pdf and .svg format. This allows for zooming into the tree, even if there are many leaves. \n\n\n```python\n_ = mmodel.D1.explain(up=2)\n```\n\n### Model Attribution\n\nAt the model level we start by finding which exogenous variables have changed between two runs.\n\n\n```python\ndifdf = mmodel.exodif()\ndifdf\n```\n\nNow we make a dictionary of experiments where the key is the name of the\nexperiment and the value of each entry is the variable to investigate in the experiment \n\n\n```python\nexperiments = {e : [e] for e in difdf.columns}\nexperiments \n```\n\nThen we can let the model run through each experiment and record a number of summary\nvariable. \n\n\n```python\nimpact = md.attribution(mmodel,experiments,start=2019,end=2021,summaryvar=['D*'])\nimpact\n```\n\n\n```python\nimpact['C',2021]\n```\n\n\n```python\nfor sumaryvar in impact.index:\n mv.attshow(md.GetAllImpact(impact, sumaryvar),tshow=0,t=False,annot=True,dec=1,\n title='Impact on: '+sumaryvar,size=(3,3),showsum=True,head=1,tail=1)\n```\n\nWhen the results are displayed, they can be filtered, sliced and diced in a number of ways. \n\nFor a model of the EBA stress test the number of changed exogenous variable can be large. Using a dictionary to contain the experiments allows us to create experiments where all variable for each country are analyzed, or each macro variable for all countries are analyzed. \n\nAlso it is possible to use aggregated sums - useful for looking at impact on PD's. Or just the last time period - useful for looking at CET1 ratios. \n\nIf there are many experiments, data can be filtered in order to look only at the variables with an impact above a certain threshold. \n\nThe is also the possibility to anonymize the row and column names and to randomize\nthe order of rows and/or columns - useful for bank names. \n\n## Optimization \nUsing the convex optimization package CVXOPT, which is part of the Anaconda Python distribution a range of optimization problems can be solved. One example is the standard mean variance problem. \n\n### A mean variance problem\n\nIf we look at a fairly general mean variance optimization problem which has been adopted to banks it looks like this: \n\n\\begin{eqnarray} \n\\mathbf x & &\\mbox{Position in each asset(+)/liability(-) type}\\\\\n\\mathbf x & &\\mbox{Position in each asset(+)/liability(-) type}\\\\\n\\mathbf \\Sigma & &\\mbox{Covariance matrix} \\\\\n\\mathbf r & &\\mbox{Return vector}\\\\\n\\lambda & &\\mbox{Risk aversion}\\\\\n\\mathbf{riskweights}& &\\text{Vector of risk weights, liabilities has riskweight = 0}\\\\\nCapital& &\\mbox{Max of sum of risk weighted assets}\\\\\n\\mathbf{lcrweights}& &\\text{Vector of LCR weights, liabilities has lcrweight = 0}\\\\\nLCR& &\\text{Min of sum of lcr weighted assets}\\\\\n\\mathbf{leverageweight}&&\\text{Vector of leverage weights, liabilities has leverageweight = 0}\\\\\nEquity&&\\mbox{Max sum of leverage weighted positions}\\\\\nBudget&&\\mbox{initial sum of the positions}\\\\\n\\end{eqnarray}\n\n\\begin{eqnarray}\n\\mbox{minimize:} & \\lambda \\mathbf x^T \\mathbf \\Sigma \\mathbf x - (1-\\lambda) \\mathbf r^T \\mathbf x & \\mbox{If }\\lambda \\mbox{ = 1 minimize risk, if } \\lambda\\mbox{ = 0 maximize return }\\\\\n\\mbox{subject to:} & \\mathbf x \\succeq \\mathbf{x^{min}} &\\mbox{Minimum positions}\\\\ \n & \\mathbf x \\preceq \\mathbf{x^{max}} &\\mbox{Maximum positions}\\\\ \n & \\mathbf{riskweights}^T\\mathbf x \\leq Capital &\\mbox{Risk weighted assets <= capital}\\\\ \n & \\mathbf{lcrweights}^T\\mathbf x \\geq LCR &\\mbox{lcr weighted assets >= LCR target}\\\\ \n & \\mathbf{leverageweight}^T\\mathbf x \\leq equity &\\mbox{leverage weighted assets <= equity}\\\\ \n & \\mathbf 1^T\\mathbf x = Budget & \\mbox{Sum of positions = B}\n\\end{eqnarray}\n\n\n### The mean variance problem in the business language language \n\nIn the business logic language this problem can be specified like this:\n\n``` \npositions = mv_opt(msigma,return,riskaversion, budget, \n [[risk_weights] , [-lcr_weights] , [leverage_weights]],\n [capital, -lcr , equity] ,min_position,max_position) \n```\n\nWhere the arguments are appropriately dimensioned CVX matrices and vectors. \n\nFor a more elaborate example there is an special notebook on the subject of optimization.\n\nAlso it should be mentioned that there is an expansion of the basic problem taking transaction cost into account. \n\n\n## Symbolic model differentiation \nModelFlow have the capability to calculate expressions for differentiation of the formulas \nof a model. This is done by the Python symbolic math library **Sympy**. After finding the \nexpressions for the differential coefficients they can be evaluated - just like the model. Based on these a linearized \nversion of the model can be constructed. \n\nWe want to be able to find he Jacobi matrices:\n\n\\begin{eqnarray} \n\\textbf{A} & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_t^T} \\\\ \\\\\n\\textbf{E}_i & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{y}_{t-i}^T } \\hspace{5 mm} i=1, \\cdots , s \\\\ \\\\\n\\textbf{F}_j & = & \\frac{\\partial \\textbf{F}}{\\partial \\textbf{x}_{t-j} ^T} \\hspace{5 mm} j=0, \\cdots , r \n\\end{eqnarray}\n\nThese matrices can be useful when finding stability properties. \n\nNow lets differentiate our toy model \n\n\n```python\nmdif.modeldiff(mmodel)\n```\n\nNow we can display the expressions for the differential coefficient - and the values in a selected time (row), in this case 2018.\n\n\n```python\nmdif.display_all(mmodel,mmodel.basedf,2018)\n```\n\nAlso the matrices of differential coefficient (Jacobi matrices) for each lag, can be calculated\n\n\n```python\n# calculate \nmatdir = mdif.calculate_allmat(mmodel,mmodel.basedf,2018)\n# Display \nfor l,m in matdir.items():\n print(f'Lag:{l} \\n {m} \\n')\n```\n\nWe can carve out the matrices only for the endogenous variables. The A and E matrices mentioned above \ncan be extracted like this: \n\n\n```python\nfor l,m in matdir.items():\n endomat = m.loc[:,[c for c in m.columns if c in mmodel.endogene]]\n print(f'Lag:{l} \\n {endomat} \\n')\n```\n\nA word of caution. \n\nSymbolic math can take time if the model is large. So it is advisable to test this feature on a small model which \ncaptures the essence before moving to a large model. \n\nAlso the Sympy library will only handle functions and expressions that it knows. \n\n## Stability\nJacobi matrices can be used to evaluate the stability properties of the model. To do this we first look at a linearized version of the model. We are interested in the effect of shocks to the system. Will shocks be \ndamped or will they be amplified. \n\nTo calculate the effect of small perturbations the model can be linearized around a solution\n\n\\begin{eqnarray*} \n\\Delta y_t & = & A \\Delta y_t + E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t + \\cdots +F_s \\Delta x_{t-s} \\\\\nI\\Delta y_t-A \\Delta y_t & = & \\hphantom{A \\Delta y_t +}E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F _0\\Delta x_t + \\cdots +F_s \\Delta x_{t-s} \\\\ \n(I-A)\\Delta y_t & = & \\hphantom{A \\Delta y_t +}E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t + \\cdots +F_s \\Delta x_{t-s} \\\\ \n\\Delta y_t & = & (I-A)^{-1}(E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t + \\cdots +F_s \\Delta x_{t-s}) \\\\\n\\Delta y_t & = & (I-A)^{-1}E_1 \\Delta y_{t-1} + \\cdots +(I-A)^{-1}E_r \\Delta y_{t-r} + (I-A)^{-1}F_0 \\Delta x_t + \\cdots +(I-A)^{-1}F_s \\Delta x_{t-s} \\\\\n\\end{eqnarray*}\n\n\n\n\\begin{eqnarray*} \ny_t & = & F(y_t \\cdots y_{t-r},x_t \\cdots x_{t-s}) \\\\\n\\Delta y_t & = & (I-A)^{-1}E_1 \\Delta y_{t-1} + \\cdots +(I-A)^{-1}E_r \\Delta y_{t-r} + (I-A)^{-1}F_0 \\Delta x_t + \\cdots +(I-A)^{-1}F_s \\Delta x_{t-s}\n\\end{eqnarray*}\n\nwhere:\n\n\\begin{eqnarray*}\nA & = & \\frac{\\partial F}{\\partial y_t^T} \\\\ \\\\\nE_i & = & \\frac{\\partial F}{\\partial y_{t-i}^T } \\hspace{5 mm} i=1, \\cdots , r\\\\ \\\\\nF_j & = & \\frac{\\partial F}{\\partial x_{t-j} ^T} \\hspace{5 mm} j=0, \\cdots , s\\\\ \\\\\n\\end{eqnarray*}\n\n\n\nWe have\n\n\\begin{eqnarray*} \ny_t & = & F(y_t \\cdots y_{t-r},x_t \\cdots x_{t-s}) \\\\\n\\Delta y_t & = & (I-A)^{-1}E_1 \\Delta y_{t-1} + \\cdots +(I-A)^{-1}E_r \\Delta y_{t-r} + (I-A)^{-1}F_0 \\Delta x_t + \\cdots +(I-A)^{-1}F_s \\Delta x_{t-s} \\\\\n\\end{eqnarray*}\n\nA rather messy problem. It can be made more simple. This is done by making a new linear model only incorporating \nvariables with one lag. \n\nThis is done the standard way by introducing new variables: $y^{1 }_{t}=y_{t-1}$,\n$y^{2}_{t}=y^1_{t-1}$, and $y^{3}_{t}=y^2_{t-1}$ Using theese transformed variables, \na system with max lag of 3 can e rewritten like this: \n\n$\\underbrace{\n\\left[\\begin{matrix}\n\\Delta y^{3} _{t}\\\\\\Delta y^{2 }_{t}\\\\\\Delta y^{1 }_{t}\\\\\\Delta y_{t}\n\\end{matrix}\\right]}_{\\Delta \\bar y_t }=\n\\underbrace {\\left[\\begin{matrix}{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & A\\end{matrix}\\right]}_{\\bar A} \n\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t}\\\\\\Delta y^{2 }_{t}\\\\\\Delta y^{1 }_{t}\\\\\\Delta y_{t}\n\\end{matrix}\\right]}_{\\Delta \\bar y_t} +\n\\underbrace{\\left[\\begin{matrix}{0} & \\mathbb{I} & {0} & {0}\\\\{0} & {0} & \\mathbb{I} & {0}\\\\{0} & {0} & {0} & \\mathbb{I}\\\\E_{3} & E_{2} & E_{1} & E\\end{matrix}\\right]}_{\\bar E}\n\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t-1}\\\\\\Delta y^{2 }_{t-1}\\\\\\Delta y^{1 }_{t-1}\\\\\\Delta y^{ }_{t-1}\n\\end{matrix}\\right]}_{\\Delta \\bar y_{t-1}} +\n\\underbrace {\\left[\\begin{matrix}{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\F_{3} & F_{2} & F_{1} & F_{0}\\end{matrix}\\right]}_{\\bar F}\n\\underbrace {\\left[\\begin{matrix}\\Delta x_{t-3}\\\\\\Delta x_{t-2}\\\\\\Delta x_{t-1}\\\\\\Delta x_{t\\hphantom{-1}}\\end{matrix}\\right]}_{\\bar x_t}$\n\n\n\nSo this expression:\n\n$\\Delta y_t = A \\Delta y_t + E_1 \\Delta y_{t-1} + \\cdots +E_r \\Delta y_{t-r} + F_0 \\Delta x_t + \\cdots +F_r \\Delta x_{t-r}$\n\n\nHas been simplified to this expression :\n\n$\\Delta \\bar y_t = \\bar A \\Delta \\bar y_t + \\bar E \\Delta \\bar y_{t-1} + \\bar F \\Delta \\bar x_t$\n\n\nIt can be solved, so we only get the: $\\Delta \\bar y_t$ on the left hand side:\n\n$\\Delta \\bar y_t = (I-\\bar A)^{-1}\\bar E \\Delta \\bar y_{t-1} + (I-\\bar A)^{-1}\\bar F \\Delta \\bar x_t$\n\n$\\mbox{This expression :} \\\\\\Delta \\bar y_t = (I-\\bar A)^{-1}\\bar E \\Delta \\bar y_{t-1} + (I-\\bar A)^{-1}\\bar F \\Delta \\bar x_t$ \n\nWhich can be written this way:\n\n$\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t}\\\\\\Delta y^{2}_{t}\\\\\\Delta y^{1}_{t}\\\\\\Delta y_{t}\n\\end{matrix}\\right]}_{\\Delta \\bar y_t}=\n\\underbrace{\\left[\n\\begin{matrix}{0} & \\mathbb{I} & {0} & {0}\\\\{0} & {0} & \\mathbb{I} & {0}\\\\{0} & {0} & {0} & \\mathbb{I}\\\\\\left(\\mathbb{I} - A\\right)^{-1} E_{3} & \\left(\\mathbb{I} -A\\right)^{-1} E_{2} & \\left(\\mathbb{I}- A\\right)^{-1} E_{1} & \\left(\\mathbb{I}- A\\right)^{-1} E\\end{matrix}\n\\right]}_{ \\mbox{companion matrix}=(I-\\bar A)^{-1}\\bar E}\n\\underbrace{\\left[\\begin{matrix}\n\\Delta y^{3} _{t-1}\\\\\\Delta y^{2 }_{t-1}\\\\\\Delta y^{1 }_{t-1}\\\\\\Delta y^{ }_{t-1}\n\\end{matrix}\\right]}_{\\Delta \\bar y_{t-1}}\n+ \\\\\n\\underbrace{\\left[\\begin{matrix}{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\{0} & {0} & {0} & {0}\\\\\\left(\\mathbb{I} - A\\right)^{-1} F_{3} & \\left(\\mathbb{I} - A\\right)^{-1} F_{2} & \\left(\\mathbb{I} - A\\right)^{-1} F_{1} & \\left(\\mathbb{I} - A\\right)^{-1} F_{0}\\end{matrix}\\right]}_{(I-\\bar A)^{-1}\\bar F} \n\\underbrace{\\left[\\begin{matrix}\\Delta x_{t-3}\\\\\\Delta x_{t-2}\\\\\\Delta x_{t-1}\\\\\\Delta x_{t\\hphantom{-1}}\\end{matrix}\\right]}_{\\Delta \\bar x_t}$\n\nSo now we have a linear model with only one lag. For this kind of models the dynamic behavior can be \nevaluated by looking at the eigenvalues $e_t$ of $((I-\\bar A)^{-1}\\bar E )$ \n\nIf all $\\lvert e_t \\lvert < 1$ the system will converge. If at least one of the eigenvalues is larger than one, the system will explode. $e_t$ can are complex numbers. If at least one $e_t$ has an imaginary part the system will oscillate - either dampened if all $\\lvert e_t \\lvert < 1$ or exploding if one $\\lvert e_t \\lvert > 1$.\n\nThe eigenvalues and associated eigenvectors can be found by the function mdif.get_eigen which will be used below.\n\n### Example: Samuelson multiplier accelerator model \nTo illustrate the feature this small classic model is created in a function which will display the results and a polar plot of the complex eigenvalues. \n\nThen experiment with different parameter values are performed in order to establish if shocks are \namplified or dampened and if shocks will induce oscillations or not. \n\n\n```python\ndef geteigen(mul,acc,years=100,show=False):\n '''Function which creates a Samuelson Multiplier accelerator model, runs it\n and alculates the eigenvalues for the compaignion matrix in order to \n evaluate stability. \n \n A polar plot of the compex eigenvalues and graphs of the endogenous variables can \n be displayes '''\n \n fam = f'''\n frml <> y = c+i $ \n frml c = {mul} * y(-1) $\n frml <> i = {acc} * (c-c(-1)) + im $'''\n\n mma = mc.model(fam,modelname = 'Accelerator multiplicator model')\n df = pd.DataFrame([[1000,200]]*years,index=range(2018,2018+years),columns=['Y','IM'])\n start = mc.model(f'c = {mul} * y(-1)')(df,silent=True) # Generate lagged variables for c \n base = mma(start,silent=True) # Solve the model \n\n compeig=mdif.get_eigen(mma,base,2021) # find the eigenvalues and eigenvectors \n if show:\n mdif.eigplot(compeig[0]) # show the eigenvalues \n _ = mma[['Y','C','I']].plot() # Show the solution\n \n return \n```\n\n#### Stability \nAll eigenvalues shorter than 1 and no imaginary parts \n\n\n```python\ngeteigen(mul=0.5,acc=0,years=30,show=1)\n```\n\n#### Explosion \nAt least one eigenvalues above 1 no imaginary part\n\n\n```python\ngeteigen(mul=0.9,acc=2,years=30,show=1)\n```\n\n#### Exploding oscillations\nAt least one eigenvalue above 1 and imaginary parts\n\n\n```python\ngeteigen(mul=0.6,acc=2,years=30,show=1)\n```\n\n#### Perpetual oscillations \nEigenvalues at 1 with imaginary part\n\n\n```python\ngeteigen(mul=0.5,acc=2,years=30,show=1)\n```\n\n#### Dampened oscillations \nAll eigenvalues below 1 and imaginary parts\n\n\n```python\ngeteigen(mul=0.7,acc=1,years=30,show=1)\n```\n\nUsing this feature. ModelFlow can be used to analyze how different feedback parameters will impact stability.\nOf cause it requires that the model is differentiable, and for large models the analysis can take time and a lot of RAM. \n\n# Onboarding data \nThe Pandas library really shines when it comes to retrieving and wrangling data. How to get data on board is very specific for each model and data source. There are many great books on using Pandas for data wrangling. So it is beyond the scope of this notebook to go into details on this subject. However, it is useful to go through some naming advice and a broad description of how data can be transformed to the right format. \n\nModelFlow need to get the data as a wide Pandas DataFrame. Each row is one time frame. Each columns s a variable. \n\nThere are no limits to the length of column names. Therefor column names can be constructed meaningful. a column name should start with a letter then it can be followed by any numbers of letters, digits or \\_. Letters have to be upper case. If lower case letters are used in the Business logic, they will be converted to upper case. \n\nOften variables reflect a number of different dimensions. When naming variables separate the dimensions by a separator string. \n\n$\\underbrace{REA\\_NON\\_DEF}_{type}\\_\\_ \n\\underbrace{DECOM}_{bank}\\_\\_\n\\underbrace{DE}_{Country}\\_\\_\n\\underbrace{HH\\_OTHER\\_NSME\\_AIRB}_{Sector}$\n\nNaming variables along dimensions is supported by ModelFlows slicing methods. Slicing allows for filtering of \nvariables with the help of wildcards like * and ?. \n\nmodel\\['REA\\_NON\\_DEF\\_\\_\\*\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB'\\] will return a dataframe with all columns where:\n\n- type = REA\\_NON\\_DEF\n- banks = all \n- country= DE\n- sector = HH_OTHER_NSME_AIRB \n\nIf we would limit the results to German banks we just write: \n\nmodel\\['REA\\_NON\\_DEF\\_\\_DE???\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB'\\] \n\n\n## From tall to wide dataframes:\nTypically the necessary wide dataframe is constructed from a tall DataFrame. In this tall dataframe has a row for each value and a column for each dimension - including time. If we just look at the few rows related to the variable mentioned above, it could look like this. (of course mock data) \n\n| value | year | type | bank | county | sector |\n|-------:|-----:|-----:|-----:| ------:| ------: |\n|. | .|.|.| .|. |\n|. | .|.|.| .|. |\n|1.00 | 2018|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|2.22 | 2019|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|3.33 | 2020|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|4.44 | 2021|REA\\_NON\\_DEF|DECOM|DE|HH\\_OTHER\\_NSME\\_AIRB |\n|. | .|.|.| .|. |\n|. | .|.|.| .|. |\n\nFirst step is to create a new dataframe with only the value, the year and the variable name. The variable name (varname) is constructed by joining the dimensions and separate them by '__' \n\n| value | year | varname |\n|-------:|-----:|-----: |\n|. | .|.|\n|. | .|.|\n|1.00| 2018|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|2.22| 2019|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|3.33| 2020|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|4.44| 2021|REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB|\n|. | .|.|\n|. | .|.|\n\nThen the dataframe is pivoted keeping the year dimension. Now the wide dataframe (ignoring all the other columns) for this variable could look like this:\n\n| YEAR | ... | REA\\_NON\\_DEF\\_\\_DECOM\\_\\_DE\\_\\_HH\\_OTHER\\_NSME\\_AIRB| ... |\n|-------:|-----:|-----: | ------: |\n| 2018|...|1.00 |...|\n| 2018|...|2.22 |...|\n| 2018|...|3.33 |...|\n| 2018|...|4.44 |... |\n\n\nA wide dataframe like this can be used as input to a ModelFlow model, so we are in business. \n\n# Summary\nModelFlow allows easy implementation of models in Python, Which is a powerful and agile language. ModelFlow leverage on the rich ecosystem of Python in order to: \n\n- Separates the specification of a model and the code which solves the model. So the user can concentrate on the economic and not the implementation of the model.\n- Can include user specified Python function in the model definition. \n- Can solve very large models\n- Can solve simultaneous models.\n- Keeps tab on the dependencies of the formulas. This allows for easy Tracing of results. \n- Can perform model inversion (goal seek) with multiple targets and instruments\n- Can attribute changes in results to input variables. Both for individual formulas and the complete model \n- Can include optimizing behavior \n \nThe purpose of this notebook has been to give a broad introduction to model management using ModelFlow. \nUsing the tool requires some knowledge of python. The required knowledge depends on the complexity of the model. So ModelFlow can be used in Python training. \n\nTo get more in-depth knowledge there is a Sphinx based documentation of the library. There you can find the \ncalling conventions and documentation of all elements.\n\nAll suggestions and recommendations are welcome \n\n# Literature:\n\n\nAho, Lam, Sethi, Ullman (2006), Compilers: Principles, Techniques, and\nTools (2nd Edition), Addison-Wesley\n\nBerndsen, Ron (1995), [Causal ordering in economic\nmodels](https://kundoc.com/pdf-causal-ordering-in-economic-models-.html),\nDecision Support Systems 15 (1995) 157-165\n\nDanmarks Nationalbank (2004), [MONA -- a quarterly model of Danish\neconomy](http://www.nationalbanken.dk/da/publikationer/Documents/2003/11/mona_web.pdf)\n\nDenning, Peter J. (2006), [The Locality\nPrinciple](http://denninginstitute.com/pjd/PUBS/locality_2006.pdf),\nChapter in *Communication Networks and Systems* (J Barria, Ed.).\nImperial College Press\n\nGilli, Manfred (1992), [Causal Ordering and Beyond, International\nEconomic Review, Vol. 33, No. 4 (Nov., 1992), pp.\n957-971](http://www.jstor.org/stable/2527152?seq=1#page_scan_tab_contents)\n\nMcKinney, Wes (2011),[pandas: a Foundational Python Library for Data Analysis and\nStatistics,] Presented at\nPyHPC2011](http://www.scribd.com/doc/71048089/pandas-a-Foundational-Python-Library-for-Data-Analysis-and-Statistics)\n\nNumba (2015) documentation,\n[http://numba.pydata.org/numba-doc/0.20.0/user/index.html](http://numba.pydata.org/numba-doc/0.20.0/user/index.html%20)\n\nPauletto, G. (1997), [Computational Solution of Large-Scale\nMacroeconometric\nModels](http://link.springer.com/book/10.1007%2F978-1-4757-2631-2),\nISBN 9781441947789\n\nE. Petersen, Christian & A. Sims, Christopher. (1987). Computer Simulation of Large-Scale Econometric Models: Project Link. International Journal of High Performance Computing Applications (http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.853.6387&rep=rep1&type=pdf)\n\nTinberger, Jan (1956), Economic policy: Principles and Design,\nAmsterdam,\n\n\n# Footnotes\n$^1$: The author has been able to draw on experience creating software\n for solving the macroeconomic models ADAM in Hansen Econometric.\n\n$^2$: In this work a number of staff in Danmarks Nationalbank made\n significant contributions: Jens Boldt and Jacob Ejsing to the\n program. Rasmus Tommerup and Lindis Oma by being the first to\n implement a stress test model in the system.\n\n$^3$: In ECB Marco Gross, Mathias Sydow and many other collegues has been of great help. \n\n$^4$: The system has benefited from discussions with participants in meetings at: IMF, Bank of Japan, Bank of England, FED Board, Oxford University, Banque de France, Single Resolution Board \n\n$^5$: Ast stands for: [Abstract Syntax\n Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree)\n\n$^6$: Re stands for[: Regular\n expression](https://en.wikipedia.org/wiki/Regular_expression)\n\n\n```python\n\n```\n", "meta": {"hexsha": "e4fe8d144981a15be25fea90a3d70310f3febeeb", "size": 317879, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Examples/ModelFlow features/wp/ModelFlow-wp.ipynb", "max_stars_repo_name": "Freya-Antonia/Modelflow2", "max_stars_repo_head_hexsha": "acfb0f6a8b8b7c69963d07e1098ba552e505bfa8", "max_stars_repo_licenses": ["X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/ModelFlow features/wp/ModelFlow-wp.ipynb", "max_issues_repo_name": "Freya-Antonia/Modelflow2", "max_issues_repo_head_hexsha": "acfb0f6a8b8b7c69963d07e1098ba552e505bfa8", "max_issues_repo_licenses": ["X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/ModelFlow features/wp/ModelFlow-wp.ipynb", "max_forks_repo_name": "Freya-Antonia/Modelflow2", "max_forks_repo_head_hexsha": "acfb0f6a8b8b7c69963d07e1098ba552e505bfa8", "max_forks_repo_licenses": ["X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.7633935841, "max_line_length": 21428, "alphanum_fraction": 0.6172883393, "converted": true, "num_tokens": 32247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30935208127124647}} {"text": "```python\nimport sympy as sy\nimport control as pc\n```\n\nPart of the big question is whether we are simulating the dynamic response, or the steady-state mathematics iterations. Here below is the steady state reponse mathamtical system design, rather than a dynamic diffferential changes with time. Hence, Python's control toolbox cannot solve a steady-state response of a already stable system. However, attempting to perform a fully stable model means that if we want to perform feedback, there's a factor of recalculating stability from that until differential changes become 0 at different time-steps. So for example, if you were to perform feedback after an initial state, you can get a steady state reponse, but this is not the dynamic response, this is solving for the right answer after a number of iterations, and all the initial steady-state answers are wrong for a feedback system. So this gives a steady state response. If we change an input signal also at another point of time, then there is a new steady state response, but the question is whether you want to account for the time dynamics. Because currently, the system is accounting for the digital computing dynamics rather than the actual transient model, so you can't account for how the system dynamically responds and results in a real-time steady-state. So if an input changes in time, you can actually model the time differential change. If we begin considering delays and inputs into the rest of the system, we need to model time as time and computations as computations - and hence we need a time variable input.\n\nThere's also the aspect that optics is fundamentally linear and 3D, so how do we account for differential changes in it? What is its dynamic response? There are only dynamic changes on dynamic inputs. What are time changes in optics? You could argue it is near instantaneous. So there's group delay as the time it takes for light to travel through the waveguide, specially if it has been affected in any way. So there is a need to model transient and steady-state responses, but each of these models should be kept separate.\n\nNow, getting a time domain model of a thermo-optic phase shifter response is non-trivial nor necessarily accurate. So, time is a completely new thing in the optical domain for these type of modelled systems. Yes, there is propagation time effects.\n\nLet's consider an MZI, in one arm there's light going over a certain length which incurrs a certain propagation time. Assuming we're only in steady-state mode, when does change occur? You can differtiate phase shift against length for example, but you would be discretizing space-wise. So imagine Pac-Mans moving in a grid of time, according to their position, their properties change, such as phase and this is also dependent in temperature at a given position, but then there must be a differential in temperature and length to calculate a steady state response. So there's this big aspect of time differentials. Could we work based purely on steady-state time differentials? Actually, that could work. There's also the factor of where to add delays, but if we consider every wavelength arm as a system, then we can simply follow the basic principles of control theory.\n\nHence, the time discretization must occur at a fraction of the time of propagation of the shortest path in the model. \n\nSo our inputs into the control system are the electromagnetic signals, that are time-domain constrained\n\n#### Beamsplitter\n\\begin{equation}\n\\begin{bmatrix} E_{out0}(t) \\\\ E_{out1}(t) \\end{bmatrix} =\n\\begin{bmatrix} r_{ac}& t_{bc} \\\\ t_{ad}& r_{bd} \\end{bmatrix}\n\\begin{bmatrix} E_{in0}(t) \\\\ E_{in1}(t) \\end{bmatrix} = \n\\begin{bmatrix} \\sqrt{r} & i\\sqrt{1-r} \\\\ i \\sqrt{1-r} & \\sqrt{r} \\end{bmatrix}\n\\begin{bmatrix} E_{in0}(t) \\\\ E_{in1}(t) \\end{bmatrix} =\n\\textbf{B}\\textbf{E(t)}\n\\end{equation}\n\n#### Phase Shifter on one arm\n\nAssuming a phase shifter on top arm\n\\begin{equation}\n\\textbf{ $\\Phi$ } = \\begin{bmatrix} e^{i\\phi} & 0 \\\\ 0 & 1\\end{bmatrix}\n\\end{equation}\n\nNote we're not yet taking into account Linear and LinearGroup delay, or the quantum probability variable within the design of the device.\n\nHence the MZI configuration is:\n\n\\begin{equation}\nM\\textbf{E(t)} = \\textbf{B} \\textbf{ $\\Phi$ } \\textbf{B}\\textbf{E(t)} \n\\end{equation}\n\n\\begin{equation}\nM\\textbf{E(t)} = \\begin{bmatrix} \\sqrt{r} & i\\sqrt{1-r} \\\\ i \\sqrt{1-r} & \\sqrt{r} \\end{bmatrix} \\begin{bmatrix} e^{i\\phi} & 0 \\\\ 0 & 1\\end{bmatrix} \\begin{bmatrix} \\sqrt{r} & i\\sqrt{1-r} \\\\ i \\sqrt{1-r} & \\sqrt{r} \\end{bmatrix}\\begin{bmatrix} E_{in0}(t) \\\\ E_{in1}(t) \\end{bmatrix} = \\begin{bmatrix} E_{out0}(t) \\\\ E_{out1}(t) \\end{bmatrix} \n\\end{equation}\n\nNow we could just crunch some matrices together and input our time signals, but what if we wanted to leverage classical control system theory with regards to MIMO inputs and outputs, so that it is easier to design this type of systems togther and include feedback and nonlinearity back into the classical control models?\n\nThe standard way to start is to create the differential equations for this type of system and we can use the fast linear properties of SymPy to create a single MZI component, and the quantum probability variable could be added into this later. Right now let´s consider that we've only got differential equations, with equal reflectivity on both sides of the matrix:\n\n\n```python\nt = sy.Symbol(\"t\")\nE0 = sy.Function(\"E_0\")(t)\nE0_s = sy.Symbol(\"E_0\")\ndE0_s = sy.Symbol(\"dE_0\")\nE1 = sy.Function(\"E_1\")(t)\nE1_s = sy.Symbol(\"E_1\")\ndE1_s = sy.Symbol(\"dE_1\")\nphi = sy.Function(\"\\phi\")(t)\nr_0, r_1 = sy.symbols(\"r_0 r_1\")\nB_0 = sy.Matrix([[sy.sqrt(r_0), sy.I*sy.sqrt(1 - r_0)],\n\t\t\t\t[sy.I*sy.sqrt(1 - r_0), sy.sqrt(r_0)]])\nB_1 = sy.Matrix([[sy.sqrt(r_1), sy.I*sy.sqrt(1 - r_1)],\n\t\t\t\t[sy.I*sy.sqrt(1 - r_1), sy.sqrt(r_1)]])\nPhi = sy.Matrix([[sy.exp(sy.I * phi), 0],\n\t\t\t\t[0, 1]])\nE = sy.Matrix([[E0], [E1]])\n\nout = B_0 * Phi * B_1 * E\nout\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\left(\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}\\right) \\operatorname{E_{0}}{\\left(t \\right)} + \\left(i \\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + i \\sqrt{r_{1}} \\sqrt{1 - r_{0}}\\right) \\operatorname{E_{1}}{\\left(t \\right)}\\\\\\left(\\sqrt{r_{0}} \\sqrt{r_{1}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}}\\right) \\operatorname{E_{1}}{\\left(t \\right)} + \\left(i \\sqrt{r_{0}} \\sqrt{1 - r_{1}} + i \\sqrt{r_{1}} \\sqrt{1 - r_{0}} e^{i \\phi{\\left(t \\right)}}\\right) \\operatorname{E_{0}}{\\left(t \\right)}\\end{matrix}\\right]$\n\n\n\n\n```python\ndifferential_time_response = out.diff(t)\ndifferential_time_response = differential_time_response.replace(E0.diff(t), dE0_s)\ndifferential_time_response = differential_time_response.replace(E1.diff(t), dE1_s)\ndifferential_time_response\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}dE_{0} \\left(\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}\\right) + dE_{1} \\left(i \\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + i \\sqrt{r_{1}} \\sqrt{1 - r_{0}}\\right) + i \\sqrt{r_{0}} \\sqrt{r_{1}} \\operatorname{E_{0}}{\\left(t \\right)} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)} - \\sqrt{r_{0}} \\sqrt{1 - r_{1}} \\operatorname{E_{1}}{\\left(t \\right)} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)}\\\\dE_{0} \\left(i \\sqrt{r_{0}} \\sqrt{1 - r_{1}} + i \\sqrt{r_{1}} \\sqrt{1 - r_{0}} e^{i \\phi{\\left(t \\right)}}\\right) + dE_{1} \\left(\\sqrt{r_{0}} \\sqrt{r_{1}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}}\\right) - \\sqrt{r_{1}} \\sqrt{1 - r_{0}} \\operatorname{E_{0}}{\\left(t \\right)} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)} - i \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}} \\operatorname{E_{1}}{\\left(t \\right)} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)}\\end{matrix}\\right]$\n\n\n\nThe problem becomes an equilibrium condition to solve. One could argue that when the output is in equilibrium or in steady state:\n\n\\begin{equation}\n\\begin{bmatrix} \\frac{dE_{out0}}{dt} \\\\ \\frac{dE_{out1}}{dt} \\end{bmatrix} = 0\n\\end{equation}\n\n\n```python\n# Note we're only expecting one solution\ndE0_dt = sy.solve(differential_time_response[0], dE0_s)[0]\ndE0_dt = dE0_dt.replace(E0, E0_s)\ndE0_dt = dE0_dt.replace(E1, E1_s)\ndE0_dt\n```\n\n\n\n\n$\\displaystyle \\frac{- i E_{0} \\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)} + E_{1} \\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)} - i dE_{1} \\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} - i dE_{1} \\sqrt{r_{1}} \\sqrt{1 - r_{0}}}{\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}}$\n\n\n\n\n```python\n# Note we're only expecting one solution\ndE1_dt = sy.solve(differential_time_response[0], dE1_s)[0]\ndE1_dt = dE1_dt.replace(E0, E0_s)\ndE1_dt = dE1_dt.replace(E1, E1_s)\n# dE1_dt = dE1_dt.replace(dE0_s, dE0_dt) # Cannot be solved canonically as it is a complementary system.\ndE1_dt\n```\n\n\n\n\n$\\displaystyle \\frac{i \\left(i E_{0} \\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)} - E_{1} \\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)} + dE_{0} \\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - dE_{0} \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}\\right)}{\\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + \\sqrt{r_{1}} \\sqrt{1 - r_{0}}}$\n\n\n\nNote that this is a complemenetary function with regards to the other state variable.\n\nHence, we can write in the nonlinear state-space equations:\n\n\\begin{equation}\n\\dot{\\textbf{x}} = \\textbf{A} \\textbf{x} + \\textbf{B} \\textbf{u}\n\\end{equation}\n\n\\begin{equation}\n\\textbf{y} = \\textbf{C} \\textbf{x} + \\textbf{D} \\textbf{u}\n\\end{equation}\n\n\n```python\nA, B = sy.linear_eq_to_matrix([dE0_dt, dE1_dt], [E0_s, E1_s])\nB = sy.simplify(B)\nA = sy.simplify(A)\n```\n\n\n```python\nA\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}- \\frac{i \\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)}}{\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}} & \\frac{\\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)}}{\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}}\\\\- \\frac{\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)}}{\\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + \\sqrt{r_{1}} \\sqrt{1 - r_{0}}} & - \\frac{i \\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} \\frac{d}{d t} \\phi{\\left(t \\right)}}{\\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + \\sqrt{r_{1}} \\sqrt{1 - r_{0}}}\\end{matrix}\\right]$\n\n\n\n\n```python\nB\n```\n\n\n\n\n$\\displaystyle \\left[\\begin{matrix}\\frac{i dE_{1} \\left(\\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + \\sqrt{r_{1}} \\sqrt{1 - r_{0}}\\right)}{\\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} - \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}}\\\\\\frac{i dE_{0} \\left(- \\sqrt{r_{0}} \\sqrt{r_{1}} e^{i \\phi{\\left(t \\right)}} + \\sqrt{1 - r_{0}} \\sqrt{1 - r_{1}}\\right)}{\\sqrt{r_{0}} \\sqrt{1 - r_{1}} e^{i \\phi{\\left(t \\right)}} + \\sqrt{r_{1}} \\sqrt{1 - r_{0}}}\\end{matrix}\\right]$\n\n\n\nNote that the differential state inputs are coupled into the state space system for the opposite original state variables, hence are coupled together and this is the nonlinear represenatation. We can no longer set the differntials inputs to 0, since they are our effective state changes. However, we know have a nonlinear system we have to deal with. It is both nonlinear in $\\phi$ and in $\\frac{dE_0}{dt} * e^{\\phi}$. Note that this system should always be oscillating, that is the nature of light. So let us redefine what a steady state of a system is, because there will be none using standard control theory in optics. But is there a steady state in an MZI? That is a different question. But there is a steady state in an MZI for a given wavelength and is fully dependent on the phase input.\n\nWe're also dealing with complementary systems.\n\n### Thermo-optic Phase Shifter Model\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "24cbfe69a786f9b00b7623a57a5bbaaf274602c1", "size": 19429, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "raw/standard_control_theory_implementation/standard_control_2.ipynb", "max_stars_repo_name": "bigphoton/arch", "max_stars_repo_head_hexsha": "95a197d6b89bc2316b0d88b2b1345cbbb90088ec", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "raw/standard_control_theory_implementation/standard_control_2.ipynb", "max_issues_repo_name": "bigphoton/arch", "max_issues_repo_head_hexsha": "95a197d6b89bc2316b0d88b2b1345cbbb90088ec", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "raw/standard_control_theory_implementation/standard_control_2.ipynb", "max_forks_repo_name": "bigphoton/arch", "max_forks_repo_head_hexsha": "95a197d6b89bc2316b0d88b2b1345cbbb90088ec", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.8199445983, "max_line_length": 1539, "alphanum_fraction": 0.576200525, "converted": true, "num_tokens": 4081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.3092030441842454}} {"text": "\n\n# メモ\r\n\r\n手を動かしてまなぶ 線形代数 藤岡敦\r\n\r\nを読む。\r\n\r\nhttp://www.shokabo.co.jp/\r\n\r\nに詳細な解答があるって。\n\n# 行列\r\n\n\n1. 行列とは数を長方形状に並べたものである。\r\n1. すべての成分が 0 の行列を零行列という。\r\n1. 行と列の個数が等しい行列を正方行列という。\r\n1. 特別な正方行列として、単位行列、対角行列、スカラー行列、上三角行列、下三角行列があげられる。\r\n1. 単位行列はクロネッカーのデルタを用いて、簡単に表すことができる。\r\n1. 転置をとっても変わらない正方行列を対称行列という。\r\n1. 行ベクトル、列ベクトルをあわせて数ベクトルという。\r\n1. すべての成分が 0 の数ベクトルを零ベクトルという。\n\n自然数 $i=1,2,\\cdots,m$ および $j=1,2,\\cdots,n$ に対して、数 $a_{ij}$ が対応しているとする。 \r\n\r\nこのとき、$mn$ 個の数 $a_{11},a_{12},\\cdots,a_{mn}$ を丸括弧 ( ) や角括弧 [ ] を用いて長方形状に並べたものを $m \\times n$ 行列または$m$行$n$列の行列という。\r\n\r\n$a_{ij}$ の $i$ や $j$ を添字(そえじ)という。\n\n\n```latex\n%%latex\n\\begin{pmatrix}\n a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\ldots & a_{mn}\n\\end{pmatrix}, \\quad\n\\begin{bmatrix}\n a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\ldots & a_{mn}\n\\end{bmatrix} \n```\n\n\n\\begin{pmatrix}\n a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\ldots & a_{mn}\n\\end{pmatrix}, \\quad\n\\begin{bmatrix}\n a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\ldots & a_{mn}\n\\end{bmatrix} \n\n\n例 \r\n\r\n次の行列は $2 \\times 3$ 行列である。\n\n\n```latex\n%%latex\r\n\\begin{pmatrix}\r\n 1 & 2 & 3 \\\\\r\n 4 & 5 & 6\r\n\\end{pmatrix}\r\n\n```\n\n\n\\begin{pmatrix}\n 1 & 2 & 3 \\\\\n 4 & 5 & 6\n\\end{pmatrix}\n\n\n\n```\nfrom sympy import *\r\nA=Matrix([[1,2,3],[4,5,6]])\r\ndisplay(A)\n```\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 & 3\\\\4 & 5 & 6\\end{matrix}\\right]$\n\n\n\r\n行列 $A$ について\r\n$A = (a_{ij})$\r\nと書く。\r\n\r\n$\\quad a_{ij},\\quad (a_{i1} a_{i2} \\cdots a_{in}), \\quad\r\n\r\n\\begin{pmatrix}\r\n a_{1j} \\\\\r\n a_{2j} \\\\\r\n a_{2j} \\\\\r\n a_{mj} \r\n\\end{pmatrix}$\r\n\r\nを$A$の$(i,j)$成分、第$i$行、第$j$列という。\n\n\n```latex\n%%latex\r\n\\begin{pmatrix}\r\n a_{1j} \\\\\r\n a_{2j} \\\\\r\n a_{2j} \\\\\r\n a_{mj} \r\n\\end{pmatrix}\n```\n\n\n\\displaystyle\n\\begin{pmatrix}\n a_{1j} \\\\\n a_{2j} \\\\\n a_{2j} \\\\\n a_{mj} \n\\end{pmatrix}\n\n\n $ A=(a_{ij})_{m \\times n} $ を $ m \\times n $ 行列、 $ B=(b_{kl})_{p \\times q} $ を $ p \\times q $ 行列とする。\r\n\r\n$ A $ と $ B $ が同じ型で、対応する成分が等しいとき、すなわち、 $ m=p $ かつ $ n=q $ で、\r\n任意の $ i=1,2,\\cdots,m $ および $ j=1,2,\\cdots,n $ に対して $ a_{ij}=b_{ij} $ が成り立つとき\r\n\r\n$$ A = B$$\r\n\r\nと記し、A $ と $ B $ は等しい、という。A = B $ でないときは\r\n\r\n$$ A \\neq B $$\n\n$$\r\n\\begin{array}{rcl}\r\n\\begin{pmatrix}\r\n a & b & c \\\\\r\n d & e & f\r\n\\end{pmatrix} \r\n&=&\r\n\\begin{pmatrix}\r\n p & q & r \\\\\r\n s & t & u\r\n\\end{pmatrix} \\\\[0.8em]\r\n\r\n&\\Updownarrow& \\\\[0.8em]\r\n\r\na = p,\\quad b = q,\\quad c = r&,& d = s,\\quad e = t,\\quad f = u\r\n\r\n\\end{array}\r\n$$\n\n\n```latex\n%%latex\r\n\\begin{array}{rcl}\r\n\\begin{pmatrix}\r\n a & b & c \\\\\r\n d & e & f\r\n\\end{pmatrix} &=&\r\n\\begin{pmatrix}\r\n p & q & r \\\\\r\n s & t & u\r\n\\end{pmatrix} \\\\[0.8em]\r\n\r\n&\\Updownarrow& \\\\[0.8em]\r\n\r\na = p,\\quad b = q,\\quad c = r&,& d = s,\\quad e = t,\\quad f = u\r\n\\end{array} \\\\\r\n\n```\n\n\n\\begin{array}{rcl}\n\\begin{pmatrix}\n a & b & c \\\\\n d & e & f\n\\end{pmatrix} &=&\n\\begin{pmatrix}\n p & q & r \\\\\n s & t & u\n\\end{pmatrix} \\\\[0.8em]\n\n&\\Updownarrow& \\\\[0.8em]\n\na = p,\\quad b = q,\\quad c = r&,& d = s,\\quad e = t,\\quad f = u\n\\end{array} \\\\\n\n\n\n```latex\n%%latex\r\nすべての成分が~0~の~m \\times n~行列を~O_{m,n}~または~O~と書き、零行列という。\r\n\\\\[0.8em]\r\n\\quad \\quad \\quad \\quad \r\nO_{3,2} =\r\n\\begin{pmatrix}\r\n 0 & 0 \\\\\r\n 0 & 0 \\\\\r\n 0 & 0 \r\n\\end{pmatrix}\r\n\\\\[0.8em]\r\n2~列、~3~行\n```\n\n\nすべての成分が~0~の~m \\times n~行列を~O_{m,n}~または~O~と書き、零行列という。\n\\\\[0.8em]\n\\quad \\quad \\quad \\quad \nO_{3,2} =\n\\begin{pmatrix}\n 0 & 0 \\\\\n 0 & 0 \\\\\n 0 & 0 \n\\end{pmatrix}\n\\\\[0.8em]\n2~列、~3~行\n\n\n\n```latex\n%%latex\r\n一般に、2~つの命題~P,~Q~に対して、P~ならば~Q~であることを~P \\Longrightarrow Q~と表し、P~と~Q~が同値であることを\r\n~P \\Longleftrightarrow Q~と表す。\n```\n\n\n一般に、2~つの命題~P,~Q~に対して、P~ならば~Q~であることを~P \\Longrightarrow Q~と表し、P~と~Q~が同値であることを\n~P \\Longleftrightarrow Q~と表す。\n\n\n\n```latex\n%%latex\r\nA = (a_{ij})_{n \\times n}~を~n \\times n~ 行列とするとき、A~を~n~次の正方行列という。\\\\\r\n成分~a_{11}, a_{22}, \\cdots a_{nn}~を~A~の対角成分という。\\\\[0.8em]\r\n\r\n正方行列 ~A~が\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i \\neq j) \\\\[0.8em]\r\n\r\nを満たすとき、A~を対角行列という。 正方行列~A~が\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i \\neq j), \\quad a_{11} = a_{22} = \\cdots = a_{nn} \\\\[0.8em]\r\n\r\nを満たすとき、A~をスカラー行列という。 正方行列~A~が\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i > j) \\\\[0.8em]\r\n\r\nを満たすとき、A~を上三角行列という。 正方行列~A~が\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i < j) \\\\[0.8em]\r\n\r\nを満たすとき、A~を下三角行列という。 \n```\n\n\nA = (a_{ij})_{n \\times n}~を~n \\times n~ 行列とするとき、A~を~n~次の正方行列という。\\\\\n成分~a_{11}, a_{22}, \\cdots a_{nn}~を~A~の対角成分という。\\\\[0.8em]\n\n正方行列 ~A~が\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i \\neq j) \\\\[0.8em]\n\nを満たすとき、A~を対角行列という。 正方行列~A~が\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i \\neq j), \\quad a_{11} = a_{22} = \\cdots = a_{nn} \\\\[0.8em]\n\nを満たすとき、A~をスカラー行列という。 正方行列~A~が\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i > j) \\\\[0.8em]\n\nを満たすとき、A~を上三角行列という。 正方行列~A~が\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad a_{ij} = 0 \\quad (i < j) \\\\[0.8em]\n\nを満たすとき、A~を下三角行列という。 \n\n\n\n```latex\n%%latex\r\n2~次の正方行列\r\n~A~ = \r\n\\begin{pmatrix}\r\n a & b \\\\\r\n c & d\r\n\\end{pmatrix}\r\n~とする。\\\\[0.8em]\r\n\r\nA~の対角成分は~\r\n\\begin{pmatrix}\r\n a & 0 \\\\\r\n 0 & d\r\n\\end{pmatrix}\\\\[0.8em]\r\n\r\nA~が対角行列、上三角行列、下三角行列となるときそれぞれ\\\\[0.8em]\r\n\r\n\\begin{pmatrix}\r\n a & 0 \\\\\r\n 0 & a\r\n\\end{pmatrix}, \\quad\r\n\r\n\\begin{pmatrix}\r\n a & b \\\\\r\n 0 & d\r\n\\end{pmatrix}, \\quad\r\n\r\n\\begin{pmatrix}\r\n a & 0 \\\\\r\n c & d\r\n\\end{pmatrix}\n```\n\n\n2~次の正方行列\n~A~ = \n\\begin{pmatrix}\n a & b \\\\\n c & d\n\\end{pmatrix}\n~とする。\\\\[0.8em]\n\nA~の対角成分は~\n\\begin{pmatrix}\n a & 0 \\\\\n 0 & d\n\\end{pmatrix}\\\\[0.8em]\n\nA~が対角行列、上三角行列、下三角行列となるときそれぞれ\\\\[0.8em]\n\n\\begin{pmatrix}\n a & 0 \\\\\n 0 & a\n\\end{pmatrix}, \\quad\n\n\\begin{pmatrix}\n a & b \\\\\n 0 & d\n\\end{pmatrix}, \\quad\n\n\\begin{pmatrix}\n a & 0 \\\\\n c & d\n\\end{pmatrix}\n\n\n\n```latex\n%%latex\r\n対角成分がすべて~1~の~n~次スカラー行列を~E_n~または~E~と書き、~n~次単位行列という。 ~I_n~や~I~と書くこともある。\\\\[0.8em]\r\n\r\nE_1 = (1) = 1, \\quad E_2 = \r\n\\begin{pmatrix}\r\n 1 & 0 \\\\\r\n 0 & 1\r\n\\end{pmatrix}, \\quad E_3 =\r\n\\begin{pmatrix}\r\n 1 & 0 & 0 \\\\\r\n 0 & 1 & 0 \\\\\r\n 0 & 0 & 1\r\n\\end{pmatrix}\n```\n\n\n対角成分がすべて~1~の~n~次スカラー行列を~E_n~または~E~と書き、~n~次単位行列という。 ~I_n~や~I~と書くこともある。\\\\[0.8em]\n\nE_1 = (1) = 1, \\quad E_2 = \n\\begin{pmatrix}\n 1 & 0 \\\\\n 0 & 1\n\\end{pmatrix}, \\quad E_3 =\n\\begin{pmatrix}\n 1 & 0 & 0 \\\\\n 0 & 1 & 0 \\\\\n 0 & 0 & 1\n\\end{pmatrix}\n\n\n\n```\n# クロネッカーのデルタ\r\n%%latex\r\nクロネッカーのデルタ\\\\[0.8em]\r\n\r\ni,j = 1,2, \\cdots, n~ に対して\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \\delta =\r\n\r\n\\left \\{\r\n\\begin{array}{cl}\r\n 1 & (i = j) \\\\\r\n 0 & (i \\neq j)\r\n\\end{array}\r\n\\right .\r\n\\\\[0.8em]\r\nにより、~0~または~1~をとる記号~\\delta_{ij}~を定める。 \\\\\r\n~\\delta_{ij}~をクロネッカーのデルタという。\n```\n\n\nクロネッカーのデルタ\\\\[0.8em]\n\ni,j = 1,2, \\cdots, n~ に対して\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \\delta =\n\n\\left \\{\n\\begin{array}{cl}\n 1 & (i = j) \\\\\n 0 & (i \\neq j)\n\\end{array}\n\\right .\n\\\\[0.8em]\nにより、~0~または~1~をとる記号~\\delta_{ij}~を定める。 \\\\\n~\\delta_{ij}~をクロネッカーのデルタという。\n\n\n\n```latex\n%%latex\r\ni,j = 1,2 のとき、クロネッカーのデルタ~\\delta_{ij}~の値を求める。\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \\delta_{11} = \\delta_{22} = 1, \\quad \\delta_{12} = \\delta_{21} = 0\n```\n\n\ni,j = 1,2 のとき、クロネッカーのデルタ~\\delta_{ij}~の値を求める。\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \\delta_{11} = \\delta_{22} = 1, \\quad \\delta_{12} = \\delta_{21} = 0\n\n\n\n```latex\n%%latex\r\nクロネッカーのデルタを用いると、~n~次単位行列~E_n~は~E_n = (\\delta_{ij})_{n \\times n}~ と表すことができる。\\\\\r\n例えば、~2~次単位行列は\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad E_2 = \r\n\r\n\\begin{pmatrix}\r\n \\delta_{11} & \\delta_{12} \\\\\r\n \\delta_{21} & \\delta_{22}\r\n\\end{pmatrix} =\r\n\r\n\\begin{pmatrix}\r\n 1 & 0 \\\\\r\n 0 & 1\r\n\\end{pmatrix} \\\\[0.8em]\r\n\r\nとなる。\n```\n\n\nクロネッカーのデルタを用いると、~n~次単位行列~E_n~は~E_n = (\\delta_{ij})_{n \\times n}~ と表すことができる。\\\\\n例えば、~2~次単位行列は\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad E_2 = \n\n\\begin{pmatrix}\n \\delta_{11} & \\delta_{12} \\\\\n \\delta_{21} & \\delta_{22}\n\\end{pmatrix} =\n\n\\begin{pmatrix}\n 1 & 0 \\\\\n 0 & 1\n\\end{pmatrix} \\\\[0.8em]\n\nとなる。\n\n\n\n```latex\n%%latex\r\n転置行列\\\\[0.8em]\r\n\r\nm \\times n~ 行列~A~の行と列を入れ替えて得られる~n \\times m~ 行列を~{}^t A, A^t~ または~{}^T A~ などと書き、\\\\\r\n~A~の転置行列という。 すなわち、\\\\[0.8em]\r\n\\quad \\quad \\quad \\quad \r\nA = \r\n\\begin{pmatrix}\r\n a_{11} & a_{12} & \\ldots & a_{1n} \\\\\r\n a_{21} & a_{22} & \\ldots & a_{2n} \\\\\r\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\r\n a_{m1} & a_{m2} & \\ldots & a_{mn}\r\n\\end{pmatrix} \\\\[0.8em]\r\n\r\nのとき、\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \r\n{}^t A = \r\n\\begin{pmatrix}\r\n a_{11} & a_{21} & \\ldots & a_{m1} \\\\\r\n a_{12} & a_{22} & \\ldots & a_{m2} \\\\\r\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\r\n a_{1n} & a_{2m} & \\ldots & a_{mn}\r\n\\end{pmatrix} \\\\[0.8em]\r\n\r\nである。定義より、\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \r\n{}^t({}^t A) = A \\\\[0.8em]\r\n\r\nが成り立つ。 なお転置行列を作ることを、転置を取る、ともいう。\n```\n\n\n転置行列\\\\[0.8em]\n\nm \\times n~ 行列~A~の行と列を入れ替えて得られる~n \\times m~ 行列を~{}^t A, A^t~ または~{}^T A~ などと書き、\\\\\n~A~の転置行列という。 すなわち、\\\\[0.8em]\n\\quad \\quad \\quad \\quad \nA = \n\\begin{pmatrix}\n a_{11} & a_{12} & \\ldots & a_{1n} \\\\\n a_{21} & a_{22} & \\ldots & a_{2n} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{m1} & a_{m2} & \\ldots & a_{mn}\n\\end{pmatrix} \\\\[0.8em]\n\nのとき、\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \n{}^t A = \n\\begin{pmatrix}\n a_{11} & a_{21} & \\ldots & a_{m1} \\\\\n a_{12} & a_{22} & \\ldots & a_{m2} \\\\\n \\vdots & \\vdots & \\ddots & \\vdots \\\\\n a_{1n} & a_{2m} & \\ldots & a_{mn}\n\\end{pmatrix} \\\\[0.8em]\n\nである。定義より、\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \n{}^t({}^t A) = A \\\\[0.8em]\n\nが成り立つ。 なお転置行列を作ることを、転置を取る、ともいう。\n\n\n\n```latex\n%%latex\r\n例題 \\\\[0.8em]\r\n\r\n2 \\times 3~ 行列~\r\n\\begin{pmatrix}\r\n 1 & 2 & 3 \\\\\r\n 4 & 5 & 6\r\n\\end{pmatrix}~\r\nの転置行列を求める。 \\\\[0.8em]\n```\n\n\n例題 \\\\[0.8em]\n\n2 \\times 3~ 行列~\n\\begin{pmatrix}\n 1 & 2 & 3 \\\\\n 4 & 5 & 6\n\\end{pmatrix}~\nの転置行列を求める。\n\n\n\n```\nfrom sympy import *\r\ninit_printing()\r\nA = Matrix([[1,2,3],[4,5,6]])\r\ndisplay(A)\r\nprint()\r\ndisplay (A.T)\n```\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 2 & 3\\\\4 & 5 & 6\\end{matrix}\\right]$\n\n\n \n\n\n\n$\\displaystyle \\left[\\begin{matrix}1 & 4\\\\2 & 5\\\\3 & 6\\end{matrix}\\right]$\n\n\n\n```latex\n%%latex\r\n対称行列\\\\[0.8em]\r\n\r\n~n~次の正方行列の転置行列は再び~n~次の正方行列となる。よって、次のような正方行列を考えることができる。\\\\[0.8em]\r\n\r\n定義 \\quad {}^t A = A が成り立つ正方行列~A~を対称行列という。\\\\[0.8em]\r\n\r\n例 \\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \r\n(1), \\quad\r\n\\begin{pmatrix}\r\n 1 & 2 \\\\\r\n 2 & 3\r\n\\end{pmatrix} , \\quad\r\n\\begin{pmatrix}\r\n 1 & 2 & 3\\\\\r\n 2 & 4 & 5\\\\\r\n 3 & 5 & 6\r\n\\end{pmatrix}\n```\n\n\n対称行列\\\\[0.8em]\n\n~n~次の正方行列の転置行列は再び~n~次の正方行列となる。よって、次のような正方行列を考えることができる。\\\\[0.8em]\n\n定義 \\quad {}^t A = A が成り立つ正方行列~A~を対称行列という。\\\\[0.8em]\n\n例 \\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \n(1), \\quad\n\\begin{pmatrix}\n 1 & 2 \\\\\n 2 & 3\n\\end{pmatrix} , \\quad\n\\begin{pmatrix}\n 1 & 2 & 3\\\\\n 2 & 4 & 5\\\\\n 3 & 5 & 6\n\\end{pmatrix}\n\n\n\n```latex\n%%latex\r\n定義より、対称行列について、次の定理が成り立つ。\\\\[0.8em]\r\n\r\nA=(a_{ij})~を~n~次の正方行列とする。 ~A~が対称行列であるための必要十分条件は\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \r\na_{ij} = a_{ji} \\quad (i,j = 1,2,\\cdots, n)\\\\[0.8em]\r\n\r\nである。\n```\n\n\n定義より、対称行列について、次の定理が成り立つ。\\\\[0.8em]\n\nA=(a_{ij})~を~n~次の正方行列とする。 ~A~が対称行列であるための必要十分条件は\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \na_{ij} = a_{ji} \\quad (i,j = 1,2,\\cdots, n)\\\\[0.8em]\n\nである。\n\n\n\n```latex\n%%latex\r\nベクトルと名のつくものを簡単に書くときは太文字、ボールド体を用いる。\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \\mathbf{0,a,b,c,d,e,n,v,x,y,z,R,C}\\\\[0.8em]\r\n\r\n手書きするときは、文字の左側を~2~重にする。\\\\[0.8em]\r\n\r\n\\quad \\quad \\quad \\quad \\mathbb{0,a,b,c,d,e,n,v,x,y,z,R,C}\\\\[0.8em]\r\n\r\n大文字しか~2~重にならない。\n```\n\n\nベクトルと名のつくものを簡単に書くときは太文字、ボールド体を用いる。\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \\mathbf{0,a,b,c,d,e,n,v,x,y,z,R,C}\\\\[0.8em]\n\n手書きするときは、文字の左側を~2~重にする。\\\\[0.8em]\n\n\\quad \\quad \\quad \\quad \\mathbb{0,a,b,c,d,e,n,v,x,y,z,R,C}\\\\[0.8em]\n\n大文字しか~2~重にならない。 => いまの考えテキストが~2~重文字のとき、テキスト重視の考え方から\\\\\n~\\mathbb~\n\n\n\n```latex\n%%latex\r\n問題\\\\[0.8em]\r\n\r\n~3~次の正方行列~A~を~A =\r\n\\begin{pmatrix}\r\n a_{11} & a_{12} & a_{13} \\\\\r\n a_{21} & a_{22} & a_{23} \\\\\r\n a_{31} & a_{32} & a_{33}\r\n\\end{pmatrix}~と表す。\r\n\r\n1.~A~の対角成分を答える。\r\n2.~A~が対角行列、スカラー行列、上三角行列、下三角行列になるとき、~A~をそれぞれ具体的に示す。\n```\n\n\n問題\\\\[0.8em]\n\n~3~次の正方行列~A~を~A =\n\\begin{pmatrix}\n a_{11} & a_{12} & a_{13} \\\\\n a_{21} & a_{22} & a_{23} \\\\\n a_{31} & a_{32} & a_{33}\n\\end{pmatrix}\n\n\n\n```latex\n%%latex\r\n1.~a_{11},a_{12},a_{13} \\\\[0.8em]\r\n2.~\r\n\\begin{pmatrix}\r\n a_{11} & 0 & 0 \\\\\r\n 0 & a_{22} & 0 \\\\\r\n 0 & 0 & a_{33}\r\n\\end{pmatrix}, \\quad\r\n\\begin{pmatrix}\r\n a_{11} & 0 & 0 \\\\\r\n 0 & a_{11} & 0 \\\\\r\n 0 & 0 & a_{11}\r\n\\end{pmatrix}, \\quad\r\n\\begin{pmatrix}\r\n a_{11} & a_{12} & a_{13} \\\\\r\n 0 & a_{22} & a_{23} \\\\\r\n 0 & 0 & a_{33}\r\n\\end{pmatrix}~, \\quad\r\n\\begin{pmatrix}\r\n a_{11} & 0 & 0 \\\\\r\n a_{21} & a_{22} & 0 \\\\\r\n a_{31} & a_{32} & a_{33}\r\n\\end{pmatrix}\n```\n\n\n1.~a_{11},a_{12},a_{13} \\\\[0.8em]\n2.~\n\\begin{pmatrix}\n a_{11} & 0 & 0 \\\\\n 0 & a_{22} & 0 \\\\\n 0 & 0 & a_{33}\n\\end{pmatrix}, \\quad\n\\begin{pmatrix}\n a_{11} & 0 & 0 \\\\\n 0 & a_{11} & 0 \\\\\n 0 & 0 & a_{11}\n\\end{pmatrix}, \\quad\n\\begin{pmatrix}\n a_{11} & a_{12} & a_{13} \\\\\n 0 & a_{22} & a_{23} \\\\\n 0 & 0 & a_{33}\n\\end{pmatrix}~, \\quad\n\\begin{pmatrix}\n a_{11} & 0 & 0 \\\\\n a_{21} & a_{22} & 0 \\\\\n a_{31} & a_{32} & a_{33}\n\\end{pmatrix}\n\n\n\n```latex\n%%latex\r\n問題 \\\\[0.8em]\r\n\r\nクロネッカーのデルタ~\\delta_{ij} \\quad (i,j = 1,2, \\cdots, n)~ について、~i,j=1,2,3~のとき、~\\delta_{ij}~の値を求める。 \\\\[0.8em]\r\n\r\n解答 \\\\[0.8em]\r\n\r\n\\delta_{11}=\\delta_{22}=\\delta_{33}=1, \\quad\r\n\r\n\\delta_{12}=\\delta_{13}=\\delta_{21}=\\delta_{23}=\\delta_{31}=\\delta_{32}=0\r\n\n```\n\n\n問題 \\\\[0.8em]\n\nクロネッカーのデルタ~\\delta_{ij} \\quad (i,j = 1,2, \\cdots, n)~ について、~i,j=1,2,3~のとき、~\\delta_{ij}~の値を求める。 \\\\[0.8em]\n\n解答 \\\\[0.8em]\n\n\\delta_{11}=\\delta_{22}=\\delta_{33}=1, \\quad\n\n\\delta_{12}=\\delta_{13}=\\delta_{21}=\\delta_{23}=\\delta_{31}=\\delta_{32}=0\n\n\n\n\n\n```latex\n%%latex\r\n問題 \\\\[0.8em]\r\n\r\n~3 \\times 2~行列~\r\n\\begin{pmatrix}\r\n 5 & 4 \\\\\r\n 3 & 2 \\\\\r\n 1 & 0\r\n\\end{pmatrix}~の転置行列を求める。\n```\n\n\n問題 \\\\[0.8em]\n\n~3 \\times 2~行列~\n\\begin{pmatrix}\n 5 & 4 \\\\\n 3 & 2 \\\\\n 1 & 0\n\\end{pmatrix}\n\n\n\n```\nfrom sympy import *\r\nfrom IPython.display import Markdown\r\ninit_printing()\r\ndisplay(Markdown(\"解答\"))\r\nprint()\r\ndisplay(Matrix([[5,4],[3,2],[1,0]]))\r\nprint()\r\ndisplay(Matrix([[5,4],[3,2],[1,0]]).T)\n```\n\n\n解答\n\n\n \n\n\n\n$\\displaystyle \\left[\\begin{matrix}5 & 4\\\\3 & 2\\\\1 & 0\\end{matrix}\\right]$\n\n\n \n\n\n\n$\\displaystyle \\left[\\begin{matrix}5 & 3 & 1\\\\4 & 2 & 0\\end{matrix}\\right]$\n\n\n\n```latex\n%%latex\r\n問題 \\\\[0.8em]\r\n\\begin{pmatrix}\r\n a^2+b^2 & ab + bc \\\\\r\n ab + bc & b^2 + c^2\r\n\\end{pmatrix}\r\n=\r\n\\begin{pmatrix}\r\n 1 & 0 \\\\\r\n 0 & 4\r\n\\end{pmatrix}\n```\n\n\n問題 \\\\[0.8em]\n\\begin{pmatrix}\n a^2+b^2 & ab + bc \\\\\n ab + bc & b^2 + c^2\n\\end{pmatrix}\n=\n\\begin{pmatrix}\n 1 & 0 \\\\\n 0 & 4\n\\end{pmatrix}\n\n\n\n```\nfrom sympy import *\r\nfrom IPython.display import Markdown\r\ninit_printing()\r\ndisplay(Markdown(\"問題\"))\r\na,b,c = symbols('a,b,c')\r\nA = Matrix([[a**2+b**2, a*b+b*c],[a*b+b*c, b**2+c**2]])\r\ndisplay(A)\r\nB = Matrix([[1,0],[0,4]])\r\ndisplay(B)\r\ndisplay(Eq(A,B))\r\ndisplay(Markdown(\"解答\"))\r\ndisplay(solve((A-B),a,b,c))\r\ndisplay(solve((A-B)))\n```\n\n\n```\nfrom sympy import *\r\nfrom IPython.display import Markdown\r\ninit_printing()\r\ndisplay(Markdown(\"問題\"))\r\na,b,c = symbols('a,b,c')\r\nA = Matrix([[a**2+b**2, a*b+b*c],[a*b+b*c, b**2+c**2],[]])\r\ndisplay(A)\n```\n\n\n問題\n\n\n\n$\\displaystyle \\left[\\begin{matrix}a^{2} + b^{2} & a b + b c\\\\a b + b c & b^{2} + c^{2}\\end{matrix}\\right]$\n\n\n# いまここ p.10\n", "meta": {"hexsha": "eff391ff13ba6eccbd5d7f89cdf1ff8c2e435151", "size": 50644, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "linear_fujioka.ipynb", "max_stars_repo_name": "kalz2q/-yjupyternotebooks", "max_stars_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-09-16T03:45:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T03:45:19.000Z", "max_issues_repo_path": "linear_fujioka.ipynb", "max_issues_repo_name": "kalz2q/-yjupyternotebooks", "max_issues_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_fujioka.ipynb", "max_forks_repo_name": "kalz2q/-yjupyternotebooks", "max_forks_repo_head_hexsha": "ba37ac7822543b830fe8602b3f611bb617943463", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2183588317, "max_line_length": 3430, "alphanum_fraction": 0.445383461, "converted": true, "num_tokens": 8513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3085335140898221}} {"text": "```python\nfrom sympy import *\nfrom math import *\nimport sys\n\n\nfrom lib_rungekutta import *\n```\n\n# Phương pháp Runge - Kutta hiện giải bài toán Cauchy cho phương trình vi phân thường\n\n## 1. Nhập dữ liệu\n\nNhập biểu thức $ y' = f(x, y)$. Lưu ý PT phải đặt trong dấu nháy kép\n\n\n```python\nexpr = \"x\"\n```\n\nNhập giá trị ban đầu $x_{0}$ và $y(x_{0})$\n\n\n```python\nx_0 = 0\ny_0 = 0\n```\n\nNhập khoảng cách giữa 2 điểm liên tiếp $h$\n\n\n```python\nh = 0.1\n```\n\nNhập số mốc của lưới điểm $n$ \n\n\n```python\nn = 150\n```\n\nNhập số nấc của Runge-Kutta. Các giá trị bao gồm 1, 2, 3, 4 hoặc kiểu hệ số của Heun\n\n\n```python\ns = 4\n```\n\n## 2. Giải PTVP và in ra kết quả\nCấp chính xác:\n\n\n```python\nprecision_x = 3;\nprecision_y = 7;\nprecision_eps = 12;\n```\n\nGiải và in kết quả:\n\n\n\n```python\ns = s if(s == \"heun\" or s == \"Heun\") else int(s); \nuu = rungekutta_oop(expr, x_0, y_0, h, n, s);\ng = (uu.Solve());\n```\n\n\n```python\nif(s == \"heun\" or s == \"Heun\"):\n#{\n print(f\"Phương pháp Runge-Kutta 3 nấc với cấu hình hệ số kiểu Heun hoàn tất với lưới điểm sau, sai số toàn cục O(h^3) = {round(h**3, precision_eps)}:\");\n#}\nelse:\n#{\n print(f\"Phương pháp Runge-Kutta {s} nấc với hoàn tất với lưới điểm sau, sai số toàn cục O(h^{s}) = {round(h**s, precision_eps)}:\");\n#}\nfor x in g: print(round(x[0], precision_x), round(x[1], precision_y));\n```\n\n Phương pháp Runge-Kutta 4 nấc với hoàn tất với lưới điểm sau, sai số toàn cục O(h^4) = 0.0001:\n 0 1\n 0.1 1.005\n 0.2 1.02\n 0.3 1.045\n 0.4 1.08\n 0.5 1.125\n 0.6 1.18\n 0.7 1.245\n 0.8 1.32\n 0.9 1.405\n 1.0 1.5\n 1.1 1.605\n 1.2 1.72\n 1.3 1.845\n 1.4 1.98\n 1.5 2.125\n 1.6 2.28\n 1.7 2.445\n 1.8 2.62\n 1.9 2.805\n 2.0 3.0\n 2.1 3.205\n 2.2 3.42\n 2.3 3.645\n 2.4 3.88\n 2.5 4.125\n 2.6 4.38\n 2.7 4.645\n 2.8 4.92\n 2.9 5.205\n 3.0 5.5\n 3.1 5.805\n 3.2 6.12\n 3.3 6.445\n 3.4 6.78\n 3.5 7.125\n 3.6 7.48\n 3.7 7.845\n 3.8 8.22\n 3.9 8.605\n 4.0 9.0\n 4.1 9.405\n 4.2 9.82\n 4.3 10.245\n 4.4 10.68\n 4.5 11.125\n 4.6 11.58\n 4.7 12.045\n 4.8 12.52\n 4.9 13.005\n 5.0 13.5\n 5.1 14.005\n 5.2 14.52\n 5.3 15.045\n 5.4 15.58\n 5.5 16.125\n 5.6 16.68\n 5.7 17.245\n 5.8 17.82\n 5.9 18.405\n 6.0 19.0\n 6.1 19.605\n 6.2 20.22\n 6.3 20.845\n 6.4 21.48\n 6.5 22.125\n 6.6 22.78\n 6.7 23.445\n 6.8 24.12\n 6.9 24.805\n 7.0 25.5\n 7.1 26.205\n 7.2 26.92\n 7.3 27.645\n 7.4 28.38\n 7.5 29.125\n 7.6 29.88\n 7.7 30.645\n 7.8 31.42\n 7.9 32.205\n 8.0 33.0\n 8.1 33.805\n 8.2 34.62\n 8.3 35.445\n 8.4 36.28\n 8.5 37.125\n 8.6 37.98\n 8.7 38.845\n 8.8 39.72\n 8.9 40.605\n 9.0 41.5\n 9.1 42.405\n 9.2 43.32\n 9.3 44.245\n 9.4 45.18\n 9.5 46.125\n 9.6 47.08\n 9.7 48.045\n 9.8 49.02\n 9.9 50.005\n 10.0 51.0\n 10.1 52.005\n 10.2 53.02\n 10.3 54.045\n 10.4 55.08\n 10.5 56.125\n 10.6 57.18\n 10.7 58.245\n 10.8 59.32\n 10.9 60.405\n 11.0 61.5\n 11.1 62.605\n 11.2 63.72\n 11.3 64.845\n 11.4 65.98\n 11.5 67.125\n 11.6 68.28\n 11.7 69.445\n 11.8 70.62\n 11.9 71.805\n 12.0 73.0\n 12.1 74.205\n 12.2 75.42\n 12.3 76.645\n 12.4 77.88\n 12.5 79.125\n 12.6 80.38\n 12.7 81.645\n 12.8 82.92\n 12.9 84.205\n 13.0 85.5\n 13.1 86.805\n 13.2 88.12\n 13.3 89.445\n 13.4 90.78\n 13.5 92.125\n 13.6 93.48\n 13.7 94.845\n 13.8 96.22\n 13.9 97.605\n 14.0 99.0\n 14.1 100.405\n 14.2 101.82\n 14.3 103.245\n 14.4 104.68\n 14.5 106.125\n 14.6 107.58\n 14.7 109.045\n 14.8 110.52\n 14.9 112.005\n 15.0 113.5\n\n\nĐồ thị:\n\n\n```python\nuu.getPlot()\n```\n\n## 3. Nghiệm kiểm chứng\nNhập PT nghiệm kiểm chứng hoặc \"NONE\" nếu không có\n\n\n```python\nsol_expr = \"NONE\"\n```\n\n\n```python\nif(sol_expr != \"NONE\"):\n#{\n sol = lambdify(symbols(\"x\"), sympify(sol_expr), \"math\");\n print(\"So sánh với giá trị đúng của nghiệm:\");\n for x in g: print(f\"y*({round(x[0], precision_x)}) = {round(x[1], precision_y)}, so sánh với giá trị chuẩn y({round(x[0], precision_x)}) = {round(sol(x[0]), precision_y)}, sai số {round(abs(sol(x[0]) - x[1]), precision_eps)}\");\n#}\n```\n", "meta": {"hexsha": "338276fb107676501812f142f37e8473a17699bb", "size": 33471, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Topic 5 - Solving Differential Equations/28.Runge_Kutta/main_rungekutta.ipynb", "max_stars_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_stars_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2020-11-23T17:00:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T06:28:40.000Z", "max_issues_repo_path": "Topic 5 - Solving Differential Equations/28.Runge_Kutta/main_rungekutta.ipynb", "max_issues_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_issues_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-09-22T17:08:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-20T12:00:59.000Z", "max_forks_repo_path": "Topic 5 - Solving Differential Equations/28.Runge_Kutta/main_rungekutta.ipynb", "max_forks_repo_name": "dthanhqhtt/MI3040-Numerical-Analysis", "max_forks_repo_head_hexsha": "cf38ea7e6dc834b19e7cffef8b867a02ba472eae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5, "max_forks_repo_forks_event_min_datetime": "2020-12-03T05:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T03:33:35.000Z", "avg_line_length": 133.884, "max_line_length": 15087, "alphanum_fraction": 0.710107257, "converted": true, "num_tokens": 2326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.3085335064598199}} {"text": "```python\nimport torch\nimport torch.nn as nn\nimport torch.distributions as td\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n```\n\n## Environment\nHere, we are going to use a simple environment to test our model. Suppose we control a particle (represented by white rectangular) that moves in a 2D plane. We can directly control the velocity of the particle along $x$ and $y$ axis. The task is to control the particle moving towards a goal position (represented by red rectangular) at the center of the plane (see video below). \n\n\n\nNow, assume we can not directly observe the position of the particle and the goal, but we can access to some visual observation that is represented as images (see figure below).\n\n\n\nNow we are going to learn a state space model of this environment. Given the learnt model, we will be able to forward simulate trajectoris in latent space and plan some actions that minimize the distance to the goal position. \n\n\n```python\nclass ParticleEnv:\n def __init__(self):\n self.state = np.array([0, 0])\n self.goal_state = np.array([0.5, 0.5])\n\n self.action_scale = 0.025\n self.step_count = 0\n\n def reset(self):\n self.step_count = 0\n self.state = 0.8 * (np.random.rand(2) - 0.5) + 0.5\n\n reward = -np.sqrt(np.square(self.state - self.goal_state).sum())\n state_image = self.generate_image()\n\n # potential_goal_states = [[0.0, 0.0], [0.9, 0.9], [0.9, 0.0], [0.0, 0.9]]\n # self.goal_state = np.array(potential_goal_states[random.choice([0, 1, 2, 3])])\n return self.state.copy(), state_image, reward\n\n def step(self, action):\n self.state += action * self.action_scale\n self.state = np.clip(self.state, a_min=0.0, a_max=1.0)\n\n reward = -np.sqrt(np.square(self.state - self.goal_state).sum())\n\n if np.sqrt(np.square(self.state - self.goal_state).sum()) < 0.01:\n done = True\n else:\n done = False\n\n state_image = self.generate_image()\n self.step_count += 1\n\n if self.step_count > 10:\n done = True\n return self.state.copy(), state_image, reward, done\n\n def generate_image(self):\n resolution = 32\n radius = 3\n image_canvas = np.zeros(shape=[3, resolution, resolution])\n\n pixel_x = int(self.state[0].item() * (resolution - 1))\n pixel_y = int(self.state[1].item() * (resolution - 1))\n\n for i in range(radius):\n for j in range(radius):\n image_canvas[:, np.clip(pixel_x + i, 0, resolution - 1), np.clip(pixel_y + j, 0, resolution - 1)] = 1.0\n image_canvas[:, np.clip(pixel_x - i, 0, resolution - 1), np.clip(pixel_y - j, 0, resolution - 1)] = 1.0\n image_canvas[:, np.clip(pixel_x + i, 0, resolution - 1), np.clip(pixel_y - j, 0, resolution - 1)] = 1.0\n image_canvas[:, np.clip(pixel_x - i, 0, resolution - 1), np.clip(pixel_y + j, 0, resolution - 1)] = 1.0\n\n pixel_x = int(self.goal_state[0].item() * (resolution - 1))\n pixel_y = int(self.goal_state[1].item() * (resolution - 1))\n\n for i in range(radius):\n for j in range(radius):\n image_canvas[0, np.clip(pixel_x + i, 0, resolution - 1), np.clip(pixel_y + j, 0, resolution - 1)] = 1.0\n image_canvas[0, np.clip(pixel_x - i, 0, resolution - 1), np.clip(pixel_y - j, 0, resolution - 1)] = 1.0\n image_canvas[0, np.clip(pixel_x + i, 0, resolution - 1), np.clip(pixel_y - j, 0, resolution - 1)] = 1.0\n image_canvas[0, np.clip(pixel_x - i, 0, resolution - 1), np.clip(pixel_y + j, 0, resolution - 1)] = 1.0\n\n return image_canvas\n```\n\nHere, we define a ReplayBuffer to collect data when interacting with the environment. The ReplayBuffer will record the visual observations (images), actions, reward (negative distance to the goal) and terminal flag at each time step. We also define some neural network template that will be used later. \n\n\n```python\nclass ReplayBuffer(object):\n \"\"\"Buffer to store and replay environment transitions.\"\"\"\n\n def __init__(self, obs_shape, action_shape, reward_shape, capacity, batch_size, length, device='cpu'):\n self.capacity = capacity\n self.batch_size = batch_size\n self.length = length\n self.device = device\n # Initialize all the buffers\n self.obs_buffer = np.empty(shape=(capacity, *obs_shape), dtype=np.float32)\n self.action_buffer = np.empty(shape=(capacity, *action_shape), dtype=np.float32)\n self.reward_buffer = np.empty(shape=(capacity, *reward_shape), dtype=np.float32)\n self.done_buffer = np.empty(shape=(capacity, *reward_shape), dtype=np.float32)\n self.idx = 0\n\n def add(self, obs, action, reward, done):\n if self.idx < self.capacity:\n self.obs_buffer[self.idx] = obs\n self.action_buffer[self.idx] = action\n self.reward_buffer[self.idx] = reward\n self.done_buffer[self.idx] = done\n self.idx += 1\n else:\n self.obs_buffer = self.obs_buffer[1:]\n self.obs_buffer = np.append(self.obs_buffer,\n obs.reshape((1, obs.shape[0], obs.shape[1], obs.shape[2])),\n axis=0)\n self.action_buffer = self.action_buffer[1:]\n self.action_buffer = np.append(self.action_buffer,\n action.reshape((1, action.shape[0])),\n axis=0)\n self.reward_buffer = self.reward_buffer[1:]\n self.reward_buffer = np.append(self.reward_buffer,\n reward.reshape((1, 1)),\n axis=0)\n self.done_buffer = self.done_buffer[1:]\n self.done_buffer = np.append(self.done_buffer,\n done.reshape((1, done.shape[0])),\n axis=0)\n\n def sample(self):\n idxs = np.random.randint(\n 0, self.capacity - self.length + 1 if self.idx == self.capacity else self.idx - self.length + 1,\n size=self.batch_size)\n obses = torch.as_tensor(self.obs_buffer[idxs], device=self.device).unsqueeze(1).float()\n actions = torch.as_tensor(self.action_buffer[idxs], device=self.device).unsqueeze(1).float()\n rewards = torch.as_tensor(self.reward_buffer[idxs], device=self.device).unsqueeze(1).float()\n dones = torch.as_tensor(self.done_buffer[idxs], device=self.device).unsqueeze(1).float()\n\n for i in range(1, self.length):\n next_obses = torch.as_tensor(self.obs_buffer[idxs + i], device=self.device).unsqueeze(1).float()\n next_actions = torch.as_tensor(self.action_buffer[idxs + i], device=self.device).unsqueeze(1).float()\n next_rewards = torch.as_tensor(self.reward_buffer[idxs + i], device=self.device).unsqueeze(1).float()\n next_dones = torch.as_tensor(self.done_buffer[idxs + i], device=self.device).unsqueeze(1).float()\n obses = torch.cat((obses, next_obses), 1)\n actions = torch.cat((actions, next_actions), 1)\n rewards = torch.cat((rewards, next_rewards), 1)\n dones = torch.cat((dones, next_dones), 1)\n\n return obses, actions, rewards, dones\n\n\nclass CNNDenseModel(nn.Module):\n def __init__(self, embed_dim: int, layers: int, h_dim: int,\n activation=nn.ReLU, min=1e-4, max=10.0):\n super().__init__()\n self._embed_size = embed_dim\n self._layers = layers\n self._hidden_size = h_dim\n self.activation = activation\n self.model = self.build_model()\n self.soft_plus = nn.Softplus()\n self._min = min\n self._max = max\n self.conv_channels = 4\n\n self.conv_in = nn.Sequential(torch.nn.Conv2d(in_channels=3,\n out_channels=self.conv_channels,\n kernel_size=3,\n stride=3))\n self.fc_out = self.build_model()\n\n def build_model(self):\n model = [nn.Linear(400, self._hidden_size)]\n model += [self.activation()]\n for i in range(self._layers - 1):\n model += [nn.Linear(self._hidden_size, self._hidden_size)]\n model += [self.activation()]\n model += [nn.Linear(self._hidden_size, self._embed_size)]\n return nn.Sequential(*model)\n\n def forward(self, obs_visual):\n x_visual = self.conv_in(obs_visual)\n x_visual = x_visual.contiguous()\n x_visual = x_visual.view(-1, self.conv_channels * 10 * 10)\n x = self.fc_out(x_visual)\n return x\n\n\nclass CNNDecoder(torch.nn.Module):\n def __init__(self, z_dim=10, h_dim=64):\n super().__init__()\n self.conv_channels = 4\n\n self.fc = nn.Sequential(torch.nn.Linear(z_dim, h_dim),\n torch.nn.ReLU(),\n torch.nn.Linear(h_dim, self.conv_channels * 10 * 10))\n self.deconv = nn.Sequential(\n torch.nn.ConvTranspose2d(in_channels=self.conv_channels, out_channels=3, kernel_size=5, stride=3))\n\n def forward(self, x):\n x = self.fc(x)\n h = x.view(-1, self.conv_channels, 10, 10)\n h = self.deconv(h) # , output_size=(x.size(0), 3, 28, 28))\n return h\n\n\nclass DenseModelNormal(nn.Module):\n def __init__(self, feature_dim: int, output_shape: tuple, layers: int, h_dim: int, activation=nn.ELU,\n min=1e-4, max=10.0):\n super().__init__()\n self._output_shape = output_shape\n self._layers = layers\n self._hidden_size = h_dim\n self.activation = activation\n # For adjusting pytorch to tensorflow\n self._feature_size = feature_dim\n # Defining the structure of the NN\n self.model = self.build_model()\n self.soft_plus = nn.Softplus()\n\n self._min = min\n self._max = max\n\n def build_model(self):\n model = [nn.Linear(self._feature_size, self._hidden_size)]\n model += [self.activation()]\n for i in range(self._layers - 1):\n model += [nn.Linear(self._hidden_size, self._hidden_size)]\n model += [self.activation()]\n model += [nn.Linear(self._hidden_size, 2 * int(np.prod(self._output_shape)))]\n return nn.Sequential(*model)\n\n def forward(self, features):\n dist_inputs = self.model(features)\n reshaped_inputs_mean = torch.reshape(dist_inputs[..., :np.prod(self._output_shape)],\n features.shape[:-1] + self._output_shape)\n reshaped_inputs_std = torch.reshape(dist_inputs[..., np.prod(self._output_shape):],\n features.shape[:-1] + self._output_shape)\n\n reshaped_inputs_std = torch.clamp(self.soft_plus(reshaped_inputs_std), min=self._min, max=self._max)\n return td.independent.Independent(td.Normal(reshaped_inputs_mean, reshaped_inputs_std), len(self._output_shape))\n```\n\n## State Space Model\nHere, we define our State Space Model (SSM). Intuitively, the SSM models an agent that is sequentially taking actions in a world and receiving rewards and visual observations. The observation $x_t$ at time $t$ visual observations are generated from the latent state $z_t$. The model assumes Markovian transitions where the next state is conditioned upon the current state and the action $a_t$ taken by the agent. Upon taking an action, the agent receives reward $r_t$. Given the graphical structure in the figure below, the SSM's joint distribution factorizes as:\n\n\n\n\\begin{align}\n &p_\\theta(x_{1:T},r_{1:T},z_{0:T},a_{1:T-1}) = \\prod_{t=1}^{T} p_\\theta(x_{t}|z_{t})p_\\theta(r_{t}|z_{t})p_\\theta(z_{t}|z_{t-1},a_{t-1})p_\\psi(a_{t-1}|z_{t-1})p(z_0)\n\\end{align}\n\nEach of the factorized distributions are modelled using nonlinear functions:\n\n* Transitions: $p_\\theta(z_{t}|z_{t-1},a_{t-1}) = p(z_{t}| f_\\theta(z_{t-1},a_{t-1}))$\n* Observations: $p_\\theta(x_{t}|z_{t}) = p(x_{t}| d_\\theta(z_{t})) $ \n* Rewards: $p_\\theta(r_{t}|z_{t}) = p(r_{t}| r_\\theta(z_{t})) $\n\nwhere $f_\\theta$, $d^m_\\theta$, $r_\\theta$, and $\\pi_\\psi$ are neural networks parameterized by $\\theta$. Given nonlinearity of these factorized distributions, the posterior distribution $p(z_{1:T}|x_{1:T},a_{1:T-1})$ is intractable. Thus, we approximate it by \n\n$$p(z_{1:T}|x_{1:T},a_{1:T-1})\\approx\\hat{q}_{\\phi}(z_{1:T}|x_{1:T},a_{1:T-1})=\\prod_{t=2}^T q_\\phi(z_{t}|g_\\phi(x_{t}, z_{t-1}, a_{t-1}))p(z_1)$$\n\nwhere $q_\\phi$ is modeled as a Gaussian distribution and $g_\\theta(x_{t}, z_{t-1}, a_{t-1})$ is a neural network parameterized by $\\phi$, which is typically called inference network.\n\nGiven all these distributions and trajectories of the form $\\tau = \\left\\{(x_{t}, a_{t}, r_{t})\\right\\}_{t=1}^{T}$ that samples from the ReplayBuffer, we seek to learn the parameters $\\theta$ and $\\phi$. Because maximum likelihood estimation is intractable in this setting, we optimize the evidence lower bound (ELBO) under the data distribution $p_d$ using a variational distribution $q$ over the latent state variables $z_t$ \n\n\\begin{align}\n\\mathbb{E}_{p_d}[\\mathrm{ELBO}] \\leq \\mathbb{E}_{p_d}[\\log p_\\theta(x_{1:T},r_{1:T}|a_{1:T-1})]\n\\end{align}\n\nwhere \n\\begin{align}\n \\mathrm{ELBO} = & \\sum_{t=1}^{T}\\Big(\\displaystyle \\mathop{\\mathbb{E}}_{\\hat{q}_{\\phi}(z_{t})}\\left[\\log p_{\\theta}(x_{t}|z_{t})\\right] +\\displaystyle\\mathop{\\mathbb{E}}_{\\hat{q}_{\\phi}(z_{t})}\\left[\\log p_{\\theta}(r_{t}|z_{t})\\right] \\nonumber\\\\\n &- \\displaystyle\\mathop{\\mathbb{E}}_{\\hat{q}_{\\phi}(z_{t-1})}\\left[\\mathrm{KL}\\left[\\hat{q}_{\\phi}(z_{t}) \\| p_{\\theta}(z_{t}|z_{t-1},a_{t-1})\\right]\\right]\\Big)\n\\end{align}\n\n\n```python\nclass SequentialVAE(nn.Module):\n def __init__(self, z_dim=8, action_dim=2, embed_dim=32):\n super().__init__()\n self.image_embed_net = CNNDenseModel(embed_dim=embed_dim, h_dim=64, layers=2)\n self.inference_net = DenseModelNormal(feature_dim=embed_dim + z_dim + action_dim,\n output_shape=(z_dim,),\n layers=2,\n h_dim=32)\n\n self.transition_net = DenseModelNormal(feature_dim=z_dim + action_dim,\n output_shape=(z_dim,),\n layers=2,\n h_dim=32)\n\n self.emission_net = CNNDecoder(z_dim=z_dim, h_dim=32)\n self.reward_net = DenseModelNormal(feature_dim=z_dim,\n output_shape=(1,),\n layers=2,\n h_dim=32)\n\n self.z_dim = z_dim\n self.action_dim = action_dim\n\n self.optimizer = torch.optim.Adam(params=self.parameters(), lr=0.002)\n\n self.anneal_factor = 2.0\n\n def get_z_post_dist(self, obs, z=None, action=None):\n\n obs_embed = self.image_embed_net(obs)\n\n if len(obs.shape) == 3:\n obs_embed = obs_embed[0]\n\n if z is None:\n z = torch.zeros(obs_embed.shape[:-1] + (self.z_dim,))\n\n if action is None:\n action = torch.zeros(obs_embed.shape[:-1] + (self.action_dim,))\n z_post_dist = self.inference_net(torch.cat([obs_embed, z, action], dim=-1))\n return z_post_dist\n\n def cross_entropy_planning(self, z):\n horizon = 4\n sample_size = 100\n discount_factor = 0.8\n\n action_samples = torch.randint(low=-1, high=2, size=(sample_size, horizon, self.action_dim))\n\n accumulated_reward = torch.zeros((1, 1))\n z_temp = z.clone().unsqueeze(0).repeat(sample_size, 1)\n for t in range(horizon):\n z_temp_dist = self.transition_net(torch.cat([z_temp, action_samples[:, t]], dim=-1))\n z_temp = z_temp_dist.mean\n\n reward = self.reward_net(z_temp).mean\n accumulated_reward = accumulated_reward + reward * (discount_factor ** t)\n\n opti_id = torch.argmax(accumulated_reward, dim=0)\n opti_action_sample = action_samples[opti_id.item()]\n return opti_action_sample[0]\n\n def learn(self, replay_buffer, episode_count):\n max_epoch = 200\n for i in range(max_epoch):\n obs, action, reward, done = replay_buffer.sample()\n\n batch_t = obs.shape[1]\n\n # get latent_state\n z_post_rsample = [[]] * batch_t\n z_post_mean = [[]] * batch_t\n z_post_std = [[]] * batch_t\n\n for t in range(batch_t):\n if t == 0:\n z_post_dist = self.get_z_post_dist(obs[:, t])\n else:\n z_post_dist = self.get_z_post_dist(obs[:, t], z_post_rsample[t - 1], action[:, t - 1])\n z_post_rsample[t] = z_post_dist.rsample()\n z_post_mean[t] = z_post_dist.mean\n z_post_std[t] = z_post_dist.stddev\n z_post_rsample = torch.stack(z_post_rsample, dim=1)\n z_post_mean = torch.stack(z_post_mean, dim=1)\n z_post_std = torch.stack(z_post_std, dim=1)\n\n z_trans_mean = [[]] * batch_t\n z_trans_std = [[]] * batch_t\n for t in range(batch_t):\n if t == 0:\n z_trans_mean[t] = z_post_mean[:, t]\n z_trans_std[t] = z_post_std[:, t]\n else:\n z_trans_dist = self.transition_net(torch.cat([z_post_rsample[:, t - 1], action[:, t]], dim=-1))\n z_trans_mean[t] = z_trans_dist.mean\n z_trans_std[t] = z_trans_dist.stddev\n z_trans_mean = torch.stack(z_trans_mean, dim=1)\n z_trans_std = torch.stack(z_trans_std, dim=1)\n\n obs_rec = self.emission_net(z_post_rsample)\n obs_rec_loss = 100 * torch.square(obs_rec - obs.view(-1, 3, 32, 32)).mean()\n\n reward_dist = self.reward_net(z_post_mean.detach())\n reward_rec_loss = -reward_dist.log_prob(reward).mean()\n\n kl_loss = (z_trans_std.log() - z_post_std.log()\n + (z_post_std.pow(2) + (z_trans_mean - z_post_mean).pow(2))\n / (2 * z_trans_std.pow(2) + 1e-5) - 0.5).mean()\n\n self.optimizer.zero_grad()\n loss = obs_rec_loss + reward_rec_loss + 1.0 * torch.max(kl_loss, torch.ones(1) * self.anneal_factor)\n loss.backward()\n self.optimizer.step()\n\n self.anneal_factor = np.clip(self.anneal_factor * 0.9, 0.1, 10.0)\n\n print(\n f'{episode_count}: obs_loss:{obs_rec_loss.item()}, reward_loss:{reward_rec_loss.item()}, kl_loss:{kl_loss.item()}')\n```\n\n## Main Loop\nWithout loss of generality, we begin at time-step $t-1$ where we have a sample of $z_{t-1}$ and taken a action $a_{t-1}$. At time step $t$, we first recieve an visual observation $x_t$ and reward $r_t$. Then,we pass $z_{t-1}$, $a_{t-1}$ and $x_t$ into the variational distribution $q_\\phi(z_t|z_{t-1}, a_{t-1}, x_t)$ and sample a $z_t$ from $q_\\phi$. Given the sample $z_t$, we optimize the following objective:\n\n\\begin{align}\n\\mathrm{argmax}_{a_{t:t+H-1}} \\ \\ J = \\mathrm{E}_{p(z_{t+1:t+H}\\ \\ \\ \\ |a_{t:t+H-1}\\ \\ \\ \\ ,z_t)}\\left[\\sum_{k=t+1}^{t+H} {\\gamma^tr(z_t)} \\right]\n\\end{align}\n\nwhere $p(z_{t+1:t+H}|a_{t:t+H-1},z_t)=\\prod_{k=t+1}^{t+H}p_\\theta(z_{k}|f_\\theta(z_{k-1},a_{k-1}))$ We choose action $a_t$ to execute and replan at each time step. After that,environment fowards to the $t+1$.\n\n\n```python\ndef main(test=False):\n env = ParticleEnv()\n replay_buffer = ReplayBuffer(obs_shape=(3, 32, 32),\n action_shape=(2,),\n reward_shape=(1,),\n capacity=1000,\n batch_size=50,\n length=10)\n\n model = SequentialVAE(z_dim=5, action_dim=2)\n if test:\n model.load_state_dict(torch.load('./model.pt'))\n\n model.eval()\n _, obs, reward = env.reset()\n\n z_post_mean = None\n action = None\n\n max_episode = 100\n episode_count = 0\n episode_data_size = 200\n\n visualize_freq = 5\n\n\n ims = []\n fig, ax = plt.subplots()\n while True:\n avg_reward = 0.0\n for i in range(episode_data_size):\n z_post_mean = model.get_z_post_dist(torch.as_tensor(obs).float(), z_post_mean, action).mean\n\n action = model.cross_entropy_planning(z_post_mean)\n _, obs, reward, done = env.step(action.detach().numpy())\n\n avg_reward += reward\n visualize_image = obs.transpose((1, 2, 0))\n if episode_count % visualize_freq == 0:\n\n im = ax.imshow(visualize_image, animated=True)\n ims.append([im])\n\n replay_buffer.add(obs, action, reward, np.array([done]))\n\n if done:\n _, obs, reward = env.reset()\n z_post_mean = None\n action = None\n\n avg_reward /= episode_data_size\n print(f'avg_reward:{avg_reward}')\n\n if episode_count % visualize_freq == 0:\n ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,\n repeat_delay=1000)\n writergif = animation.PillowWriter(fps=30)\n\n if test:\n file_name = f'./test_episode_{episode_count}.gif'\n else:\n file_name = f'./episode_{episode_count}.gif'\n ani.save(file_name, writer=writergif)\n ims.clear()\n\n if not test:\n # train model using collected data\n model.train()\n model.learn(replay_buffer, episode_count)\n model.eval()\n torch.save(model.state_dict(), './model.pt')\n\n episode_count += 1\n if episode_count > max_episode:\n break\n```\n\n\n```python\nmain(False)\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "5e9c61e208880c9b9793ac12f4878223311a646d", "size": 47713, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "L10/SeqentialVAE/sequentialVAE.ipynb", "max_stars_repo_name": "crslab/CS5340-notebooks", "max_stars_repo_head_hexsha": "ddc403ad5664315ed74a602db6d9a9401f4cbea9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "L10/SeqentialVAE/sequentialVAE.ipynb", "max_issues_repo_name": "crslab/CS5340-notebooks", "max_issues_repo_head_hexsha": "ddc403ad5664315ed74a602db6d9a9401f4cbea9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "L10/SeqentialVAE/sequentialVAE.ipynb", "max_forks_repo_name": "crslab/CS5340-notebooks", "max_forks_repo_head_hexsha": "ddc403ad5664315ed74a602db6d9a9401f4cbea9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-21T13:54:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-21T13:54:28.000Z", "avg_line_length": 58.400244798, "max_line_length": 4164, "alphanum_fraction": 0.6210466749, "converted": true, "num_tokens": 5641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3082365618643718}} {"text": "## Forecasting\n\n\n```python\n# Libraries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n%matplotlib inline\n\n# Databank \nimport mysql.connector\nfrom sqlalchemy import create_engine, exc\n\n\nimport itertools ### Modul, welches bestimmte Schleifen ermöglicht\nimport warnings ###Modul, welches uns erlaubt, bestimmte Warnungen ein- und auszublenden\n\n#Sonstige Module und Funktionen\nfrom time import gmtime, strftime #Für die aktuelle Zeit\n\n```\n\n\n```python\n#Einstellen der Darstellungsoptionen\n\n#Pandas - Mehr Zeilen und Spalten anzeigen\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\n\n#Seaborn\nsns.set_style(\"darkgrid\")\nplt.matplotlib.style.use('default')\n\nmy_colors = [\"windows blue\", \"saffron\", \"hot pink\", \"algae green\", \"dusty purple\", \"greyish\", \"petrol\", \"denim blue\", \"lime\"]\nsns.set_palette(sns.xkcd_palette(my_colors))\ncolors = sns.xkcd_palette(my_colors)\n\n#Warnings\nwarnings.filterwarnings(\"ignore\")\n\n#Connection-String für die Datenbank\nstr_db_typ = 'mysql+mysqlconnector://'\nstr_db_user = 'root'\nstr_db_password = ''\nstr_db_adr = '@localhost'\nstr_db_schema = '' \n```\n\n\n```python\n### Sammlung aller selbstgeschriebenen Funktionen\n\n#Mein Connection-String\ndef my_con_str(db_typ='mysql+mysqlconnector', db_user='root', db_passwort='', db_adr = 'localhost', db_schema = ''):\n '''Funktion, die einen DB-Connection-String zusammensetzt'''\n try:\n if len(db_schema) == 0:\n schema_sep = ''\n print('Achtung: Es wurde keine Datenbank angeben.')\n else:\n schema_sep ='/' \n con_str = '{0}://{1}{2}@{3}{4}{5}'.format(db_typ, db_user, db_passwort, db_adr, schema_sep, db_schema)\n print('Connection: {}'.format(con_str))\n return con_str\n except:\n print('Etwas ist schief gelaufen. Bitte alle Parameter überprüfen.')\n con_str = ''\n return con_str\n \n\n#Anlegen einer neuen Datenbank, falls diese noch nicht da ist.\ndef my_create_schema(dbname, con):\n engine = create_engine(con)\n engine.execute('CREATE DATABASE IF NOT EXISTS {}'.format(dbname))\n return\n\n\n#Meine Datenzusammenfassung\ndef my_df_summary(data):\n '''Eigene Funktion für die Summary'''\n try:\n dat = data.copy()\n df = pd.DataFrame([dat.min(), dat.max(), dat.mean(), dat.std(), dat.isna().sum(), dat.nunique(), dat.dtypes],\n index=['Minimum', 'Maximum', 'Mittelwert', 'Stand. Abw.','#NA', '#Uniques', 'dtypes']) \n return df\n except:\n print('Es konnte keine Summary erstellt werden.')\n return data \n\n\n```\n\n### Datenbank einrichten\n\n\n```python\ncon = my_con_str()\n```\n\n Achtung: Es wurde keine Datenbank angeben.\n Connection: mysql+mysqlconnector://root@localhost\n\n\n\n```python\nmy_create_schema('timeseries',con)\n```\n\n\n```python\ncon = my_con_str(db_schema='timeseries')\n```\n\n Connection: mysql+mysqlconnector://root@localhost/timeseries\n\n\n### Datensatz\n\n\n```python\n#Einlesen und anschauen des zu bearbeitenden Datensatzes\ndf = pd.read_excel(r'NYSE_sample.xlsx')\n```\n\n\n```python\ndf.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DateAABAAAPLAMZNAXPBACATCSCOCVXDISGEGOOGLGSHDIBMINTCJNJJPMKOMCDMMMMRKMSFTNKEPFEPGTRVUNHUTXVZWMTXOM
02006-01-0340.9110.6847.5852.5870.4457.8017.4559.0824.4035.37217.83128.8741.2482.0625.5761.6340.1920.4533.5279.1132.7526.8410.7423.7858.7845.9961.7356.5330.3846.2358.47
12006-01-0440.9710.7147.2551.9571.1759.2717.8558.9123.9935.32222.84127.0940.4881.9525.9162.5839.6220.4133.8278.7133.1326.9710.6924.5558.8946.5061.8856.1931.2746.3258.57
22006-01-0541.5310.6347.6552.5070.3359.2718.3558.1924.4135.23225.85127.0440.0882.5026.2762.3239.7420.5133.8677.9933.1826.9910.7624.5858.7046.9561.6955.9831.6345.6958.28
32006-01-0643.2110.9047.8752.6869.3560.4518.7759.2524.7435.47233.06128.8440.3884.9526.3162.6040.0220.7034.0678.6333.1226.9110.7224.8558.6447.2162.9056.1631.3545.8859.43
42006-01-0943.4210.8647.0853.9968.7761.5519.0658.9525.0035.38233.68130.3940.8283.7326.4762.9940.6720.8034.7179.0233.6626.8610.8824.8559.0847.2361.4056.8031.4845.7159.40
\n
\n\n\n\n\n```python\ndf = df.iloc[:,0:6]\n```\n\n\n```python\ndf.info()\n```\n\n \n RangeIndex: 3020 entries, 0 to 3019\n Data columns (total 6 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 Date 3020 non-null object \n 1 AABA 3019 non-null float64\n 2 AAPL 3019 non-null float64\n 3 AMZN 3019 non-null float64\n 4 AXP 3020 non-null float64\n 5 BA 3020 non-null float64\n dtypes: float64(5), object(1)\n memory usage: 141.7+ KB\n\n\n\n```python\ndf.describe()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
AABAAAPLAMZNAXPBA
count3019.0000003019.0000003019.0000003020.0000003020.000000
mean28.41272664.662892299.37623159.385315101.515868
std13.25816344.536448279.98016119.37190147.480903
min8.9500007.24000026.07000010.26000029.360000
25%16.13000023.42000081.09000045.71500070.600000
50%27.10000057.920000205.44000057.81500085.490000
75%36.63500099.480000375.14000075.892500130.615000
max72.930000176.4200001195.83000099.700000297.900000
\n
\n\n\n\n\n```python\nmy_df_summary(df)\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DateAABAAAPLAMZNAXPBA
Minimum2006-01-038.957.2426.0710.2629.36
Maximum2017-12-2972.93176.421195.8399.7297.9
MittelwertNaN28.412764.6629299.37659.3853101.516
Stand. Abw.NaN13.258244.5364279.9819.371947.4809
#NA011100
#Uniques302019602579290123852556
dtypesobjectfloat64float64float64float64float64
\n
\n\n\n\n\n```python\ndf.plot()\n```\n\n\n```python\n#Oder grafisch\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\nfig = df.plot(kind='line')\nplt.title('Plot aller numerischen Werte', size=14)\nplt.ylabel('Preis in USD')\nplt.legend(fontsize=12)\nplt.show()\n```\n\n### 1. Schritt: In welcher Frequenz liegen meine Zeitreihendaten vor?\n\n\n```python\ndf_ = df.copy()\n \ns_Dates = pd.to_datetime(df_.iloc[:,0], format='%Y-%m-%d', errors='ignore')\n \n#Mit \"Nummer\" des Wochentages\ndf_NuDay = pd.DataFrame(s_Dates.dt.dayofweek.value_counts(dropna=False))\ndf_NuDay = df_NuDay.reset_index()\ndf_NuDay.columns=['#Tag', 'Anzahl']\n \n#Mit \"Namen\" des Wochentages\ndf_NaDay = pd.DataFrame(s_Dates.dt.day_name().value_counts(dropna=False))\ndf_NaDay = df_NaDay.reset_index()\ndf_NaDay.columns=['Tag', 'Anzahl']\n```\n\n\n```python\ndf_NaDay\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
TagAnzahl
0Wednesday622
1Tuesday618
2Thursday609
3Friday605
4Monday566
\n
\n\n\n\n\n```python\n#Oder grafisch\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 4]\nfig=sns.barplot(x='Tag', y='Anzahl', data=df_NaDay)\nplt.title(\"Wie häufig sind die einzelnen Wochentage enthalten?\", size=14)\nplt.xlabel(\"\")\nplt.ylabel(\"Häufigkeiten\")\nplt.show()\n```\n\n### Aufbereiten der fehlenden Werte\n\n\n```python\n#Das muss Zeitreihe für Zeitreihe individuell gemacht werden!\n#Schritt 0: Auswahl einer Zeitreihe\ndf_ = df.iloc[:,0:2].copy() #Hier wähle ich den Index (Spalte 0) und die erste Datenspalte (Spalte 1) aus.\n\n# df.iloc[:,[0,4]].copy() #So würde ich bspw. die 4. Datenspalte (Spalte 5) auswählen.\n```\n\n\n```python\ndf_.head()\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
DateAABA
02006-01-0340.91
12006-01-0440.97
22006-01-0541.53
32006-01-0643.21
42006-01-0943.42
\n
\n\n\n\n\n```python\n#Cleansing\n#Schritt 1:\nl_colnames = df_.columns.to_list()\nl_colnames[0] = 'Date'\ndf_.columns = l_colnames\n\ndf_['Date'] = pd.to_datetime(df_['Date'], format='%Y-%m-%d', errors='ignore')\ndaterange = pd.date_range(start=min(df_['Date']), end=max(df_['Date']), freq='B')\ndf_ts = pd.DataFrame(daterange)\ndf_ts.columns = ['Date']\ndf_ts = df_ts.merge(df_, how='left', on='Date')\n\n#Schritt 2\nprint('{} fehlende Werte werden durch den zuletzt gültigen Wert ersetzt.'.format(df_ts.iloc[:,1].isna().sum()))\ndf_ts = df_ts.fillna(method='ffill')\ndf_ts = df_ts.set_index('Date', drop=True)\n```\n\n 110 fehlende Werte werden durch den zuletzt gültigen Wert ersetzt.\n\n\n\n```python\n#Plotten der vollständigen Daten\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\nfig = df_ts.plot(kind='line')\nplt.title('Vollständige Zeitreihe', size=18)\nplt.legend(fontsize=12)\nplt.ylabel('Preis in USD', size=12)\nplt.show()\n```\n\n### Ausreißer erkennen\n\n\n```python\n#Ausreißer Anzeigen - Für Zeitreihen NICHT entfernen.\n#Ausreißer erkennt man in Zeitreihen an dem Verhalten der prozentualen Veränderungen zum jeweils vorherigen Wert.\n%matplotlib inline\ndf_ = df.iloc[:,0:2].copy()\ndf_.iloc[:,1] = np.log(df_.iloc[:,1]) #Log-Differenzen sind die prozentualen Veränderungen\ndf_diff = df_.iloc[:,1].diff()\n\nplt.rcParams['figure.figsize'] = [15, 2]\n\nfig = sns.boxplot(data=df_diff, orient='h')\n\nplt.title('Häufigkeiten der prozentualen Wertveränderungen', size=14)\nplt.xlabel('')\nplt.show()\n```\n\n\n```python\ni_iqr_faktor = 2\ndf_ = df.iloc[:,0:2].copy()\ndf_['Date'] = pd.to_datetime(df_['Date'], format='%Y-%m-%d', errors='ignore')\ndf_.iloc[:,1:] = np.log(df_.iloc[:,1:])\ndf_diff = df_.diff()\n\n\nq25 = df_diff.iloc[:,1].quantile(0.25)\nq75 = df_diff.iloc[:,1].quantile(0.75)\n\niqr = q75-q25\n\ngrenze_unten = q25 - (i_iqr_faktor*iqr)\ngrenze_oben = q75 + (i_iqr_faktor*iqr)\ndf_[((df_diff.iloc[:,1] < grenze_unten) | (df_diff.iloc[:,1] > grenze_oben))]\n\n\n\n\ndf_dates = df_[((df_diff.iloc[:,1] < grenze_unten) | (df_diff.iloc[:,1] > grenze_oben))]\ndf_dates = df_dates.reset_index()\ndf_dates = df_dates.iloc[:,0:2]\n \nprint('Bei den eingegebenen Daten und des IQR-Faktors sind Tage, an denen die Wertveränderung < {0:.2f} oder > {1:.2f} war, auffällig.'.format(grenze_unten, grenze_oben))\nprint('Dies tritt an {} Tagen auf: '.format(len(df_dates)))\ndf_dates\n```\n\n Bei den eingegebenen Daten und des IQR-Faktors sind Tage, an denen die Wertveränderung < -0.05 oder > 0.06 war, auffällig.\n Dies tritt an 89 Tagen auf: \n\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
indexDate
0102006-01-18
1732006-04-19
21362006-07-19
31792006-09-19
42652007-01-24
53232007-04-18
63352007-05-04
74502007-10-17
84572007-10-26
94582007-10-29
104652007-11-07
115082008-01-10
125172008-01-24
135212008-01-30
145232008-02-01
155542008-03-18
165862008-05-02
175872008-05-05
186142008-06-12
196302008-07-07
206722008-09-04
216822008-09-18
226842008-09-22
236892008-09-29
246922008-10-02
256962008-10-08
266972008-10-09
276992008-10-13
287002008-10-14
297012008-10-15
307022008-10-16
317052008-10-21
327102008-10-28
337122008-10-30
347182008-11-07
357212008-11-12
367222008-11-13
377252008-11-18
387262008-11-19
397292008-11-24
407322008-11-28
417332008-12-01
427342008-12-02
437402008-12-10
447612009-01-12
457642009-01-15
467722009-01-28
477812009-02-10
487852009-02-17
497902009-02-24
508052009-03-17
518232009-04-13
528332009-04-27
538722009-06-22
548982009-07-29
5510942010-05-10
5611442010-07-21
5712032010-10-13
5813082011-03-15
5913482011-05-11
6013962011-07-20
6114072011-08-04
6214092011-08-08
6314102011-08-09
6414122011-08-11
6514242011-08-29
6614312011-09-08
6714462011-09-29
6814492011-10-04
6914502011-10-05
7014682011-10-31
7115042011-12-21
7216642012-08-10
7317152012-10-23
7418962013-07-17
7520312014-01-29
7620852014-04-16
7720992014-05-07
7821262014-06-16
7921942014-09-22
8022832015-01-29
8123592015-05-19
8224542015-10-02
8324962015-12-02
8425172016-01-04
8525202016-01-07
8625462016-02-16
8727582016-12-15
8828772017-06-08
\n
\n\n\n\n\n```python\n#Sind einzelne Jahre (Monate) besonders auffällig?\n%matplotlib inline\ndf_dates['Jahr'] = df_dates['Date'].map(lambda x: x.strftime('%Y'))\nplt.rcParams['figure.figsize'] = [15, 4]\ndf_dates.groupby('Jahr').size().plot(kind = 'bar')\nplt.xlabel('Periode')\nplt.ylabel('Anzahl')\nplt.show()\n```\n\n\n```python\n#Zu untersuchende Daten auswählen\ndf_ts_clean = df_ts[df_ts.index > '2013-12-31']\nprint('Insgesamt liegen {} zusammenhängende ähnliche Beobachtungen vor.'.format(len(df_ts_clean)))\n```\n\n Insgesamt liegen 1043 zusammenhängende ähnliche Beobachtungen vor.\n\n\n### Erzeugen eines Trainings- und eines Testdatensatzes\n\n\n```python\n#Zerteilung in Trainings- und Testdaten - Im Normalfall beginnt man mit dem Verhältnis 80:20\n#Weil wir Tagesdaten haben und mit \"klassischen\" Zeitreihenanalyseverfahren schwerlich mehr als 60 Perioden mit hoher\n#Genauigkeit schätzen kann, teilen wir 95:5.\n\ni_split = int(0.95*len(df_ts_clean))\n\ndf_train, df_test = df_ts_clean.iloc[:i_split,:], df_ts_clean.iloc[i_split:,:]\n\nprint('Train und Test sind zusammen {} Einträge lang.'.format(len(df_train)+len(df_test)))\nprint('D.h., alle Forecasts müssen {} Perioden lang sein.'.format(len(df_test)))\n```\n\n Train und Test sind zusammen 1043 Einträge lang.\n D.h., alle Forecasts müssen 53 Perioden lang sein.\n\n\n\n```python\n#Plot\n\nplt.rcParams['figure.figsize'] = [15, 6]\n\nplt.plot(df_train.index, df_train.values, label='Trainingsdaten')\nplt.plot(df_test.index, df_test.values, label='Testdaten', color=colors[1])\n\nplt.axvline(x = df_ts_clean.index[i_split], linewidth=2, color='grey', ls='--')\nplt.legend(loc=2, fontsize=10)\nplt.title('Aktienkurs (Close) von {} an der NYSE'.format(df_train.columns[0]), fontsize=14)\nplt.xlabel('Zeit', fontsize=10)\nplt.ylabel('Preis in USD', fontsize=10)\nplt.show()\n```\n\n\n```python\n\n```\n\n## Prognose-Verfahren\n\n## Naiver Forecast - Einfaches Fortschreiben des letzten Wertes
\n\n\n\\begin{align}\n \\hat{y}_{t+1} &= y_{t} \n\\end{align}
\n
\n\n\n```python\nvals = np.asarray(df_train.values)\ny_hat = df_test.copy()\ny_hat['naiv'] = vals[-1][0]\n```\n\n\n```python\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\n\nplt.plot(df_train.index, df_train.values, label='Traininsdaten')\nplt.plot(df_test.index, df_test.values, label='Testdaten')\nplt.plot(y_hat.index, y_hat['naiv'], label='Naiver Forecast')\nplt.legend(loc='best')\nplt.title(\"Naiver Forecast\")\nplt.show()\n```\n\n### Wie lässt sich die Güte eines Forecasts bewerten?\n\n### Root Mean Squared Error - RMSE\n\nTipp: https://en.wikipedia.org/wiki/Root-mean-square_deviation
\n\n\n\\begin{align}\n\\text{RMSE} \\; &= \\sqrt{\\frac{\\sum_{t=1}^T (\\hat{y}_t - y_t)^2}{T}} \n\\end{align}
\n\nSeltener schaut man auch einfach auch den durchschnittlichen Fehler.
\n\n\\begin{align*}\n\\text{ME} \\; &= \\frac{\\sum_{t=1}^T (\\hat{y}_t - y_t)}{T}\n\\end{align*}
\n\n
\n\n\n```python\n#Importieren der Fehler-Schätzstatistiken aus sklearn\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt #Importieren einer Wurzel-Funktion aus math\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, y_hat.naiv))\nme = (df_test.iloc[:,0] - y_hat['naiv']).sum() / len(df_test)\nprint('Für den naiven Forecast ergeben sich ein ME: {0:.4f} und ein RMSE: {1:.4f}.'.format(me,rmse))\n```\n\n Für den naiven Forecast ergeben sich ein ME: 3.2947 und ein RMSE: 3.7385.\n\n\n\nAuch kann man die Güte es Forecasts an bestimmten Eigenschaften der Residuen (Schätzfehler) ablesen.
\n\n\\begin{align*}\n\\text{Residuen} \\; &= \\hat{y}_t - y_t \\quad = \\epsilon_t\n\\end{align*}\n\n
\n\n\n```python\nresiduen = (df_test.iloc[:,0] - y_hat['naiv'])\nprint('Die Residuen haben für diesen Forecast folgene Standardabweichung: {0:.4f}.'.format(residuen.std()))\nstdres = residuen.std()\n```\n\n Die Residuen haben für diesen Forecast folgene Standardabweichung: 1.7835.\n\n\n\n```python\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 12]\nplt.subplot(2,1,1)\nresiduen.hist(bins=50, density=True)\nplt.subplot(2,1,2)\nplt.plot(df_test.index, residuen.values, label='Residuen', linewidth=2)\nplt.legend(loc=2)\nplt.title(\"Residuen\")\nplt.show()\n```\n\n### Wie kann man Verfahren denn Vergleichen?\n\n\n```python\n#Anlegen einer Tabelle, um später die Güte verschiedener Verfahren miteinander vergleichen zu können.\n#ACHTUNG: Mit dieser Zeile wird ein leerer DataFrame erzeugt.\ndf_Fehler = pd.DataFrame(columns=['Methode', 'ME', 'RMSE', 'StdRes'])\n```\n\n\n```python\n#Einfügen der Güte-Maße\ndf_Fehler = df_Fehler.append({'Methode': 'Naives Fortschreiben', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n\n```python\ndf_Fehler\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodeMERMSEStdRes
0Naives Fortschreiben3.2947173.738471.78354
\n
\n\n\n\n## Moving Average (Gleitender Mittelwert)\n\n\n```python\n#Mit rolling und mean() kann man den gleitenden Mittelwert ganz einfach erzeugen. \n#Mit einer Schleife und append schreibt man die Werte fort.\n\nn = 60 #Bspw. den gleitenden Durchschnitt über alle Handelstage des letzten Quartals.\ndf_train.rolling(n).mean().iloc[-1][0]\n```\n\n\n\n\n 63.95716666666658\n\n\n\n\n```python\nn = 60\ndf_mav = df_train.copy()\nfor i in range(len(df_test)):\n df_mav = df_mav.append({df_mav.columns[0] : df_mav.rolling(n).mean().iloc[-1][0]}, ignore_index=True)\n```\n\n\n```python\ny_hat = df_test.copy()\ny_hat_mav = df_mav.iloc[-len(df_test):].copy()\ny_hat['mav'] = y_hat_mav.values\n```\n\n\n```python\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\n\nplt.plot(df_train.index, df_train.values, label='Trainingsdaten')\nplt.plot(df_test.index, df_test.values, label='Testdaten')\nplt.plot(df_test.index, y_hat['mav'].values, label='Moving Average Forecast')\n\nplt.title('Gleitender Durchschnitt')\nplt.legend(loc='best')\nplt.show()\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, y_hat.mav))\nme = (df_test.iloc[:,0] - y_hat['mav']).sum() / len(df_test)\nprint('Für den naiven Forecast ergeben sich ein ME: {0:.4f} und ein RMSE: {1:.4f}.'.format(me,rmse))\n\nresiduen = (df_test.iloc[:,0] - y_hat['mav'])\nprint('Die Residuen haben für diesen Forecast folgene Standardabweichung: {0:.4f}.'.format(residuen.std()))\nstdres = residuen.std()\n```\n\n Für den naiven Forecast ergeben sich ein ME: 4.6000 und ein RMSE: 4.8247.\n Die Residuen haben für diesen Forecast folgene Standardabweichung: 1.4691.\n\n\n\n```python\ndf_Fehler = df_Fehler.append({'Methode': 'Moving Average', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n\n```python\ndf_Fehler\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodeMERMSEStdRes
0Naives Fortschreiben3.2947173.7384701.783540
1Moving Average4.6000204.8247141.469149
\n
\n\n\n\n\n```python\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 12]\nplt.suptitle('Moving Average')\nplt.subplot(2,1,1)\nresiduen.hist(bins=50, density=True)\nplt.subplot(2,1,2)\nplt.plot(df_test.index, residuen.values, label='Residuen', linewidth=2)\nplt.legend(loc=2)\nplt.title(\"Residuen - Moving Average\")\nplt.show()\n```\n\n\nTipp: Wer sich intensiver mit der Mathematik hinter den meisten bekannten und etablierten Verfahren zur Zeitreihenen-Analyse beschäftigen möchte, kann sich u.a. hier einlesen:
\n\nhttps://www.stat.berkeley.edu/~arturof/Teaching/STAT248/lab10_part1.html\n
\n\n### Exponentielle Glättung\n\n

Einfache (naive) exponentielle Glättung


\n\nFür die einfache exponentielle Glättung gilt:

\n\\begin{align}\n \\hat{y}_{t+1} &= \\hat{y}_{t} + \\alpha ( y_t - \\hat{y}_{t}) \n\\end{align}
\n\nWeil $\\alpha$ zwischen 0 und 1 liegen muss, kann man die Gleichung umschreiben:

\n\\begin{align}\n \\hat{y}_{t+1} &= \\alpha y_t + (1-\\alpha) \\hat{y}_{t} \n\\end{align}
\n\nUnd das lässt sich schreiben als:

\n\\begin{align}\n \\hat{y}_{t+1} &= \\alpha y_{t} + \\alpha(1-\\alpha) y_{t-1} + \\alpha(1-\\alpha)^2 y_{t-2} + \\cdots + \\alpha(1-\\alpha)^{t-1} y_{1} + \\alpha(1-\\alpha)^{t} \\hat{y}_{1} \n\\end{align}
\n
\n\n\n```python\nimport statsmodels.api as sm\nfrom statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt\n```\n\n\n```python\n#Forecasts mit verschiedenen Glättungsparametern erzeugen\nfit1 = SimpleExpSmoothing(df_train).fit(smoothing_level=0.25,optimized=False)\nfcast1 = fit1.forecast(len(df_test)).rename(r'$\\alpha=0.25$')\n\n\nfit2 = SimpleExpSmoothing(df_train).fit(smoothing_level=0.50,optimized=False)\nfcast2 = fit2.forecast(len(df_test)).rename(r'$\\alpha=0.50$')\n\n\nfit3 = SimpleExpSmoothing(df_train).fit()\nfcast3 = fit3.forecast(len(df_test)).rename(r'$\\alpha=%s$'%round(fit3.model.params['smoothing_level'],1))\n```\n\n\n```python\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\n\nfcast1.plot(legend=True, color=colors[0], ls='--')\nfit1.fittedvalues.plot(color=colors[0])\n\nfcast2.plot(legend=True, color=colors[1], ls='--')\nfit2.fittedvalues.plot(color=colors[1])\n\nfcast3.plot(legend=True, color=colors[2], ls='--')\nfit3.fittedvalues.plot(color=colors[2])\n\nplt.title('Anpassung der einfachen exponentiellen Glättung auf {}'.format(df_train.columns[0]), fontsize=14)\nplt.xlabel('Zeit', fontsize=10)\nplt.ylabel('Preis in USD', fontsize=10)\n\nplt.show()\n```\n\n\n```python\nfit3.params\n```\n\n\n\n\n {'smoothing_level': 0.9779823062246565,\n 'smoothing_slope': nan,\n 'smoothing_seasonal': nan,\n 'damping_slope': nan,\n 'initial_level': 40.42145456370888,\n 'initial_slope': nan,\n 'initial_seasons': array([], dtype=float64),\n 'use_boxcox': False,\n 'lamda': None,\n 'remove_bias': False}\n\n\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, fcast1.values))\nme = (df_test.iloc[:,0] - fcast1.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast1.values)\nstdres = residuen.std()\nprint('Forecast 1 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n```\n\n Forecast 1 - RMSE: 2.9550, ME: 2.3688, StdRes: 1.7835\n\n\n\n```python\ndf_Fehler = df_Fehler.append({'Methode': 'EinfExpGlätt 0.25', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, fcast2.values))\nme = (df_test.iloc[:,0] - fcast2.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast2.values)\nstdres = residuen.std()\nprint('Forecast 2 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n```\n\n Forecast 2 - RMSE: 3.2135, ME: 2.6843, StdRes: 1.7835\n\n\n\n```python\ndf_Fehler = df_Fehler.append({'Methode': 'EinfExpGlätt 0.5', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, fcast3.values))\nme = (df_test.iloc[:,0] - fcast3.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast3.values)\nstdres = residuen.std()\nprint('Forecast 3 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n```\n\n Forecast 3 - RMSE: 3.7143, ME: 3.2672, StdRes: 1.7835\n\n\n\n```python\ndf_Fehler = df_Fehler.append({'Methode': 'EinfExpGlätt 1', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n\n```python\ndf_Fehler\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodeMERMSEStdRes
0Naives Fortschreiben3.2947173.7384701.783540
1Moving Average4.6000204.8247141.469149
2EinfExpGlätt 0.252.3687582.9549971.783540
3EinfExpGlätt 0.52.6843403.2135151.783540
4EinfExpGlätt 13.2672223.7142611.783540
\n
\n\n\n\n

Exponentielle Glättung mit 'Level' und 'Trend' (Holt-Verfahren)


\n\nDas Holt-Verfahren nennt man auch zweifache exponentielle Glättung:

\n\n\\begin{align*}\n\\text{Level: } \\; \\quad \\ell_t &= \\alpha y_t + (1-\\alpha) (\\ell_{t-1} + b_{t-1}) \\\\ \\\\\n\\text{Growth: } \\; \\quad b_t &= \\beta^* (\\ell_t - \\ell_{t-1}) + (1-\\beta^*) b_{t-1} \\\\ \\\\\n\\text{Forecast: } \\; \\hat{y}_{t+h|t} &= \\ell_t + b_t h \\\\ \\\\\n\\end{align*}\n\nManchmal wird der Trend auch gedämpft.

\n\n\\begin{align*}\n\\text{Level: } \\; \\quad \\ell_t &= \\alpha y_t + (1-\\alpha) (\\ell_{t-1} + \\phi b_{t-1}) \\\\ \\\\\n\\text{Growth: } \\; \\quad b_t &= \\beta^* (\\ell_t - \\ell_{t-1}) + (1-\\beta^*) b_{t-1} \\\\ \\\\\n\\text{Forecast: } \\; \\hat{y}_{t+h|t} &= \\ell_t + (\\phi + \\phi^2 + \\cdots + \\phi^h) b_t h \\\\ \\\\\n\\end{align*}\n
\n\n\n```python\n#Schätzen der zweifachen exponentiellen Glättung\nfit4 = Holt(df_train.iloc[:,0]).fit(smoothing_level=0.8, smoothing_slope=0.2, optimized=False)\nfcast4 = fit4.forecast(len(df_test)).rename(\"Holt's linear trend\")\n\nfit5 = Holt(df_train.iloc[:,0], exponential=True).fit(smoothing_level=0.8, smoothing_slope=0.2, optimized=False)\nfcast5 = fit5.forecast(len(df_test)).rename(\"Exponential trend\")\n\nfit6 = Holt(df_train.iloc[:,0], damped=True).fit()\nfcast6 = fit6.forecast(len(df_test)).rename(\"Additive damped trend\")\n```\n\n\n```python\nfit6.params\n```\n\n\n\n\n {'smoothing_level': 0.9044915581422307,\n 'smoothing_slope': 1.0,\n 'smoothing_seasonal': nan,\n 'damping_slope': 0.04365336398134816,\n 'initial_level': 40.46649733865921,\n 'initial_slope': 0.0,\n 'initial_seasons': array([], dtype=float64),\n 'use_boxcox': False,\n 'lamda': None,\n 'remove_bias': False}\n\n\n\n\n```python\n#Plotten der Ergebnisse\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\n\nfcast4.plot(legend=True, color=colors[3], ls='--')\nfit4.fittedvalues.plot(color=colors[3])\n\nfcast5.plot(legend=True, color=colors[4], ls='--')\nfit5.fittedvalues.plot(color=colors[4])\n\nfcast6.plot(legend=True, color=colors[5], ls='--')\nfit6.fittedvalues.plot(color=colors[5])\n\nplt.title('Anpassung der zweifachen exponentiellen Glättung auf {}'.format(df_train.columns[0]), fontsize=14)\nplt.xlabel('Zeit', fontsize=10)\nplt.ylabel('Preis in USD', fontsize=10)\n\nplt.show()\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, fcast4.values))\nme = (df_test.iloc[:,0] - fcast4.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast4.values)\nstdres = residuen.std()\nprint('Forecast 4 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n\ndf_Fehler = df_Fehler.append({'Methode': 'Holt LT', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n\nrmse = sqrt(mean_squared_error(df_test, fcast5.values))\nme = (df_test.iloc[:,0] - fcast5.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast5.values)\nstdres = residuen.std()\nprint('Forecast 5 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n\ndf_Fehler = df_Fehler.append({'Methode': 'Holt ET', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n\nrmse = sqrt(mean_squared_error(df_test, fcast6.values))\nme = (df_test.iloc[:,0] - fcast6.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast6.values)\nstdres = residuen.std()\nprint('Forecast 6 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n\ndf_Fehler = df_Fehler.append({'Methode': 'Holt add, damped trend', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n Forecast 4 - RMSE: 9.0572, ME: 8.1390, StdRes: 4.0116\n Forecast 5 - RMSE: 8.6140, ME: 7.7632, StdRes: 3.7684\n Forecast 6 - RMSE: 3.6790, ME: 3.2271, StdRes: 1.7836\n\n\n\n```python\ndf_Fehler\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodeMERMSEStdRes
0Naives Fortschreiben3.2947173.7384701.783540
1Moving Average4.6000204.8247141.469149
2EinfExpGlätt 0.252.3687582.9549971.783540
3EinfExpGlätt 0.52.6843403.2135151.783540
4EinfExpGlätt 13.2672223.7142611.783540
5Holt LT8.1389989.0571734.011575
6Holt ET7.7632248.6139723.768397
7Holt add, damped trend3.2270573.6790061.783596
\n
\n\n\n\n

Exponentielle Glättung mit 'Level', 'Trend' und 'Saisoneffekten' (Holt-Winters)


\n\nDas Holt-Winters-Verfahren nennt man (spezielle) dreifache exponentielle Glättung:

\n\n\\begin{align*}\n\\text{Level: } \\; \\quad \\ell_t &= \\alpha \\frac{y_t}{s_{t-m}} + (1-\\alpha) (\\ell_{t-1} + b_{t-1}) \\\\\\\\\n\\text{Growth: } \\; \\quad b_t &= \\beta^* (\\ell_t - \\ell_{t-1}) + (1-\\beta^*) b_{t-1} \\\\\\\\\n\\text{Seasonal: } \\; \\quad s_t &= \\gamma \\frac{y_t}{\\ell_{t-1} + b_{t-1}} + (1-\\gamma) s_{t-m} \\\\\\\\\n\\text{Forecast: }\\; \\hat{y}_{t+h|t} &= (\\ell_t + b_t h ) s_{t-m+h_m^+} \\\\\n\\end{align*}\n
\n\n\n```python\n#Schätzen von Holt-Winters\nfit7 = ExponentialSmoothing(df_train.iloc[:,0], seasonal_periods=5, trend='add', seasonal='add').fit()\nfcast7 = fit7.forecast(len(df_test)).rename(\"Holt-Winters Additive\")\n\nfit8 = ExponentialSmoothing(df_train.iloc[:,0], seasonal_periods=5, trend='add', seasonal='mul').fit()\nfcast8 = fit8.forecast(len(df_test)).rename(\"Holt-Winters Multiplikativ\")\n\n```\n\n\n```python\n#Plotten der Ergebnisse\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\n\nfcast7.plot(legend=True, color=colors[1], ls='--')\nfit7.fittedvalues.plot(color=colors[2])\n\nfcast8.plot(legend=True, color=colors[3], ls='--')\nfit8.fittedvalues.plot(color=colors[4])\n\nplt.title('Anpassung der dreifachen exponentiellen Glättung auf {}'.format(df_train.columns[0]), fontsize=14)\nplt.xlabel('Zeit', fontsize=10)\nplt.ylabel('Preis in USD', fontsize=10)\n\nplt.show()\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, fcast7.values))\nme = (df_test.iloc[:,0] - fcast7.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast7.values)\nstdres = residuen.std()\nprint('Forecast 7 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n\ndf_Fehler = df_Fehler.append({'Methode': 'Holt Winters add', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n\nrmse = sqrt(mean_squared_error(df_test, fcast8.values))\nme = (df_test.iloc[:,0] - fcast8.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast8.values)\nstdres = residuen.std()\nprint('Forecast 8 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n\ndf_Fehler = df_Fehler.append({'Methode': 'Holt Winters mult', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n\n```\n\n Forecast 7 - RMSE: 2.3152, ME: 1.6727, StdRes: 1.6160\n Forecast 8 - RMSE: 2.3310, ME: 1.6947, StdRes: 1.6158\n\n\n\n```python\ndf_Fehler\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodeMERMSEStdRes
0Naives Fortschreiben3.2947173.7384701.783540
1Moving Average4.6000204.8247141.469149
2EinfExpGlätt 0.252.3687582.9549971.783540
3EinfExpGlätt 0.52.6843403.2135151.783540
4EinfExpGlätt 13.2672223.7142611.783540
5Holt LT8.1389989.0571734.011575
6Holt ET7.7632248.6139723.768397
7Holt add, damped trend3.2270573.6790061.783596
8Holt Winters add1.6726652.3151891.616035
9Holt Winters mult1.6947242.3310321.615823
\n
\n\n\n\n## Faktor-Dekomposition\n### Wie bekomme ich heraus, ob und welche Saisonalität in den Daten vorliegt?\n\n\n```python\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 8]\nsm.tsa.seasonal_decompose(df_train).plot()\nplt.show()\n```\n\n\n```python\n\n```\n\n## Autoregressive Prozesse AR, ARMA und ARIMA\n\n\nTipp: Eine Einführung in ARIMA-Modelle findet sich hier:
\n \nhttps://towardsdatascience.com/unboxing-arima-models-1dc09d2746f8\n\n
\n\n

Autoregressive Prognose-Modelle


\n\nBei ARIMA-Modellen wird eine Zeitreihe durch einen verzögerten Term der zu erklärenden Variable (AR) und einen Moving-Average-Term (MA) erklärt. Unter bestimmten Umständen muss das Modell insgesamt als integrierte Gleichung (I; ein- oder mehrfach differenziert) optimiert werden.

\nDafür gilt es, die optimale Anzahl an Verzögerungen (p), das optimale Momentum (q) und, ggf., das optimale Differenz-Niveau (d) gefunden werden.
\n\n\\begin{align*}\n\\text{Forecast:} \\; \\quad \\hat{y}_{t} &= \\mu + \\phi_{1}y{t-1}+\\cdots+\\phi_{p}y_{t-p}-\\theta_{1}\\epsilon_{t-1}-\\cdots-\\theta_{q}\\epsilon_{t-q} \\\\\\\\\n\\text{Für d = 0:} \\; \\quad y_t &= Y_t \\\\\\\\\n\\text{Für d = 1:} \\; \\quad y_t &= Y_t - Y_{t-1} \\\\\\\\\n\\text{Für d = 2:} \\; \\quad y_t &= (Y_t - Y_{t-1})-(Y_{t-1} - Y_{t-2})\n\\end{align*}\n
\n\n\n```python\nfrom statsmodels.tsa.arima_model import ARIMA\nwarnings.filterwarnings(\"ignore\") # specify to ignore warning messages\n```\n\n\n```python\n#Eigene Auto-Arima-Funktion\n#Erzeugen einer Liste von allen Parametern, die getestet werden sollen.\np = range(0, 6)\nd = range(0, 3)\nq = range(0, 5)\npdq = list(itertools.product(p, d, q))\npdq\n```\n\n\n\n\n [(0, 0, 0),\n (0, 0, 1),\n (0, 0, 2),\n (0, 0, 3),\n (0, 0, 4),\n (0, 1, 0),\n (0, 1, 1),\n (0, 1, 2),\n (0, 1, 3),\n (0, 1, 4),\n (0, 2, 0),\n (0, 2, 1),\n (0, 2, 2),\n (0, 2, 3),\n (0, 2, 4),\n (1, 0, 0),\n (1, 0, 1),\n (1, 0, 2),\n (1, 0, 3),\n (1, 0, 4),\n (1, 1, 0),\n (1, 1, 1),\n (1, 1, 2),\n (1, 1, 3),\n (1, 1, 4),\n (1, 2, 0),\n (1, 2, 1),\n (1, 2, 2),\n (1, 2, 3),\n (1, 2, 4),\n (2, 0, 0),\n (2, 0, 1),\n (2, 0, 2),\n (2, 0, 3),\n (2, 0, 4),\n (2, 1, 0),\n (2, 1, 1),\n (2, 1, 2),\n (2, 1, 3),\n (2, 1, 4),\n (2, 2, 0),\n (2, 2, 1),\n (2, 2, 2),\n (2, 2, 3),\n (2, 2, 4),\n (3, 0, 0),\n (3, 0, 1),\n (3, 0, 2),\n (3, 0, 3),\n (3, 0, 4),\n (3, 1, 0),\n (3, 1, 1),\n (3, 1, 2),\n (3, 1, 3),\n (3, 1, 4),\n (3, 2, 0),\n (3, 2, 1),\n (3, 2, 2),\n (3, 2, 3),\n (3, 2, 4),\n (4, 0, 0),\n (4, 0, 1),\n (4, 0, 2),\n (4, 0, 3),\n (4, 0, 4),\n (4, 1, 0),\n (4, 1, 1),\n (4, 1, 2),\n (4, 1, 3),\n (4, 1, 4),\n (4, 2, 0),\n (4, 2, 1),\n (4, 2, 2),\n (4, 2, 3),\n (4, 2, 4),\n (5, 0, 0),\n (5, 0, 1),\n (5, 0, 2),\n (5, 0, 3),\n (5, 0, 4),\n (5, 1, 0),\n (5, 1, 1),\n (5, 1, 2),\n (5, 1, 3),\n (5, 1, 4),\n (5, 2, 0),\n (5, 2, 1),\n (5, 2, 2),\n (5, 2, 3),\n (5, 2, 4)]\n\n\n\n\n```python\nts = df_train.copy()\n```\n\n\n```python\nAIC = []\nARIMA_model = []\ni = 0\n\nfor param in pdq:\n try:\n mod = ARIMA(ts, order=param)\n results = mod.fit()\n print() \n print(i, \": \",'ARIMA{} - AIC:{}'.format(param, results.aic), end='\\r')\n AIC.append(results.aic)\n ARIMA_model.append([param])\n except:\n continue\n i = i + 1\n```\n\n \n 0 : ARIMA(0, 0, 0) - AIC:7013.454578932967\n 1 : ARIMA(0, 0, 1) - AIC:5771.249334363882\n 2 : ARIMA(0, 1, 0) - AIC:2151.2132474557666\n 3 : ARIMA(0, 1, 1) - AIC:2152.659153522236\n 4 : ARIMA(0, 1, 2) - AIC:2154.6282701671657\n 5 : ARIMA(0, 1, 3) - AIC:2154.2940952408876\n 6 : ARIMA(0, 1, 4) - AIC:2156.2916346441207\n 7 : ARIMA(0, 2, 0) - AIC:2855.776649047264\n 8 : ARIMA(0, 2, 1) - AIC:2155.557809569962\n 9 : ARIMA(0, 2, 2) - AIC:2156.873683836948\n 10 : ARIMA(0, 2, 3) - AIC:2158.8664849005554\n 11 : ARIMA(0, 2, 4) - AIC:2158.185413456307\n 12 : ARIMA(1, 0, 0) - AIC:2161.715398545889\n 13 : ARIMA(1, 1, 0) - AIC:2152.652069831722\n 14 : ARIMA(1, 1, 1) - AIC:2154.05849222667\n 15 : ARIMA(1, 1, 2) - AIC:2156.00943161475\n 16 : ARIMA(1, 1, 3) - AIC:2156.283781964605\n 17 : ARIMA(1, 1, 4) - AIC:2158.1436481289193\n 18 : ARIMA(1, 2, 0) - AIC:2554.3582284510103\n 19 : ARIMA(1, 2, 1) - AIC:2156.868439790889\n 20 : ARIMA(1, 2, 2) - AIC:2158.318046812955\n 21 : ARIMA(1, 2, 4) - AIC:2159.039955302013\n 22 : ARIMA(2, 0, 0) - AIC:2163.274614068158\n 23 : ARIMA(2, 1, 0) - AIC:2154.6011925086386\n 24 : ARIMA(2, 1, 1) - AIC:2156.015511628101\n 25 : ARIMA(2, 1, 2) - AIC:2156.9449701306753\n 26 : ARIMA(2, 1, 3) - AIC:2157.324687034196\n 27 : ARIMA(2, 1, 4) - AIC:2159.308318725509\n 28 : ARIMA(2, 2, 0) - AIC:2460.2116081875092\n 29 : ARIMA(2, 2, 1) - AIC:2158.8482822691212\n 30 : ARIMA(2, 2, 4) - AIC:2156.52216639959\n 31 : ARIMA(3, 0, 0) - AIC:2165.1799595355556\n 32 : ARIMA(3, 1, 0) - AIC:2154.555067840616\n 33 : ARIMA(3, 1, 1) - AIC:2156.5490428831517\n 34 : ARIMA(3, 1, 2) - AIC:2157.348646689716\n 35 : ARIMA(3, 1, 3) - AIC:2153.1014330217354\n 36 : ARIMA(3, 1, 4) - AIC:2154.1306360821527\n 37 : ARIMA(3, 2, 0) - AIC:2387.4182292152723\n 38 : ARIMA(3, 2, 1) - AIC:2158.5533428297467\n 39 : ARIMA(3, 2, 2) - AIC:2158.862946838637\n 40 : ARIMA(3, 2, 3) - AIC:2159.023606585547\n 41 : ARIMA(3, 2, 4) - AIC:2163.844070173267\n 42 : ARIMA(4, 0, 0) - AIC:2165.367570202199\n 43 : ARIMA(4, 1, 0) - AIC:2156.5530637506677\n 44 : ARIMA(4, 1, 1) - AIC:2157.5206766635756\n 45 : ARIMA(4, 1, 2) - AIC:2159.348635885285\n 46 : ARIMA(4, 1, 3) - AIC:2154.070742005638\n 47 : ARIMA(4, 1, 4) - AIC:2147.873205912918\n 48 : ARIMA(4, 2, 0) - AIC:2351.2852861599386\n 49 : ARIMA(4, 2, 1) - AIC:2160.5327629534695\n 50 : ARIMA(4, 2, 2) - AIC:2160.8313532391257\n 51 : ARIMA(4, 2, 3) - AIC:2162.708666584628\n 52 : ARIMA(4, 2, 4) - AIC:2157.925120733335\n 53 : ARIMA(5, 0, 0) - AIC:2167.3500849145366\n 54 : ARIMA(5, 1, 0) - AIC:2158.134017272393\n 55 : ARIMA(5, 1, 1) - AIC:2158.0045903186533\n 56 : ARIMA(5, 1, 2) - AIC:2157.36639751832\n 57 : ARIMA(5, 1, 3) - AIC:2155.7195524462245\n 58 : ARIMA(5, 1, 4) - AIC:2152.439435093944\n 59 : ARIMA(5, 2, 0) - AIC:2337.485641686427\n 60 : ARIMA(5, 2, 1) - AIC:2161.9573835202627\r\n\n\n```python\nprint('Das AIC nimmt mit {} für das Modell ARIMA{} den kleinsten Wert an.'.format(min(AIC), ARIMA_model[AIC.index(min(AIC))][0]))\n```\n\n Das AIC nimmt mit 2147.873205912918 für das Modell ARIMA(4, 1, 4) den kleinsten Wert an.\n\n\n\n```python\nmod = ARIMA(ts,order=ARIMA_model[AIC.index(min(AIC))][0])\nfit9 = mod.fit()\n```\n\n\n```python\n#Achtung, wenn d != 0, dann werden Differenzen vorhergesagt.\nfcast9 = fit9.predict(start=len(ts), end=len(ts)+len(df_test)-1, dynamic=False)\nfcast9.head()\n```\n\n\n\n\n 2017-10-18 0.112075\n 2017-10-19 0.178367\n 2017-10-20 0.254370\n 2017-10-23 0.075667\n 2017-10-24 0.274277\n Freq: B, dtype: float64\n\n\n\n\n```python\ny_hat_ = fcast9.copy()\ny_hat_[0] = y_hat_[0] + ts.iloc[-1][0]\ny_hat_ = np.cumsum(y_hat_.values)\nfcast9[:] = y_hat_\n```\n\n\n```python\n#Plotten der Ergebnisse\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = [15, 6]\n\nplt.plot(df_train.index, df_train.values, label='Trainingsdaten')\nplt.plot(fcast9.index, fcast9.values, label='ARIMA', color=colors[2])\n\nplt.legend(loc=2)\nplt.title('Anpassung von autoregressiven Modellen auf {}'.format(df_train.columns[0]), fontsize=14)\nplt.xlabel('Zeit', fontsize=10)\nplt.ylabel('Preis in USD', fontsize=10)\n\nplt.show()\n```\n\n\n```python\nrmse = sqrt(mean_squared_error(df_test, fcast9.values))\nme = (df_test.iloc[:,0] - fcast9.values).sum() / len(df_test)\nresiduen = (df_test.iloc[:,0] - fcast9.values)\nstdres = residuen.std()\nprint('Forecast 7 - RMSE: {0:.4f}, ME: {1:.4f}, StdRes: {2:.4f}'.format(rmse, me, stdres))\n\ndf_Fehler = df_Fehler.append({'Methode': 'ARIMA(4,1,4)', 'ME': me, 'RMSE': rmse, 'StdRes': stdres},\n ignore_index=True)\n```\n\n Forecast 7 - RMSE: 2.6475, ME: 2.0076, StdRes: 1.7424\n\n\n\n```python\ndf_Fehler\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
MethodeMERMSEStdRes
0Naives Fortschreiben3.2947173.7384701.783540
1Moving Average4.6000204.8247141.469149
2EinfExpGlätt 0.252.3687582.9549971.783540
3EinfExpGlätt 0.52.6843403.2135151.783540
4EinfExpGlätt 13.2672223.7142611.783540
5Holt LT8.1389989.0571734.011575
6Holt ET7.7632248.6139723.768397
7Holt add, damped trend3.2270573.6790061.783596
8Holt Winters add1.6726652.3151891.616035
9Holt Winters mult1.6947242.3310321.615823
10ARIMA(0,1,0)2.0076192.6475101.742428
11ARIMA(4,1,4)2.0076192.6475101.742428
\n
\n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "ec7cc4199b94c6b3067e4302a5f487fad8ade59f", "size": 918353, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "9_Prognose_with_Python.ipynb", "max_stars_repo_name": "kafasin/big_data_science", "max_stars_repo_head_hexsha": "b989cea4e6f53eb66adfb9add7bab71006775a27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-08-16T19:35:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T19:35:48.000Z", "max_issues_repo_path": "9_Prognose_with_Python.ipynb", "max_issues_repo_name": "kafasin/big_data_science", "max_issues_repo_head_hexsha": "b989cea4e6f53eb66adfb9add7bab71006775a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "9_Prognose_with_Python.ipynb", "max_forks_repo_name": "kafasin/big_data_science", "max_forks_repo_head_hexsha": "b989cea4e6f53eb66adfb9add7bab71006775a27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 238.6572245322, "max_line_length": 115400, "alphanum_fraction": 0.8992065143, "converted": true, "num_tokens": 22902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.30807914889316823}} {"text": "\n\n\n# IllinoisGRMHD: Basic equations and modules\n\n## Authors: Leo Werneck & Zach Etienne\n\n**This module is currently under development**\n\n## This module introduces the basic equations solved by IllinoisGRMHD and provides an introduction to the modules inside the code.\n\n## Introduction:\n\n[`IllinoisGRMHD`](http://arxiv.org/abs/1501.07276) solves the equations of General Relativistic MagnetoHydroDynamics (GRMHD) using a high-resolution shock capturing scheme. It is a rewrite of the Illinois Numerical Relativity (ILNR) group's GRMHD code, and generates results that agree to roundoff error with that original code. Its feature set coincides with the features of the ILNR group's recent code (ca. 2009-2014), which was used in their modeling of the following systems:\n\n1. Magnetized circumbinary disk accretion onto binary black holes\n2. Magnetized black hole-neutron star mergers\n3. Magnetized Bondi flow, Bondi-Hoyle-Littleton accretion\n4. White dwarf-neutron star mergers\n\n`IllinoisGRMHD` is particularly good at modeling GRMHD flows into black holes without the need for excision. Its [HARM-based conservative-to-primitive solver](https://arxiv.org/abs/astro-ph/0512420) has also been modified to check the physicality of conservative variables prior to primitive inversion, and move them into the physical range if they become unphysical.\n\nCurrently IllinoisGRMHD consists of\n\n1. the Piecewise Parabolic Method (PPM) for reconstruction, \n2. the Harten, Lax, van Leer (HLL/HLLE) approximate Riemann solver, and\n3. a modified HARM Conservative-to-Primitive solver. \n\n`IllinoisGRMHD` evolves the vector potential $A_{\\mu}$ (on staggered grids) instead of the magnetic fields ($B^i$) directly, to guarantee that the magnetic fields will remain divergenceless even at AMR boundaries. On uniform resolution grids, this vector potential formulation produces results equivalent to those generated using the standard, staggered flux-CT scheme. This scheme is based on that of [Del Zanna *et al.* (2003)](https://arxiv.org/abs/astro-ph/0210618).\n\n### Required and recommended citations:\n* **(Required)** Etienne, Z. B., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L. IllinoisGRMHD: an open-source, user-friendly GRMHD code for dynamical spacetimes. Class. Quantum Grav. 32 (2015) 175009. ([arxiv:1501.07276](http://arxiv.org/abs/1501.07276)).\n* **(Required)** Noble, S. C., Gammie, C. F., McKinney, J. C., Del Zanna, L. Primitive Variable Solvers for Conservative General Relativistic Magnetohydrodynamics. Astrophysical Journal, 641, 626 (2006) ([astro-ph/0512420](https://arxiv.org/abs/astro-ph/0512420)).\n* **(Recommended)** Del Zanna, L., Bucciantini N., Londrillo, P. An efficient shock-capturing central-type scheme for multidimensional relativistic flows - II. Magnetohydrodynamics. A&A 400 (2) 397-413 (2003). DOI: 10.1051/0004-6361:20021641 ([astro-ph/0210618](https://arxiv.org/abs/astro-ph/0210618)).\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis module is organized as follows\n\n1. [Step 1](#basic_equations): **The equations of GRMHD**\n1. [Step 2](#suitable_equations): **Recasting the equations of GRMHD into a more useful form**\n 1. [Step 2.1](#einstein_equations): Einstein's equations\n 1. [Step 2.2](#conserv_of_baryon_number): Conservation of baryon number\n 1. [Step 2.3](#conserv_of_em_tensor): Conservation of energy-momentum\n 1. [Step 2.4](#em_evo_equations): The evolution equations for the electromagnetic field\n 1. [Step 2.5](#equation_of_state): The equation of state (EOS)\n1. [Step 3](#latex_pdf_output): **Output this notebook to $\\LaTeX$-formatted PDF file**\n\n\n\n# Step 1: The equations of GRMHD \\[Back to [top](#toc)\\]\n$$\\label{basic_equations}$$\n\nThe basic equations solved by `IllinoisGRMHD` are\n\n1. Einstein's equations: $R^{\\mu\\nu} + \\frac{1}{2}g^{\\mu\\nu}R = 8\\pi T^{\\mu\\nu} = 8\\pi \\left(T^{\\mu\\nu}_{\\rm matter} + T^{\\mu\\nu}_{\\rm EM}\\right)$ ;\n1. Conservation of baryon number: $\\nabla_{\\mu}\\left(\\rho_{0} u^{\\mu}\\right) = 0$ ;\n1. Conservation of energy-momentum: $\\nabla_{\\mu}T^{\\mu\\nu} = \\nabla_{\\mu}\\left(T^{\\mu\\nu}_{\\rm matter} + T^{\\mu\\nu}_{\\rm EM}\\right) = 0$ ;\n1. Dual of homogeneous Maxwell's equations: $\\nabla_{\\nu} F^{*\\mu\\nu}=\\frac{1}{\\sqrt{-g}}\\partial_{\\nu}\\left(\\sqrt{-g}F^{*\\mu\\nu}\\right)=0$ ,\n\nwhere $g_{\\mu\\nu}$ is the ADM 4-metric, $R_{\\mu\\nu}$ and $R$ are the Ricci tensor and scalar, respectively, constructed from $g_{\\mu\\nu}$, $\\nabla_{\\mu}$ is the covariant derivative compatible with $g_{\\mu\\nu}$, $g\\equiv\\det\\left(g_{\\mu\\nu}\\right)$, $F^{\\mu\\nu}$ is the Faraday tensor and $F^{*\\mu\\nu}=\\frac{1}{2}\\epsilon^{\\mu\\nu\\rho\\sigma}F_{\\mu\\nu}$ its dual ($\\epsilon^{\\mu\\nu\\rho\\sigma}$ is the Levi-Civita symbol).\n\nThe final equation that must be solved is the equation of state (EOS) for the matter. Currently `IllinoisGRMHD` implements a hybrid EOS of the form (**add citation**)\n\n5. Equation of State (EOS): $P(\\rho_{0},\\epsilon) = P_{\\rm cold}(\\rho_{0}) + \\left(\\Gamma_{\\rm th}-1\\right) \\rho_{0} \\left[\\epsilon-\\epsilon_{\\rm cold}(\\rho_{0})\\right]$ ,\n\nwhere P is the pressure, $\\epsilon$ the specific internal energy (the subscript cold indicate the cold components of these quantities), and $\\Gamma_{\\rm th}$ is a constant parameter which determines the conversion efficiency of kinetic to thermal energy at shocks.\n\n\n\n# Step 2: Recasting the equations of GRMHD into a more useful form \\[Back to [top](#toc)\\]\n$$\\label{suitable_equations}$$\n\nIn this step we will write down the equations used by `IllinoisGRMHD` in the form they are implemented. To give an example, the GRMHD equations are written in the *conservative form*\n\n$$\n\\partial_{t}\\boldsymbol{C} + \\boldsymbol{\\nabla}\\cdot\\boldsymbol{F} = \\boldsymbol{S}\\ ,\n$$\n\nwhere $\\boldsymbol{C} = \\left\\{\\rho_{\\star},\\tilde\\tau,\\tilde{S}_{i},\\tilde{B}^{i}\\right\\}$ is the vector of conservative variables, $\\boldsymbol{F}$ is the flux vector, and $\\boldsymbol{S}$ the vector of source terms (explict expressions for the components of $\\boldsymbol{C}$, $\\boldsymbol{F}$, and $\\boldsymbol{S}$ can be found below).\n\n\n\n## Step 2.1: Einstein's equations \\[Back to [top](#toc)\\]\n$$\\label{einstein_equations}$$\n\n`IllinoisGRMHD` solves Einstein's field equations (with $G_{\\rm N}=1=c$) in the presence of matter sources,\n\n$$\nG^{\\mu\\nu} = 8\\pi T^{\\mu\\nu}\\ ,\n$$\n\nwhere $G^{\\mu\\nu} \\equiv R^{\\mu\\nu} + \\frac{1}{2}g^{\\mu\\nu}R$ is the Einstein tensor and the total energy-momentum tensor, $T^{\\mu\\nu}$, is the sum of the matter and electromagnetic energy-momentum tensors:\n\n$$\nT^{\\mu\\nu} = T^{\\mu\\nu}_{\\rm matter} + T^{\\mu\\nu}_{\\rm EM}\\ .\n$$\n\nEinstein's field equations are solved using the BSSN formalism (see [this tutorial module](../../Tutorial-BSSN_formulation.ipynb) for an overview).\n\n\n\n## Step 2.2: Conservation of baryon number \\[Back to [top](#toc)\\]\n$$\\label{conserv_of_baryon_number}$$\n\nThe conservation of baryon number equation is written as (cf. eqs. (6), (7), and (18) in [Etienne *et al.*](https://arxiv.org/pdf/1501.07276.pdf))\n\n$$\n\\boxed{\\partial_{t}\\rho_{\\star} + \\partial_{j}\\left(\\rho_{\\star}v^{j}\\right) = 0}\\ ,\n$$\n\nwhere $\\rho_{\\star}\\equiv \\alpha \\sqrt{\\gamma}\\rho_{0}u^{0}$ and $v^{i}\\equiv u^{i}/u^{0}$.\n\n\n\n## Step 2.3: Conservation of energy-momentum \\[Back to [top](#toc)\\]\n$$\\label{conserv_of_em_tensor}$$\n\nIn the ideal MHD limit, we can write down the total energy momentum tensor as (cf. eq. (8) in [Etienne *et al.*](https://arxiv.org/pdf/1501.07276.pdf) and the discussion before it)\n\n$$\nT^{\\mu \\nu} = (\\rho_0 h +b^2) u^{\\mu} u^{\\nu} + \\left( P + \\frac{b^2}{2}\\ .\n\\right) g^{\\mu \\nu} - b^{\\mu} b^{\\nu}\n$$\n\nThe spatial components of the energy-momentum conservation equation give (cf. eq. (18) of https://arxiv.org/pdf/astro-ph/0503420.pdf and eqs. (35) and (36) of [Duez et al.](https://arxiv.org/pdf/astro-ph/0503420.pdf))\n\n$$\n\\boxed{\\partial_{t}\\tilde{S}_{i} + \\partial_{j}\\left(\\alpha\\sqrt{\\gamma} T^{j}_{\\ i}\\right) = \\frac{1}{2}\\sqrt{\\gamma} T^{\\alpha\\beta}\\partial_{i}g_{\\alpha\\beta}}\\ ,\n$$\n\nwhere\n\n$$\n\\tilde{S}_{i} = \\sqrt{\\gamma}S_{i} = \\alpha \\sqrt{\\gamma} T^{0}_{\\ i} = \\left(\\rho_{\\star}h + \\alpha u^{0}\\sqrt{\\gamma}b^{2}\\right)u_{i} - \\alpha \\sqrt{\\gamma} b^{0} b^{i}\\ .\n$$\n\nThe time component of the energy-momentum conservation equation gives (cf. eq. (18) of [Etienne *et al.*](https://arxiv.org/pdf/1501.07276.pdf))\n\n$$\n\\boxed{\\partial_{t}\\tilde{\\tau} + \\partial_{i}\\left(\\alpha^{2}\\sqrt{\\gamma}T^{0i} - \\rho_{\\star}v^{i}\\right) = s}\\ ,\n$$\n\nwhere\n\n\\begin{align}\n\\tilde{\\tau} &= \\sqrt{\\gamma}n_{\\mu}n_{\\nu} - \\rho_{\\star} = \\alpha^{2}\\sqrt{\\gamma}T^{00} - \\rho_{\\star}\\ ,\\\\\ns &= -\\alpha \\sqrt{\\gamma} T^{\\mu\\nu} \\nabla_{\\nu} n_{\\mu} = \\alpha\\sqrt{\\gamma}\\left[\\left(T^{00}\\beta^{i}\\beta^{j} + 2T^{0i}\\beta^{j} + T^{ij}\\right)K_{ij} - \\left(T^{00}\\beta^{i} + T^{0i}\\right)\\partial_{i}\\alpha\\right]\\ ,\n\\end{align}\n\nwith $n_{\\mu} = \\left(\\alpha,0,0,0\\right)$ being the normal vector and $K_{ij}$ the extrinsic curvature.\n\n\n\n## Step 2.4: The evolution equations for the electromagnetic field \\[Back to [top](#toc)\\]\n$$\\label{em_evo_equations}$$\n\nFrom the spatial components of the dual of Maxwell's equations,\n\n$$\n\\nabla_{\\nu} F^{*\\mu\\nu}=\\frac{1}{\\sqrt{-g}}\\partial_{\\nu}\\left(\\sqrt{-g}F^{*\\mu\\nu}\\right)=0\\ ,\n$$\n\nwe get the magnetic induction equation, which in conservative form may be written as (cf. eq. (12) [Etienne *et al.*](https://arxiv.org/pdf/1501.07276.pdf))\n\n$$\n\\partial_{t}\\tilde{B}^{i} + \\partial_{j}\\left(v^{j}\\tilde{B}^{i} - v^{i}\\tilde{B}^{j}\\right) = 0\\ ,\n$$\n\nwhere $\\tilde{B}^{i} = \\sqrt{\\gamma}B^{i}$. We must also guarantee that no magnetic mopoles form, via the constraint\n\n$$\n\\partial_{i}\\tilde{B}^{i} = 0\\ ,\n$$\n\nwhich is the time component of the dual of Maxwell's equations. Satisfying this constraint equation while evolving the magnetic field forward in time via the evolution equation above turns out to be a nontrivial endeavor, *particularly* on AMR grids. Instead, we choose to evolve the magnetic 4-vector potential $\\mathcal{A}_{\\mu}$ instead of the magnetic fields directly, so that\n\n\\begin{align}\n\\mathcal{A}_{\\mu} &= \\Phi n_{\\mu} + A_{\\mu}\\ ,\\\\\n\\tilde{B}^{i} &= \\tilde{\\epsilon}^{ijk}\\partial_{j}A_{k}\\ ,\n\\end{align}\n\nwhere $A_{\\mu}$ is purely spatial ($A_{\\mu}n^{\\mu} = 0$) and $\\Phi$ is the EM scalar potential.\n\nSpecial finite difference operators for the vector potential are defined in IllinoisGRMHD so that the divergence of a curl is zero to roundoff error, which implies that the divergence of $\\tilde{B}^{i}$ (as defined above) is zero and the condition $\\partial_{i}\\tilde{B}^{i}=0$ is satisfied automatically, *even on AMR grids*.\n\nIn terms of $A_{i}$, the induction equation becomes\n\n$$\n\\boxed{\\partial_t A_i = \\tilde\\epsilon_{ijk} v^j \\tilde{B}^k - \\partial_i (\\alpha \\Phi - \\beta^j A_j)}\\ .\n$$\n\nThe final equation comes from choosing the covariant version of the \"[generalized Lorenz gauge condition](https://arxiv.org/pdf/1207.3354.pdf)\" that was introduced by the Illinois Relativity group,\n\n$$\n\\nabla_{\\mu}\\mathcal{A}^{\\mu} = \\xi n_{\\mu} \\mathcal{A}^{\\mu}\\ ,\n$$\n\nwhere $\\xi$ is a parameter with dimensions 1/Length, chosen so that the CFL condition remains satisfied. This gauge choice yields the additional evolution equation\n\n$$\n\\boxed{\\partial_t [\\sqrt{\\gamma} \\Phi] + \\partial_j (\\alpha \\sqrt{\\gamma} A^j - \\beta^j [\\sqrt{\\gamma}\\Phi]) = -\\xi\\alpha \\sqrt{\\gamma}\\Phi}\\ .\n$$\n\nNote that in `IllinoisGRMHD` the evolved variable is $\\sqrt{\\gamma}\\Phi$, not $\\Phi$.\n\n\n\n## Step 2.5: The equation of state (EOS) \\[Back to [top](#toc)\\]\n$$\\label{equation_of_state}$$\n\n`IllinoisGRMHD` currently implements a hybrid EOS of the form\n\n$$\n\\boxed{P(\\rho_{0},\\epsilon) = P_{\\rm cold}(\\rho_{0}) + \\left(\\Gamma_{\\rm th}-1\\right) \\rho_{0} \\left[\\epsilon-\\epsilon_{\\rm cold}(\\rho_{0})\\right]}\\ .\n$$\n\nThe function $\\epsilon_{\\rm cold}$ is related to $P_{\\rm cold}$ by the fist law of thermodynamics,\n\n$$\n\\epsilon_{\\rm cold}(\\rho_{0}) = \\int \\frac{P_{\\rm cold}(\\rho_{0})}{\\rho_{0}^{2}}d\\rho_{0}\\ .\n$$\n\nCurrently, all functions within `IllinoisGRMHD` support piecewise-defined $P_{\\rm cold}(\\rho_{0})$ (the so-called \"piecewise polytrope\" EOS) with up to nine different polytropic indices, except for the conservatives-to-primitives solver, which currently supports only one.\n\nIn typical runs of the code, particularly on the ones presented in the [release paper](https://arxiv.org/pdf/1501.07276.pdf), the $\\Gamma$-law EOS, $P = (\\Gamma - 1)\\rho_{0}\\epsilon$, is adopted. This corresponds to setting $P_{\\rm cold} = (\\Gamma - 1)\\rho_{0}\\epsilon_{\\rm cold}$ in the boxed equation above, which is equivalent to $P_{\\rm cold} = \\kappa\\rho_{0}^{\\Gamma}$ (with constant $\\kappa$), and $\\Gamma_{\\rm th} = \\Gamma$. In the absence of shocks, $\\epsilon = \\epsilon_{\\rm cold}$ so that $P = P_{\\rm cold}$.\n\n\n\n# Step 3: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\n\n```python\n#!jupyter nbconvert --to latex --template ../../latex_nrpy_style.tplx Tutorial-IllinoisGRMHD__Overview.ipynb\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__Overview.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__Overview.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__Overview.tex\n!rm -f Tut*.out Tut*.aux Tut*.log\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "6a8311970af5e3e96eb2c2519626a196407ed652", "size": 17299, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__Overview.ipynb", "max_stars_repo_name": "kazewong/nrpytutorial", "max_stars_repo_head_hexsha": "cc511325f37f01284b2b83584beb2a452556b3fb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__Overview.ipynb", "max_issues_repo_name": "kazewong/nrpytutorial", "max_issues_repo_head_hexsha": "cc511325f37f01284b2b83584beb2a452556b3fb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__Overview.ipynb", "max_forks_repo_name": "kazewong/nrpytutorial", "max_forks_repo_head_hexsha": "cc511325f37f01284b2b83584beb2a452556b3fb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.348534202, "max_line_length": 545, "alphanum_fraction": 0.5955257529, "converted": true, "num_tokens": 4363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3075841679616698}} {"text": "```python\nimport mmf_setup;mmf_setup.nbinit()\n```\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n

This cell contains some definitions for equations and some CSS for styling\n the notebook. If things look a bit strange, please try the following:\n

    \n
  • Choose \"Trust Notebook\" from the \"File\" menu.
  • \n
  • Re-execute this cell.
  • \n
  • Reload the notebook.
  • \n
\n

\n
\n\n\n\n# Overview\n\nHere we demonstrate how gravitational wave data from a set of observations might constrain nuclear parameters. These results were generated as follows:\n\n1. A unified equation of state (EoS) was defined in terms of $N_p = 18$ parameters $\\vect{p}$ as follows:\n * An outer crust is fixed by tabulated data. (No parameters.)\n * A compressible liquid drop model (CLDM) modeling spherical nuclei embedded in a gas of neutrons and electrons. (2 parameters)\n * A homogeneous interior with a homogeneous nuclear equation of state $\\mathcal{E}(n_n, n_p)$ in conjunction with $\\beta$-equilibrium. (13 parameters = 4 neutron matter parameters + 3 proton polaron parameters + 6 symmetric nuclear matter parameters)\n * A core characterized by the speed of sound (3 parameters).\n2. The Tolman-Oppenheimer-Volkoff (TOV) equations were solved for non-rotating neutron stars, giving the neutron star masses $M(P_c, \\vect{p})$, radii $R(P_c, \\vect{p})$, second Love number $k_2(P_c, \\vect{p})$ as functions of the central pressure $P_c$ and the 18 parameters $\\vect{p}$.\n3. Numerical derivatives of these functions were obtained using Richardson extrapolation. These are tabulated for a set of $N_m$ masses spanning a range of neutron stars. These derivatives are stored in dimensionless form:\n\n $$\n \\frac{p_i}{M_j} \\pdiff{M_j}{p_i} = p_j \\pdiff \\ln M_j.\n $$\n \n4. Using a post-Newtonian analysis, these derivatives are used to obtain a set of Fisher information matrices $\\mat{F}$ corresponding to the expected aLIGO signal sensitivity for all pairs of masses $m_1$ and $m_2$. This is summarized in a $N_m\\times N_m\\times N_p\\times N_p$ array where each entry $F[i, j,:,:]$ corresponds to the expected Fisher information matrix (FIM) obtained from the inspiral of a binary with masses $m_i$ and $m_j$ at a fiducial distance of $D_0=40$Mpc. For an event at distance $D$, this must be weighted by a factor $(D_0/D)^2$.\n5. From this set of FIM, a collective FIM can be obtained by summing over a sample population of binaries, weighed appropriately.\n6. Nuclear uncertainties can be input directly with an information matrix:\n\n $$\n \\mat{F}_{\\text{nuclear}} = \\mat{C}^{-1} \n \\approx \\diag\\left(\\frac{1}{\\sigma_{0}^{2}}, \\frac{1}{\\sigma_{1}^2}, \\cdots\\right)\n $$\n \n where $\\sigma_i$ are the estimated 1-$\\sigma$ relative Gaussian errors for the $i$th parameter $p_i$. If parameter covariances are known, they can be introduced directly into the covariance matrix $\\mat{C}$. *(All of this analysis assumes that errors are small enough and Gaussian so that linear error analysis is a reasonable approximation. As above, the tabulated FIM is scaled by the parameter values to be dimensionless, so the errors $\\sigma_i$ represent the relative errors in parameter.)*\n7. From this combined FIM, we perform various analyses such as a principal component analysis, looking at the largest eigenvalues and eigenvectors of $\\mat{F}$, or computing the parameter covariance matrix $\\mat{C} = \\mat{F}^{-1}$.\n\nThe summary of this analysis for a sample equation of state roughly matching th$ ALF4 equation of state is presented in the following notebook:\n\n* [`ALF4.ipynb`](ALF4.ipynb)\n\n*(As additional equations of state are added, they will be analyzed in appropriately named notebooks.)*\n\n# Equation of State\n\n## Outer Crust\n\nThe outer crust is simply tabulated from results like those of Negele and Vautherin. There are no parameters introduced here.\n\n## CLDM\n\nOnce the nuclear equation of state $\\mathcal{E}(n_n, n_p)$ is specified (see below), we make a unified transition from the outer crust to homogeneous matter using a compressible liquid drop model with the following components:\n\n* A spherical nucleus in a spherical Wigner-Seitz cell. (Energy density $\\mathcal{E}(n_n^(i), n_p^(i))$ where $n_{n,p}^{i}$ are the average densities of the protons and neutrons inside the drop.)\n* A surrounding neutron gas. (Described by $\\mathcal{E}(n_n^{o}, 0)$ where $n_n^{o}$ is the density of the neutron gas.)\n* A homogeneous electron cloud. (Described as a free Fermi gas, relativistic if needed, maintaining beta-equilibrium by establishing zero total charge.)\n* A surface term.\n\nThe only parameters that enter this approximation are those describing the surface of the drop. For this we use the approach of [Lattimer:1985] (also in [Steiner:2012a]) which is characterized in terms of the proton fraction $x = n_p/n_b$ and the isospin asymmetry $\\beta = (n_n - n_p)/(n_n + n_p)$:\n\n$$\n \\sigma = \\sigma_0\\mathcal{B}(x), \\qquad\n \\mathcal{B}(x) = \\frac{16+b}{x^{-3} + b + \\frac{1}{(1-x)^3}}, \\qquad\n C_{\\mathrm{sym}} = \\frac{\\sigma_{\\delta}}{\\sigma_0} = \\frac{96}{b+16}.\n$$\n\nThis introduces two parameters `sigma_delta`$=\\sigma_\\delta$ and `sigma_0`$=\\sigma_0$. Note that for small asymmetries $x\\approx 1$, $\\beta \\approx 0$, we have:\n\n$$\n \\sigma = \\sigma_0\\left(\n 1 -\n \\frac{C_{\\mathrm{sym}}}\n {C_{\\mathrm{sym}} - \\frac{12}{2 - \\frac{1}{(1+\\beta)^3} - \\frac{1}{(1-\\beta)^3}}}\n \\right)\n \\approx\n \\sigma_0\\left(\n 1 - C_{\\mathrm{sym}}\\beta^2 + \\order(\\beta^4)\n \\right)\n$$\n\nThus, we see that there are two independent parameters in this expression. We fix the parameter $\\sigma_0$ so that the CLDM matches the baryon density $n_B$ and energy-density $\\mathcal{E}(n_B)$ at the upper end of the tabulated set of outer-crust data, ensuring a smooth transition (at most, second-order).\n\nFollowing [Steiner:2012a], we introduce one more parameter `C_C`$=\\mathcal{C}$ which is a suppression factor in the Coulomb energy intended to model the diffuseness of the proton distribution. Finally, one could in principle vary the dimension `d_C`$=d$ of the Wigner-Seitz cell to allow for a crude estimate of pasta. We have tried this in some cases, but generally leave $d=3$.\n\nOnce these parameters are fixed, and $\\sigma_0$ is found, we must find the transition from a droplet to homogeneous matter by finding the point where the chemical potentials and pressures are equal. This ensures that the transition from the CLDM to homogeneous matter remains convex. To summarize, we have the following parameters:\n\n**CLDM**\n* `C_C`: Coulomb suppression factor $\\mathcal{C}$.\n* `d_C`: Dimension $d$ of the cells. (Generally held fixed at $d=3$.)\n* `sigma_delta`: Surface tension isospin dependence $\\sigma_\\delta$ [MeV/fm$^2$].\n\n[Lattimer:1985]: http://dx.doi.org/10.1016/0375-9474(85)90006-5 (J.M. Lattimer, C.J. Pethick, D.G. Ravenhall, and D.Q. Lamb, \"Physical properties of hot, dense matter: The general case\", Nucl. Phys. A 432(3), 646 - 742 (1985) )\n\n[Steiner:2012a]: http://dx.doi.org/10.1103/PhysRevC.85.055804 (Andrew W. Steiner, \"Deep crustal heating in a multicomponent accreted neutron star crust\", Phys. Rev. C 85, 055804 (2012) )\n\n## Homogeneous Matter\n\nAs motivated by our work with fitting a nuclear energy density functional (NEDF) called SeaLL1:\n\n* [Bulgac, Forbes, Jin, Perez, and Schunck: A Minimal Nuclear Energy Density Functional (accepted for PRC)](https://arxiv.org/abs/1708.08771)\n\nwe acknowledge that the connection between neutron matter and symmetric nuclear matter might be quite weak. We thus base our parameterization of homogeneous matter on an expansion in proton fraction starting from pure neutron matter. For pure neutron matter, we use the following energy per particle $E_n$ [MeV] as a function of neutron density $n_n$ [1/fm$^3$]:\n \n$$\n E_n(n_n) = \\frac{\\mathcal{E}_{n}(n_n)}{n_n} \n = m_nc^2 + a\\left(\\frac{n_n}{\\bar{n}_0}\\right)^{\\alpha} + b\\left(\\frac{n_n}{\\bar{n}_0}\\right)^{\\beta}\n$$\n \nwhere $m_n=939.565$MeV/$c^2$ is the neutron mass, $\\bar{n}_0 = 0.16$/fm$^3$ is a constant (approximately the nucleon saturation density) and $a$, $b$, $\\alpha$, and $\\beta$ are four EoS parameters `a`, `alpha`, `b`, and `beta` in the code.\n\nAdding a small proton fraction, we extend this using the following form:\n \n\\begin{align}\n \\text{energy-per-particle}&& E_{np}(n_n, n_p) &= (1-x_p)E_n(n_n) + x_p\\left(m_pc^2 + \\Sigma^p(n_B)\\right) \n + \\frac{(2\\pi^2)^{2/3}}{2m^*}x_p^{5/3}n_B^{2/3} +x_p^2f_2(n_B) + x_p^3f_3(n_B)+\\cdots\\\\\n &&n_B &= n_n + n_p, \\qquad x_p = \\frac{n_p}{n_B},&&\\\\\n \\text{proton self-energy}&&\\Sigma^p(n_B) &= \\mu_p\\frac{n_B}{\\bar{n}_0}\\frac{2u_p-\\frac{n_B}{n_0}}{2u_p - 1}&&\n\\end{align}\n \nwhere $m_p = 938.272$MeV/$c^2$ is the bare proton mass, and $m^*$ is the effective proton mass. The properties of the proton polaron are characterized by the parameters $\\mu_p$ [MeV], the proton chemical potential at $n_B = \\bar{n}_0$ and $u_p$ which specifies at which $n_B = u_p\\bar{n}_0$ the proton self-energy $\\Sigma^p(n_B)$ reaches its minimum value as shown below:\n\n\n```python\n%pylab inline --no-import-all\nimport constants as u\nn_0 = 0.16/u.fm**3\nmu_p = -104.5*u.MeV\nu_p = 3.136\nn_B = np.linspace(0, (u_p+1)*n_0)\nSigma_p = mu_p*n_B/n_0*(2*u_p - n_B/n_0)/(2*u_p-1)\nplt.figure(figsize=(8,5))\nplt.plot(n_B, Sigma_p)\nplt.grid(True)\nplt.xticks([0, n_0, u_p*n_0], ['0', r'$\\bar{n}_0$', r'$u_p\\bar{n}_0$'])\nplt.yticks([0, mu_p], ['0', r'$\\mu_p$'])\nplt.xlabel(r'$n_B$')\nplt.ylabel(r'$\\Sigma^p(n_B)$')\nplt.title(\"Demonstration of the parametrization of $\\Sigma^p(n_B)$\")\n```\n\nThe expansion above depends on the functions $f_2(n_B)$, $f_3(n_B)$ etc. which we fix by matching the energy-per-particle of symmetric nuclear matter:\n\n$$\n E_{np}(n_n, n_p) = \\varepsilon_0 + \\frac{K_0}{2}(\\delta\\rho)^2 \n + \\left((S_2 + L_2(\\delta\\rho) + \\frac{K_2}{2}(\\delta\\rho)^2\\right)\\delta^2\\\\\n \\delta = \\frac{n_n-n_p}{n_B}, \\qquad\n \\delta\\rho = \\frac{n_B - n_0}{3n_0}.\n$$\n\nThis introduces the following nuclear parameters: the saturation density $n_0$ [$1/$fm$^{3}$], the saturation energy-per-particle $\\varepsilon_0$ [MeV], the symmetric incompressibility $K_0$ [MeV], and the following symmetry parameters at second order in the iso-spin asymmetry $\\delta$: the symmetry energy $S_2$ [MeV], its slope $L_2$ [MeV] and its incompressibility $K_2$ [MeV]. Demanding that $E_{np}(n_n, n_p)$ match this expression order-by-order in the powers of $x_p$ up to order $x_p^5$ fixes the functions $f_2(n_B)$ through $f_5(n_B)$, completing the definition of the homogeneous equation of state. To summarize, we have the following parameters:\n\n**Nuclear Matter near Saturation**\n* `n_0`: Saturation density $n_0$ [$1/$fm$^3$].\n* `e_0`: Saturation energy density $\\varepsilon_0$ [MeV].\n* `K_0`: Symmetric incompressibility $K_0$ [MeV].\n* `S_2`: Second-order symmetry energy $S_2$ [MeV].\n* `L_2`: Second-order slope of the symmetry energy $L_2$ [MeV].\n* `K_2`: Second-order incompressibility $K_2$ [MeV].\n\n**Pure Neutron Matter**\n* `a`: Coefficient $a$ [MeV] of the low-density polytrope.\n* `alpha`: Power $\\alpha$ of the low-density polytrope.\n* `b`: Coefficient $b$ [MeV] of the high-density polytrope.\n* `beta`: Power $\\beta$ of the high-density polytrope.\n\n**Proton Polaron**\n* `mu_p0`: Proton chemical potential at the saturation density $\\mu_p(\\bar{n}_0)$ [MeV].\n* `u_p`: Location $u_p\\bar{n}_0$ of the minimum of the polaron dispersion.\n* `m_eff_m_p`: Effective mass `m_p^*/m_p` of the proton in the polaron dispersion.\n\nFrom these and the energy-density of a free lepton gas, we compute the equation of state by enforcing $\\beta$-equilibrium through the condition of bulk charge neutrality and chemical equilibrium.\n\n## Core\n\nFinally, we require a parametrization of the inner core, which we characterize by the behaviour of the square of the speed-of-sound $C = c_s^2/c^2$. We parametrize this as a polynomial starting at an energy density $\\mathcal{E}_c$ up to a transition energy-density $\\mathcal{E}_t$ as a function of the energy density $\\mathcal{E} = n_BE_{np}(n_B)$. Above $\\mathcal{E}_t$ we simply adopt the asymptotic form $C_0 = 1/3$ predicted by quark matter.\n\nIn our code we specify that the polynomial form for $\\mathcal{E}_c \\leq \\mathcal{E}\\leq \\mathcal{E}_t$ satisfy:\n\n1. $C(\\mathcal{E})$ is quadratic.\n2. $C(\\mathcal{E}_c) = C_c$ where $C_c$ is determined from the homogeneous equation of state.\n3. $C(\\mathcal{E}_\\max) = C_\\max$ is the maximum of the polynomial. The two parameters $\\mathcal{E}_\\max$ and $C_\\max$ are free.\n\nThese uniquely fix the equation of state of the core in terms of the following parameters:\n\n**Core**\n* `E_c`: Transition energy-density $\\mathcal{E}_c$ [MeV/fm$^3$] at which we transition from the homogeneous equation of state to the core.\n* `C_max`: Maximum value $C_\\max$.\n* `E_max`: Energy-density $\\mathcal{E}_\\max$ [MeV/fm$^3$] at which the polynomial obtains its maximum value.\n", "meta": {"hexsha": "29de19b34fcdfca231045504e02f188912e18fb2", "size": 37207, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Equation of State.ipynb", "max_stars_repo_name": "mforbes/binder_tov_explorer", "max_stars_repo_head_hexsha": "70f24221c11e7ce7fec01062865a5423d9267190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Equation of State.ipynb", "max_issues_repo_name": "mforbes/binder_tov_explorer", "max_issues_repo_head_hexsha": "70f24221c11e7ce7fec01062865a5423d9267190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Equation of State.ipynb", "max_forks_repo_name": "mforbes/binder_tov_explorer", "max_forks_repo_head_hexsha": "70f24221c11e7ce7fec01062865a5423d9267190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 88.1682464455, "max_line_length": 17434, "alphanum_fraction": 0.7651517188, "converted": true, "num_tokens": 3930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.30753280861137916}} {"text": "```python\n%matplotlib inline\n```\n\n\n분산 데이터 병렬 처리와 병렬 처리 파이프라인을 사용한 트랜스포머 모델 학습\n=======================================================================\n\n**Author**: `Pritam Damania `_\n **번역**: `백선희 `_\n\n이 튜토리얼은 `분산 데이터 병렬처리(Distributed Data Parallel) `__ 와\n`병렬 처리 파이프라인 `__\n를 사용하여 여러 GPU에 걸친 거대한 트랜스포머(Transformer) 모델을 어떻게 학습시키는지 보여줍니다.\n이번 튜토리얼은 `nn.Transformer 와 TorchText 로 시퀀스-투-시퀀스(Sequence-to-Sequence) 모델링하기 `__ 의\n확장판이며 분산 데이터 병렬 처리와 병렬 처리 파이프라인이 어떻게 트랜스포머 모델 학습에 쓰이는지 보여주기 위해 이전 튜토리얼에서의\n모델 규모를 증가시켰습니다.\n\n선수과목(Prerequisites):\n\n * `Pipeline Parallelism `__\n * `nn.Transformer 와 TorchText 로 시퀀스-투-시퀀스(Sequence-to-Sequence) 모델링하기 `__\n * `분산 데이터 병렬 처리 시작하기 `__\n\n\n모델 정의하기\n-------------\n\n\n\n\n``PositionalEncoding`` 모듈은 시퀀스에서 토큰의 상대적, 절대적 위치에 대한\n몇몇 정보를 주입합니다.\n위치 인코딩은 임베딩과 같은 차원을 가지므로\n둘을 합칠 수 있습니다. 여기서, 주파수가 다른 ``sine`` 과 ``cosine`` 함수를\n사용합니다.\n\n\n\n\n```python\nimport sys\nimport os\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport tempfile\nfrom torch.nn import TransformerEncoder, TransformerEncoderLayer\n\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\n이번 튜토리얼에서는, 트랜스포머 모델을 두 개의 GPU에 걸쳐서 나누고\n병렬 처리 파이프라인으로 학습시켜 보겠습니다. 추가로,\n`분산 데이터 병렬 처리 `__\n를 사용하여 이 파이프라인의 두 복제를 훈련시킵니다. 한 프로세스는\nGPUs 0, 1에 거쳐 파이프를 구동하고 다른 프로세스는 GPUs 2, 3에서 파이프를 구동합니다. 그 다음, 이 두\n프로세스는 분산 데이터 병렬처리로 두 복제본(replica)을 학습시킵니다.\n모델은 바로 `nn.Transformer 와 TorchText 로 시퀀스-투-시퀀스(Sequence-to-Sequence) 모델링하기\n`__ 튜토리얼과\n똑같은 모델이지만 두 단계로 나뉩니다. 대부분 파라미터(parameter)들은\n`nn.TransformerEncoder `__ 계층(layer)에 포함됩니다.\n`nn.TransformerEncoder `__ 는\n`nn.TransformerEncoderLayer `__ 의 ``nlayers`` 로 구성되어 있습니다.\n결과적으로, 이 튜토리얼에서는 ``nn.TransformerEncoder`` 에 중점을 두고 있으며\n``nn.TransformerEncoderLayer`` 의 절반은 한 GPU에 두고\n나머지 절반은 다른 GPU에 있도록 모델을 분할합니다. 이를 위해서 ``Encoder`` 와\n``Decoder`` 섹션을 분리된 모듈로 빼낸 다음, 원본 트랜스포머 모듈을\n나타내는 nn.Sequential을 빌드 합니다.\n\n\n\n\n```python\nif sys.platform == 'win32':\n print('Windows platform is not supported for pipeline parallelism')\n sys.exit(0)\nif torch.cuda.device_count() < 4:\n print('Need at least four GPU devices for this tutorial')\n sys.exit(0)\n\nclass Encoder(nn.Module):\n def __init__(self, ntoken, ninp, dropout=0.5):\n super(Encoder, self).__init__()\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n # Need (S, N) format for encoder.\n src = src.t()\n src = self.encoder(src) * math.sqrt(self.ninp)\n return self.pos_encoder(src)\n\nclass Decoder(nn.Module):\n def __init__(self, ntoken, ninp):\n super(Decoder, self).__init__()\n self.decoder = nn.Linear(ninp, ntoken)\n self.init_weights()\n\n def init_weights(self):\n initrange = 0.1\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, inp):\n # Need batch dimension first for output of pipeline.\n return self.decoder(inp).permute(1, 0, 2)\n```\n\n학습을 위한 다중 프로세스 시작\n------------------------------\n\n\n\n\n각각 두 개의 GPU에서 자체 파이프라인을 구동하는 두 개의 프로세스를 시작합니다.\n``run_worker`` 는 각 프로세스에 실행됩니다.\n\n\n\n\n```python\ndef run_worker(rank, world_size):\n```\n\n데이터 로드하고 배치 만들기\n---------------------------\n\n\n\n\n학습 프로세스는 ``torchtext`` 의 Wikitext-2 데이터셋을 사용합니다.\ntorchtext 데이터셋에 접근하기 전에, https://github.com/pytorch/data 을 참고하여 torchdata를\n설치하시기 바랍니다.\n단어 오브젝트는 훈련 데이터셋으로 만들어지고, 토큰을 텐서(tensor)로 수치화하는데 사용됩니다.\n시퀀스 데이터로부터 시작하여, ``batchify()`` 함수는 데이터셋을 열(column)들로 정리하고,\n``batch_size`` 사이즈의 배치들로 나눈 후에 남은 모든 토큰을 버립니다.\n예를 들어, 알파벳을 시퀀스(총 길이 26)로 생각하고 배치 사이즈를 4라고 한다면,\n알파벳을 길이가 6인 4개의 시퀀스로 나눌 수 있습니다:\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\n이 열들은 모델에 의해서 독립적으로 취급되며, 이는\n``G`` 와 ``F`` 의 의존성이 학습될 수 없다는 것을 의미하지만, 더 효율적인\n배치 프로세싱(batch processing)을 허용합니다.\n\n\n\n\n\n```python\n# In 'run_worker'\n def print_with_rank(msg):\n print('[RANK {}]: {}'.format(rank, msg))\n\n from torchtext.datasets import WikiText2\n from torchtext.data.utils import get_tokenizer\n from torchtext.vocab import build_vocab_from_iterator\n\n train_iter = WikiText2(split='train')\n tokenizer = get_tokenizer('basic_english')\n vocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=[\"\"])\n vocab.set_default_index(vocab[\"\"])\n\n def data_process(raw_text_iter):\n data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter]\n return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))\n\n train_iter, val_iter, test_iter = WikiText2()\n train_data = data_process(train_iter)\n val_data = data_process(val_iter)\n test_data = data_process(test_iter)\n\n device = torch.device(2 * rank)\n\n def batchify(data, bsz, rank, world_size, is_train=False):\n # Divide the dataset into bsz parts.\n nbatch = data.size(0) // bsz\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * bsz)\n # Evenly divide the data across the bsz batches.\n data = data.view(bsz, -1).t().contiguous()\n # Divide the data across the ranks only for training data.\n if is_train:\n data_per_rank = data.size(0) // world_size\n data = data[rank * data_per_rank : (rank + 1) * data_per_rank]\n return data.to(device)\n\n batch_size = 20\n eval_batch_size = 10\n train_data = batchify(train_data, batch_size, rank, world_size, True)\n val_data = batchify(val_data, eval_batch_size, rank, world_size)\n test_data = batchify(test_data, eval_batch_size, rank, world_size)\n```\n\n입력과 타겟 시퀀스를 생성하기 위한 함수들\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\n\n``get_batch()`` 함수는 트랜스포머 모델을 위한 입력과 타겟 시퀀스를\n생성합니다. 이 함수는 소스 데이터를 ``bptt`` 길이를 가진 덩어리로 세분화합니다.\n언어 모델링 과제를 위해서, 모델은\n다음 단어인 ``Target`` 이 필요합니다. 예를 들어 ``bptt`` 의 값이 2라면,\n``i`` = 0 일 때 다음의 2 개 변수(Variable)를 얻을 수 있습니다:\n\n\n\n\n청크가 차원 0에 속하며\n트랜스포머 모델의 ``S`` 차원과 일치한다는 것을 유의해야 합니다.\n배치 차원 ``N`` 은 1 차원에 해당합니다.\n\n\n\n\n\n```python\n# In 'run_worker'\n bptt = 35\n def get_batch(source, i):\n seq_len = min(bptt, len(source) - 1 - i)\n data = source[i:i+seq_len]\n target = source[i+1:i+1+seq_len].view(-1)\n # Need batch dimension first for pipeline parallelism.\n return data.t(), target\n```\n\n모델 규모와 파이프 초기화\n-------------------------\n\n\n\n\n병렬 처리 파이프라인을 활용한 대형 트랜스포머 모델 학습을 보이기 위해,\n트랜스포머 계층 규모를 적절히 확장시킵니다.\n4096차원의 임베딩 벡터, 4096의 은닉 사이즈, 16개의 어텐션 헤드(attention head)와 총 8 개의\n트랜스포머 계층 (``nn.TransformerEncoderLayer``)를 사용합니다. 이는 최대\n**~1 억** 개의 파라미터를 갖는 모델을 생성합니다.\n\n`RPC 프레임워크 `__ 를 초기화해야 합니다.\nPipe가 향후 호스트 파이프라인을 교차 확장할 수 있도록 하는 `RRef `__ 를 통해\nRPC 프레임워크에 의존하기 때문입니다.\n이때 RPC 프레임워크는 오직 하나의 하나의 worker로 초기화를 해야 하는데,\n여러 GPU를 다루기 위해 프로세스 하나만 사용하고 있기 때문입니다.\n\n그런 다음 파이프라인은 한 GPU에 8개의 트랜스포머와\n다른 GPU에 8개의 트랜스포머 계층으로 초기화됩니다. 한 파이프는 GPU 0, 1에 거쳐 설정되고\n다른 하나는 GPU 2, 3에 설정됩니다. 그런 다음 DistributedDataParallel을 사용하여 두 파이프가 모두 복제됩니다.\n\n\n\n\n```python\n# In 'run_worker'\n ntokens = len(vocab) # the size of vocabulary\n emsize = 4096 # embedding dimension\n nhid = 4096 # the dimension of the feedforward network model in nn.TransformerEncoder\n nlayers = 8 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder\n nhead = 16 # the number of heads in the multiheadattention models\n dropout = 0.2 # the dropout value\n\n from torch.distributed import rpc\n tmpfile = tempfile.NamedTemporaryFile()\n rpc.init_rpc(\n name=\"worker\",\n rank=0,\n world_size=1,\n rpc_backend_options=rpc.TensorPipeRpcBackendOptions(\n init_method=\"file://{}\".format(tmpfile.name),\n # Specifying _transports and _channels is a workaround and we no longer\n # will have to specify _transports and _channels for PyTorch\n # versions >= 1.8.1\n _transports=[\"ibv\", \"uv\"],\n _channels=[\"cuda_ipc\", \"cuda_basic\"],\n )\n )\n\n # Num gpus for model parallelism.\n num_gpus = 2\n partition_len = ((nlayers - 1) // num_gpus) + 1\n\n # Add encoder in the beginning.\n tmp_list = [Encoder(ntokens, emsize, dropout).cuda(2 * rank)]\n module_list = []\n\n # Add all the necessary transformer blocks.\n for i in range(nlayers):\n transformer_block = TransformerEncoderLayer(emsize, nhead, nhid, dropout)\n if i != 0 and i % (partition_len) == 0:\n module_list.append(nn.Sequential(*tmp_list))\n tmp_list = []\n device = i // (partition_len)\n tmp_list.append(transformer_block.to(2 * rank + device))\n\n # Add decoder in the end.\n tmp_list.append(Decoder(ntokens, emsize).cuda(2 * rank + num_gpus - 1))\n module_list.append(nn.Sequential(*tmp_list))\n\n # Need to use 'checkpoint=never' since as of PyTorch 1.8, Pipe checkpointing\n # doesn't work with DDP.\n from torch.distributed.pipeline.sync import Pipe\n chunks = 8\n model = Pipe(torch.nn.Sequential(\n *module_list), chunks = chunks, checkpoint=\"never\")\n\n # Initialize process group and wrap model in DDP.\n from torch.nn.parallel import DistributedDataParallel\n import torch.distributed as dist\n os.environ['MASTER_ADDR'] = 'localhost'\n os.environ['MASTER_PORT'] = '29500'\n dist.init_process_group(\n backend=\"nccl\", rank=rank, world_size=world_size)\n model = DistributedDataParallel(model)\n\n def get_total_params(module: torch.nn.Module):\n total_params = 0\n for param in module.parameters():\n total_params += param.numel()\n return total_params\n\n print_with_rank('Total parameters in model: {:,}'.format(get_total_params(model)))\n```\n\n모델 실행하기\n-------------\n\n\n\n\n손실(loss)을 추적하기 위해 `CrossEntropyLoss `__ 가\n적용되며, 옵티마이저(optimizer)로서 `SGD `__\n는 확률적 경사하강법(stochastic gradient descent method)을 구현합니다. 초기\n학습률(learning rate)은 5.0로 설정됩니다. `StepLR `__ 는\n에폭(epoch)에 따라서 학습률을 조절하는 데 사용됩니다. 학습하는 동안,\n기울기 폭발(gradient exploding)을 방지하기 위해 모든 기울기를 함께 조정(scale)하는 함수\n`nn.utils.clip_grad_norm\\_ `__\n을 이용합니다.\n\n\n\n\n\n```python\n# In 'run_worker'\n criterion = nn.CrossEntropyLoss()\n lr = 5.0 # learning rate\n optimizer = torch.optim.SGD(model.parameters(), lr=lr)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n\n import time\n def train():\n model.train() # Turn on the train mode\n total_loss = 0.\n start_time = time.time()\n ntokens = len(vocab)\n\n # Train only for 50 batches to keep script execution time low.\n nbatches = min(50 * bptt, train_data.size(0) - 1)\n\n for batch, i in enumerate(range(0, nbatches, bptt)):\n data, targets = get_batch(train_data, i)\n optimizer.zero_grad()\n # Since the Pipe is only within a single host and process the ``RRef``\n # returned by forward method is local to this node and can simply\n # retrieved via ``RRef.local_value()``.\n output = model(data).local_value()\n # Need to move targets to the device where the output of the\n # pipeline resides.\n loss = criterion(output.view(-1, ntokens), targets.cuda(2 * rank + 1))\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n total_loss += loss.item()\n log_interval = 10\n if batch % log_interval == 0 and batch > 0:\n cur_loss = total_loss / log_interval\n elapsed = time.time() - start_time\n print_with_rank('| epoch {:3d} | {:5d}/{:5d} batches | '\n 'lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f}'.format(\n epoch, batch, nbatches // bptt, scheduler.get_last_lr()[0],\n elapsed * 1000 / log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\n def evaluate(eval_model, data_source):\n eval_model.eval() # Turn on the evaluation mode\n total_loss = 0.\n ntokens = len(vocab)\n # Evaluate only for 50 batches to keep script execution time low.\n nbatches = min(50 * bptt, data_source.size(0) - 1)\n with torch.no_grad():\n for i in range(0, nbatches, bptt):\n data, targets = get_batch(data_source, i)\n output = eval_model(data).local_value()\n output_flat = output.view(-1, ntokens)\n # Need to move targets to the device where the output of the\n # pipeline resides.\n total_loss += len(data) * criterion(output_flat, targets.cuda(2 * rank + 1)).item()\n return total_loss / (len(data_source) - 1)\n```\n\n에폭을 반복합니다. 만약 검증 오차(validation loss)가 지금까지 관찰한 것 중 최적이라면\n모델을 저장합니다. 각 에폭 이후에 학습률을 조절합니다.\n\n\n\n\n```python\n# In 'run_worker'\n best_val_loss = float(\"inf\")\n epochs = 3 # The number of epochs\n best_model = None\n\n for epoch in range(1, epochs + 1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(model, val_data)\n print_with_rank('-' * 89)\n print_with_rank('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print_with_rank('-' * 89)\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_model = model\n\n scheduler.step()\n```\n\n평가 데이터셋으로 모델 평가하기\n-------------------------------\n\n평가 데이터셋에서의 결과를 확인하기 위해 최고의 모델을 적용합니다.\n\n\n\n\n```python\n# In 'run_worker'\n test_loss = evaluate(best_model, test_data)\n print_with_rank('=' * 89)\n print_with_rank('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\n print_with_rank('=' * 89)\n\n# Main execution\nimport torch.multiprocessing as mp\n\nif __name__==\"__main__\":\n world_size = 2\n mp.spawn(run_worker, args=(world_size, ), nprocs=world_size, join=True)\n```\n\nOutput\n------\n\n\n\n\n.. code-block:: py\n\n [RANK 0]: | epoch 1 | 10/ 50 batches | lr 5.00 | ms/batch 778.97 | loss 43.31 | ppl 6432469059895903232.00\n [RANK 1]: | epoch 1 | 10/ 50 batches | lr 5.00 | ms/batch 778.90 | loss 44.50 | ppl 21245447128217366528.00\n [RANK 0]: | epoch 1 | 20/ 50 batches | lr 5.00 | ms/batch 699.89 | loss 44.50 | ppl 21176949187407757312.00\n [RANK 1]: | epoch 1 | 20/ 50 batches | lr 5.00 | ms/batch 699.87 | loss 44.62 | ppl 23975861229620961280.00\n [RANK 0]: | epoch 1 | 30/ 50 batches | lr 5.00 | ms/batch 698.86 | loss 41.62 | ppl 1193312915629888256.00\n [RANK 1]: | epoch 1 | 30/ 50 batches | lr 5.00 | ms/batch 698.87 | loss 40.69 | ppl 471605759847546240.00\n [RANK 0]: | epoch 1 | 40/ 50 batches | lr 5.00 | ms/batch 698.34 | loss 45.20 | ppl 42812308420836458496.00\n [RANK 1]: | epoch 1 | 40/ 50 batches | lr 5.00 | ms/batch 698.33 | loss 45.68 | ppl 68839569686012223488.00\n [RANK 1]: -----------------------------------------------------------------------------------------\n [RANK 1]: | end of epoch 1 | time: 40.08s | valid loss 0.80 | valid ppl 2.22\n [RANK 1]: -----------------------------------------------------------------------------------------\n [RANK 0]: -----------------------------------------------------------------------------------------\n [RANK 0]: | end of epoch 1 | time: 40.09s | valid loss 0.80 | valid ppl 2.22\n [RANK 0]: -----------------------------------------------------------------------------------------\n [RANK 0]: | epoch 2 | 10/ 50 batches | lr 4.75 | ms/batch 768.51 | loss 36.34 | ppl 6063529544668166.00\n [RANK 1]: | epoch 2 | 10/ 50 batches | lr 4.75 | ms/batch 769.23 | loss 37.41 | ppl 17651211266236086.00\n [RANK 0]: | epoch 2 | 20/ 50 batches | lr 4.75 | ms/batch 699.57 | loss 28.97 | ppl 3798441739584.11\n [RANK 1]: | epoch 2 | 20/ 50 batches | lr 4.75 | ms/batch 699.56 | loss 29.28 | ppl 5203636967575.47\n [RANK 0]: | epoch 2 | 30/ 50 batches | lr 4.75 | ms/batch 699.04 | loss 28.43 | ppl 2212498693571.25\n [RANK 1]: | epoch 2 | 30/ 50 batches | lr 4.75 | ms/batch 699.05 | loss 28.33 | ppl 2015144761281.48\n [RANK 0]: | epoch 2 | 40/ 50 batches | lr 4.75 | ms/batch 699.10 | loss 23.30 | ppl 13121380184.92\n [RANK 1]: | epoch 2 | 40/ 50 batches | lr 4.75 | ms/batch 699.09 | loss 23.41 | ppl 14653799192.87\n [RANK 0]: -----------------------------------------------------------------------------------------\n [RANK 0]: | end of epoch 2 | time: 39.97s | valid loss 0.24 | valid ppl 1.27\n [RANK 0]: -----------------------------------------------------------------------------------------\n [RANK 1]: -----------------------------------------------------------------------------------------\n [RANK 1]: | end of epoch 2 | time: 39.98s | valid loss 0.24 | valid ppl 1.27\n [RANK 1]: -----------------------------------------------------------------------------------------\n [RANK 0]: | epoch 3 | 10/ 50 batches | lr 4.51 | ms/batch 769.36 | loss 12.80 | ppl 361681.11\n [RANK 1]: | epoch 3 | 10/ 50 batches | lr 4.51 | ms/batch 768.97 | loss 12.57 | ppl 287876.61\n [RANK 0]: | epoch 3 | 20/ 50 batches | lr 4.51 | ms/batch 698.27 | loss 12.01 | ppl 164364.60\n [RANK 1]: | epoch 3 | 20/ 50 batches | lr 4.51 | ms/batch 698.30 | loss 11.98 | ppl 159095.89\n [RANK 0]: | epoch 3 | 30/ 50 batches | lr 4.51 | ms/batch 697.75 | loss 10.90 | ppl 54261.91\n [RANK 1]: | epoch 3 | 30/ 50 batches | lr 4.51 | ms/batch 697.72 | loss 10.89 | ppl 53372.39\n [RANK 0]: | epoch 3 | 40/ 50 batches | lr 4.51 | ms/batch 699.49 | loss 10.78 | ppl 47948.35\n [RANK 1]: | epoch 3 | 40/ 50 batches | lr 4.51 | ms/batch 699.50 | loss 10.79 | ppl 48664.42\n [RANK 0]: -----------------------------------------------------------------------------------------\n [RANK 0]: | end of epoch 3 | time: 39.96s | valid loss 0.38 | valid ppl 1.46\n [RANK 0]: -----------------------------------------------------------------------------------------\n [RANK 1]: -----------------------------------------------------------------------------------------\n [RANK 1]: | end of epoch 3 | time: 39.96s | valid loss 0.38 | valid ppl 1.46\n [RANK 1]: -----------------------------------------------------------------------------------------\n [RANK 0]: =========================================================================================\n [RANK 0]: | End of training | test loss 0.33 | test ppl 1.39\n [RANK 0]: =========================================================================================\n [RANK 1]: =========================================================================================\n [RANK 1]: | End of training | test loss 0.33 | test ppl 1.39\n [RANK 1]: =========================================================================================\n\n\n\n", "meta": {"hexsha": "98d278388ecbf93b9e1b43e6db98f1e1c3737f8d", "size": 34309, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/e081556e6a716888948cd45335518ed9/ddp_pipeline.ipynb", "max_stars_repo_name": "9bow/PyTorch-Tutorials-KR", "max_stars_repo_head_hexsha": "bfddf43a696545cb0991262faeb653affe1040b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44, "max_stars_repo_stars_event_min_datetime": "2021-12-07T14:51:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:34:17.000Z", "max_issues_repo_path": "docs/_downloads/e081556e6a716888948cd45335518ed9/ddp_pipeline.ipynb", "max_issues_repo_name": "9bow/PyTorch-Tutorials-KR", "max_issues_repo_head_hexsha": "bfddf43a696545cb0991262faeb653affe1040b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 128, "max_issues_repo_issues_event_min_datetime": "2021-12-02T18:11:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T05:16:39.000Z", "max_forks_repo_path": "docs/_downloads/e081556e6a716888948cd45335518ed9/ddp_pipeline.ipynb", "max_forks_repo_name": "9bow/PyTorch-Tutorials-KR", "max_forks_repo_head_hexsha": "bfddf43a696545cb0991262faeb653affe1040b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14, "max_forks_repo_forks_event_min_datetime": "2021-12-02T18:56:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:18:23.000Z", "avg_line_length": 131.4521072797, "max_line_length": 5099, "alphanum_fraction": 0.6135124894, "converted": true, "num_tokens": 7525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.30750848357452826}} {"text": "```python\n%matplotlib inline\n```\n\n\nnn.Transformer 와 TorchText 로 시퀀스-투-시퀀스(Sequence-to-Sequence) 모델링하기\n==========================================================================\n\n이 튜토리얼에서는\n`nn.Transformer `__ 모듈을\n이용하는 시퀀스-투-시퀀스(Sequence-to-Sequence) 모델을 학습하는 방법을 배워보겠습니다.\n\nPyTorch 1.2 버젼에는\n`Attention is All You Need `__ 논문에\n기반한 표준 트랜스포머(transformer) 모듈을 포함하고 있습니다.\n트랜스포머 모델은 더 높은 수준의 병렬화(parallelization)가 가능하면서도\n많은 시퀀스-투-시퀀스 문제들에서 품질이 우수함이 입증되었습니다.\n``nn.Transformer`` 모듈은 입력(input) 과 출력(output) 사이의 전역적인 의존성(global dependencies)\n을 나타내기 위하여 전적으로 어텐션(attention) 메커니즘에 의존합니다.\n(최근에 또 다른 모듈이 `nn.MultiheadAttention `__ 으로 구현되었습니다.)\n``nn.Transformer`` 모듈은 현재 모듈화가 매우 잘 되어 있어,\n다음과 같은 단일 컴포넌트 (이 튜토리얼의 `nn.TransformerEncoder `__ 와 같은)\n는 쉽게 적용 및 구성될 수 있습니다.\n\n\n\n\n\n\n\n모델 정의하기\n----------------\n\n\n\n\n이 튜토리얼에서, 우리는 ``nn.TransformerEncoder`` 모델을 언어 모델링(language modeling) 과제에 대해서 학습시킬 것입니다.\n언어 모델링 과제는 주어진 단어 (또는 단어의 시퀀스) 가 다음에 이어지는 단어 시퀀스를 따를 가능성(likelihood)에 대한 확률을 할당하는 것입니다.\n먼저, 토큰(token) 들의 시퀀스가 임베딩(embedding) 레이어로 전달되며, 이어서 포지셔널 인코딩(positional encoding) 레이어가 각 단어의 순서를 설명합니다.\n(더 자세한 설명은 다음 단락을 참고해주세요.)\n``nn.TransformerEncoder`` 는 여러 개의\n`nn.TransformerEncoderLayer `__\n레이어로 구성되어 있습니다.\n``nn.TransformerEncoder`` 내부의 셀프-어텐션(self-attention) 레이어들은 시퀀스 안에서의 이전 포지션에만 집중하도록 허용되기 때문에,\n입력(input) 순서와 함께, 정사각 형태의 어텐션 마스크(attention mask) 가 필요합니다.\n언어 모델링 과제를 위해서, 미래의 포지션에 있는 모든 토큰들은 마스킹 되어야(가려져야) 합니다.\n실제 단어를 얻기 위해서, ``nn.TransformerEncoder`` 의 출력은 로그-소프트맥스(log-Softmax) 로 이어지는 최종 선형(Linear) 레이어로 전달 됩니다.\n\n\n\n\n\n```python\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass TransformerModel(nn.Module):\n\n def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):\n super(TransformerModel, self).__init__()\n from torch.nn import TransformerEncoder, TransformerEncoderLayer\n self.model_type = 'Transformer'\n self.src_mask = None\n self.pos_encoder = PositionalEncoding(ninp, dropout)\n encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)\n self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)\n self.encoder = nn.Embedding(ntoken, ninp)\n self.ninp = ninp\n self.decoder = nn.Linear(ninp, ntoken)\n\n self.init_weights()\n\n def _generate_square_subsequent_mask(self, sz):\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.zero_()\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def forward(self, src):\n if self.src_mask is None or self.src_mask.size(0) != len(src):\n device = src.device\n mask = self._generate_square_subsequent_mask(len(src)).to(device)\n self.src_mask = mask\n\n src = self.encoder(src) * math.sqrt(self.ninp)\n src = self.pos_encoder(src)\n output = self.transformer_encoder(src, self.src_mask)\n output = self.decoder(output)\n return output\n```\n\n``PositionalEncoding`` 모듈은 시퀀스 안에서 토큰의 상대적인 또는 절대적인 포지션에 대한 어떤 정보를 주입합니다.\n포지셔널 인코딩은 임베딩과 합칠 수 있도록 똑같은 차원을 가집니다.\n여기에서, 우리는 다른 주파수(frequency) 의 ``sine`` 과 ``cosine`` 함수를 사용합니다.\n\n\n\n\n\n```python\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n return self.dropout(x)\n```\n\n데이터 로드하고 배치 만들기\n-------------------\n\n\n\n\n학습 과정에서는 ``torchtext`` 의 Wikitext-2 데이터셋을 이용합니다.\n단어 오브젝트는 훈련 데이터셋(train dataset) 에 의하여 만들어지고, 토큰을 텐서(tensor)로 수치화하는데 사용됩니다.\n시퀀스 데이터로부터 시작하여, ``batchify()`` 함수는 데이터셋을 컬럼들로 배열하고, ``batch_size`` 사이즈의 배치들로 나눈 후에 남은 모든 토큰을 버립니다.\n예를 들어, 알파벳을 시퀀스(총 길이 26) 로 생각하고 배치 사이즈를 4라고 한다면, 우리는 알파벳을 길이가 6인 4개의 시퀀스로 나눌 수 있습니다.\n\n\\begin{align}\\begin{bmatrix}\n \\text{A} & \\text{B} & \\text{C} & \\ldots & \\text{X} & \\text{Y} & \\text{Z}\n \\end{bmatrix}\n \\Rightarrow\n \\begin{bmatrix}\n \\begin{bmatrix}\\text{A} \\\\ \\text{B} \\\\ \\text{C} \\\\ \\text{D} \\\\ \\text{E} \\\\ \\text{F}\\end{bmatrix} &\n \\begin{bmatrix}\\text{G} \\\\ \\text{H} \\\\ \\text{I} \\\\ \\text{J} \\\\ \\text{K} \\\\ \\text{L}\\end{bmatrix} &\n \\begin{bmatrix}\\text{M} \\\\ \\text{N} \\\\ \\text{O} \\\\ \\text{P} \\\\ \\text{Q} \\\\ \\text{R}\\end{bmatrix} &\n \\begin{bmatrix}\\text{S} \\\\ \\text{T} \\\\ \\text{U} \\\\ \\text{V} \\\\ \\text{W} \\\\ \\text{X}\\end{bmatrix}\n \\end{bmatrix}\\end{align}\n\n이 컬럼들은 모델에 의해서 독립적으로 취급되며, 이것은 더 효율적인 배치 프로세싱(batch processing) 이 가능하지만, ``G`` 와 ``F`` 의 의존성이 학습될 수 없다는 것을 의미합니다.\n\n\n\n\n\n```python\nimport torchtext\nfrom torchtext.data.utils import get_tokenizer\nTEXT = torchtext.data.Field(tokenize=get_tokenizer(\"basic_english\"),\n init_token='',\n eos_token='',\n lower=True)\ntrain_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)\nTEXT.build_vocab(train_txt)\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef batchify(data, bsz):\n data = TEXT.numericalize([data.examples[0].text])\n # 데이터셋을 bsz 파트들로 나눕니다.\n nbatch = data.size(0) // bsz\n # 깔끔하게 나누어 떨어지지 않는 추가적인 부분(나머지들) 은 잘라냅니다.\n data = data.narrow(0, 0, nbatch * bsz)\n # 데이터에 대하여 bsz 배치들로 동등하게 나눕니다.\n data = data.view(bsz, -1).t().contiguous()\n return data.to(device)\n\nbatch_size = 20\neval_batch_size = 10\ntrain_data = batchify(train_txt, batch_size)\nval_data = batchify(val_txt, eval_batch_size)\ntest_data = batchify(test_txt, eval_batch_size)\n```\n\n입력(input) 과 타겟(target) 시퀀스를 생성하기 위한 함수들\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\n\n\n``get_batch()`` 함수는 트랜스포머 모델을 위한 입력과 타겟 시퀀스를 생성합니다.\n이 함수는 소스 데이터를 ``bptt`` 길이를 가진 덩어리로 세분화 합니다.\n언어 모델링 과제를 위해서, 모델은 다음 단어인 ``Target`` 이 필요 합니다.\n예를 들어, ``bptt`` 의 값이 2 라면, 우리는 ``i`` = 0 일 때 다음의 2 개의 변수(Variable) 를 얻을 수 있습니다:\n\n\n\n\n변수 덩어리는 트랜스포머 모델의 ``S`` 차원과 일치하는 0 차원에 해당합니다.\n배치 차원 ``N`` 은 1 차원에 해당합니다.\n\n\n\n\n\n```python\nbptt = 35\ndef get_batch(source, i):\n seq_len = min(bptt, len(source) - 1 - i)\n data = source[i:i+seq_len]\n target = source[i+1:i+1+seq_len].view(-1)\n return data, target\n```\n\n인스턴스(instance) 초기화하기\n--------------------\n\n\n\n\n모델은 아래와 같은 하이퍼파라미터(hyperparameter) 로 세팅 됩니다.\n단어 사이즈는 단어 오브젝트의 길이와 일치 합니다.\n\n\n\n\n\n```python\nntokens = len(TEXT.vocab.stoi) # 단어 사전의 크기\nemsize = 200 # 임베딩 차원\nnhid = 200 # nn.TransformerEncoder 에서 피드포워드 네트워크(feedforward network) 모델의 차원\nnlayers = 2 # nn.TransformerEncoder 내부의 nn.TransformerEncoderLayer 개수\nnhead = 2 # 멀티헤드 어텐션(multi-head attention) 모델의 헤드 개수\ndropout = 0.2 # 드랍아웃(dropout) 값\nmodel = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)\n```\n\n모델 실행하기\n-------------\n\n\n\n\n손실(loss) 을 추적하는 데에는\n`CrossEntropyLoss `__\n가 적용되며, 옵티마이저(optimizer) 로서\n`SGD `__\n는 확률적 경사 하강법(stochastic gradient descent method) 을 구현합니다.\n초기 학습률(learning rate) 은 5.0 으로 설정됩니다.\n`StepLR `__\n은 에포크(epoch) 에 따라서 학습률을 조절하는데 사용됩니다.\n학습하는 동안에, 우리는 기울기 폭발(gradient exploding) 을 방지하기 위하여 모든 기울기를 함께 스케일(scale) 하는 함수인\n`nn.utils.clip_grad_norm\\_ `__\n을 이용합니다.\n\n\n\n\n\n```python\ncriterion = nn.CrossEntropyLoss()\nlr = 5.0 # 학습률\noptimizer = torch.optim.SGD(model.parameters(), lr=lr)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n\nimport time\ndef train():\n model.train() # 학습 모드를 시작합니다.\n total_loss = 0.\n start_time = time.time()\n ntokens = len(TEXT.vocab.stoi)\n for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):\n data, targets = get_batch(train_data, i)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output.view(-1, ntokens), targets)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n optimizer.step()\n\n total_loss += loss.item()\n log_interval = 200\n if batch % log_interval == 0 and batch > 0:\n cur_loss = total_loss / log_interval\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | '\n 'lr {:02.2f} | ms/batch {:5.2f} | '\n 'loss {:5.2f} | ppl {:8.2f}'.format(\n epoch, batch, len(train_data) // bptt, scheduler.get_lr()[0],\n elapsed * 1000 / log_interval,\n cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\ndef evaluate(eval_model, data_source):\n eval_model.eval() # 평가 모드를 시작합니다.\n total_loss = 0.\n ntokens = len(TEXT.vocab.stoi)\n with torch.no_grad():\n for i in range(0, data_source.size(0) - 1, bptt):\n data, targets = get_batch(data_source, i)\n output = eval_model(data)\n output_flat = output.view(-1, ntokens)\n total_loss += len(data) * criterion(output_flat, targets).item()\n return total_loss / (len(data_source) - 1)\n```\n\n에포크 내에서 반복됩니다. 만약 검증 오차(validation loss) 가 우리가 지금까지 관찰한 것 중 최적이라면 모델을 저장합니다.\n매 에포크 이후에 학습률을 조절합니다.\n\n\n\n\n```python\nbest_val_loss = float(\"inf\")\nepochs = 3 # 에포크 수\nbest_model = None\n\nfor epoch in range(1, epochs + 1):\n epoch_start_time = time.time()\n train()\n val_loss = evaluate(model, val_data)\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print('-' * 89)\n\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_model = model\n\n scheduler.step()\n```\n\n평가 데이터셋(test dataset) 으로 모델을 평가하기\n-------------------------------------\n\n평가 데이터셋에 대한 결과를 확인하기 위해서 최고의 모델을 적용합니다.\n\n\n\n\n```python\ntest_loss = evaluate(best_model, test_data)\nprint('=' * 89)\nprint('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\nprint('=' * 89)\n```\n", "meta": {"hexsha": "bf784604ba8469a9943e8aa2d56efb2a52a87340", "size": 22416, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "docs/_downloads/9cf2d4ead514e661e20d2070c9bf7324/transformer_tutorial.ipynb", "max_stars_repo_name": "kypark7/PyTorch-tutorials-kr", "max_stars_repo_head_hexsha": "70b45364908f8f411da00b47a65678c64a1cfedf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-18T04:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T00:56:24.000Z", "max_issues_repo_path": "docs/_downloads/9cf2d4ead514e661e20d2070c9bf7324/transformer_tutorial.ipynb", "max_issues_repo_name": "kypark7/PyTorch-tutorials-kr", "max_issues_repo_head_hexsha": "70b45364908f8f411da00b47a65678c64a1cfedf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "docs/_downloads/9cf2d4ead514e661e20d2070c9bf7324/transformer_tutorial.ipynb", "max_forks_repo_name": "kypark7/PyTorch-tutorials-kr", "max_forks_repo_head_hexsha": "70b45364908f8f411da00b47a65678c64a1cfedf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-27T10:47:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T10:47:39.000Z", "avg_line_length": 100.972972973, "max_line_length": 2383, "alphanum_fraction": 0.6539525339, "converted": true, "num_tokens": 4414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.30636709778625404}} {"text": "# Code stuff - not slides!\n\n\n```python\n%run ../ML_plots.ipynb\n```\n\n ERROR:root:File `'../ML_plots.ipynb.py'` not found.\n\n\n# Session 12:\n## Supervised learning, part 1\n\n*Andreas Bjerre-Nielsen*\n\n## Agenda\n1. [Modelling data](#Modelling-data)\n1. [A familiar regression model](#A-familiar-regression-model)\n1. [The curse of overfitting](#The-curse-of-overfitting)\n1. [Important details](#Implementation-details)\n\n## Vaaaamos\n\n\n```python\nimport warnings\nfrom sklearn.exceptions import ConvergenceWarning\nwarnings.filterwarnings(action='ignore', category=ConvergenceWarning)\n\nimport matplotlib.pyplot as plt\nimport numpy as np \nimport pandas as pd \nimport seaborn as sns\n\nplt.style.use('default') # set style (colors, background, size, gridlines etc.)\nplt.rcParams['figure.figsize'] = 10, 4 # set default size of plots\nplt.rcParams.update({'font.size': 18})\n```\n\n## Supervised problems (1)\n*How do we distinguish between problems?*\n\n\n```python\nf_identify_question\n```\n\n## Supervised problems (2)\n*The two canonical problems*\n\n\n```python\nf_identify_answer\n```\n\n## Supervised problems (3)\n*Which models have we seen for classification?*\n\n- .\n\n- .\n\n- .\n\n# Modelling data\n\n## Model complexity (1)\n*What does a model of low complexity look like?*\n\n\n```python\nf_complexity[0]\n```\n\n## Model complexity (2)\n*What does medium model complexity look like?*\n\n\n```python\nf_complexity[1]\n```\n\n## Model complexity (3)\n*What does high model complexity look like?*\n\n\n```python\nf_complexity[2]\n```\n\n## Model fitting (1)\n*Quiz (1 min.): Which model fitted the data best?*\n\n\n```python\nf_bias_var['regression'][2]\n```\n\n## Model fitting (2)\n*What does underfitting and overfitting look like for classification?*\n\n\n```python\nf_bias_var['classification'][2]\n```\n\n## Two agendas (1)\n\nWhat are the objectives of empirical research? \n\n1. *causation*: what is the effect of a particular variable on an outcome? \n2. *prediction*: find some function that provides a good prediction of $y$ as a function of $x$\n\n## Two agendas (2)\n\nHow might we express the agendas in a model?\n\n$$ y = \\alpha + \\beta x + \\varepsilon $$\n\n- *causation*: interested in $\\hat{\\beta}$ \n\n- *prediction*: interested in $\\hat{y}$ \n\n\n## Two agendas (3)\n\nMight these two agendas be related at a deeper level? \n\nCan prediction quality inform us about how to make causal models?\n\n# A familiar regression model\n\n## Estimation (1)\n*Do we know already some ways to estimate regression models?*\n\n- Social scientists know all about the Ordinary Least Squares (OLS).\n - OLS estimate both parameters and their standard deviation.\n - Is best linear unbiased estimator under regularity conditions. \n \n\n*How is OLS estimated?*\n\n- $\\beta=(\\textbf{X}^T\\textbf{X})^{-1}\\textbf{X}^T\\textbf{y}$\n- computation requires non perfect multicollinarity.\n\n## Estimation (2)\n*How might we estimate a linear regression model?*\n\n- first order method (e.g. gradient descent)\n- second order method (e.g. Newton-Raphson)\n\n*So what the hell was gradient descent?*\n\n- compute errors, multiply with features and update\n\n## Estimation (3)\n*Can you explain that in details?*\n\n- Yes, like with Adaline, we minimize the sum of squared errors (SSE): \n\\begin{align}SSE&=\\boldsymbol{e}^{T}\\boldsymbol{e}\\\\\\boldsymbol{e}&=\\textbf{y}-\\textbf{X}\\textbf{w}\\end{align}\n\n\n```python\nX = np.random.normal(size=(3,2))\ny = np.random.normal(size=(3))\nw = np.random.normal(size=(3))\n\ne = y-(w[0]+X.dot(w[1:]))\nSSE = e.T.dot(e)\n```\n\n## Estimation (4)\n*And what about the updating..? What is it something about the first order deritative?*\n\n\\begin{align}\n\\frac{\\partial SSE}{\\partial\\hat{w}}=&\\textbf{X}^T\\textbf{e},\\\\\n \\Delta\\hat{w}=&\\eta\\cdot\\textbf{X}^T\\textbf{e}=\\eta\\cdot\\textbf{X}^T(\\textbf{y}-\\hat{\\textbf{y}})\n\\end{align}\n\n\n```python\neta = 0.001 # learning rate\nfod = X.T.dot(e)\nupdate_vars = eta*fod\nupdate_bias = eta*e.sum()\n```\n\n## Estimation (5)\n*What might some advantages be relative to OLS?*\n\n- Works despite high multicollinarity\n- Speed\n - OLS has $\\mathcal{O}(K^2N)$ computation time ([read more](https://math.stackexchange.com/questions/84495/computational-complexity-of-least-square-regression-operation))\n - Quadratic scaling in number of variables ($K$).\n - Stochastic gradient descent\n - Likely to converge faster with many observations ($N$)\n\n## Fitting a polynomial (1)\nPolyonomial: $f(x) = 2+8*x^4$\n\nTry models of increasing order polynomials. \n\n- Split data into train and test (50/50)\n\n\n- For polynomial order 0 to 9:\n - Iteration n: $y = \\sum_{k=0}^{n}(\\beta_k\\cdot x^k)+\\varepsilon$.\n - Estimate order n model on training data\n - Evaluate with on test data with RMSE: \n - $log RMSE = \\log (\\sqrt{MSE})$ \n\n## Fitting a polynomial (2)\nWe generate samples of data from true model.\n\n\n```python\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\n\ndef true_fct(X):\n return 2+X**4\n\nn_samples = 25\nn_degrees = 15\n\nnp.random.seed(0)\n\nX_train = np.random.normal(size=(n_samples,1))\ny_train = true_fct(X_train).reshape(-1) + np.random.randn(n_samples) \n\nX_test = np.random.normal(size=(n_samples,1))\ny_test = true_fct(X_test).reshape(-1) + np.random.randn(n_samples)\n```\n\n## Fitting a polynomial (3)\nWe estimate the polynomials\n\n\n```python\nfrom sklearn.metrics import mean_squared_error as mse\n\ntest_mse = []\ntrain_mse = []\nparameters = []\ndegrees = range(n_degrees+1)\n\nfor p in degrees:\n X_train_p = PolynomialFeatures(degree=p).fit_transform(X_train)\n X_test_p = PolynomialFeatures(degree=p).fit_transform(X_train)\n reg = LinearRegression().fit(X_train_p, y_train)\n train_mse += [mse(reg.predict(X_train_p),y_train)] \n test_mse += [mse(reg.predict(X_test_p),y_test)] \n parameters.append(reg.coef_)\n```\n\n## Fitting a polynomial (4)\n*So what happens to the model performance in- and out-of-sample?*\n\n\n```python\ndegree_index = pd.Index(degrees,name='Polynomial degree ~ model complexity')\nax = pd.DataFrame({'Train set':train_mse, 'Test set':test_mse})\\\n .set_index(degree_index)\\\n .plot(figsize=(10,4))\nax.set_ylabel('Mean squared error')\n```\n\n## Fitting a polynomial (4)\n*Why does it go wrong?*\n- more spurious parameters\n- the coefficient size increases\n\n## Fitting a polynomial (5)\n*What do you mean coefficient size increase?*\n\n\n```python\norder_idx = pd.Index(range(n_degrees+1),name='Polynomial order')\nax = pd.DataFrame(parameters,index=order_idx)\\\n.abs().mean(1)\\\n.plot(logy=True)\nax.set_ylabel('Mean parameter size')\n```\n\n## Fitting a polynomial (6)\n*How else could we visualize this problem?*\n\n\n```python\nf_bias_var['regression'][2]\n```\n\n# The curse of overfitting\n\n## Looking for a remedy\n*How might we solve the overfitting problem?*\n\nBy reducing\n- the number of variables\n- the coefficient size of variables \n\n## Regularization (1)\n\n*Why do we regularize?*\n\n- To mitigate overfitting > better model predictions\n\n*How do we regularize?*\n\n- We make models which are less complex:\n - reducing the **number** of coefficient;\n - reducing the **size** of the coefficients.\n\n## Regularization (2)\n\n*What does regularization look like?*\n\nWe add a penalty term our optimization procedure:\n \n$$ \\text{arg min}_\\beta \\, \\underset{\\text{MSE}}{\\underbrace{E[(y_0 - \\hat{f}(x_0))^2]}} + \\underset{\\text{penalty}}{\\underbrace{\\lambda \\cdot R(\\beta)}}$$\n\nIntroduction of penalties implies that increased model complexity has to be met with high increases precision of estimates.\n\n## Regularization (3)\n\n*What are some used penalty functions?*\n\nThe two most common penalty functions are L1 and L2 regularization.\n\n- L1 regularization (***Lasso***): $R(\\beta)=\\sum_{j=1}^{p}|\\beta_j|$ \n - Makes coefficients sparse, i.e. selects variables by removing some (if $\\lambda$ is high)\n \n \n- L2 regularization (***Ridge***): $R(\\beta)=\\sum_{j=1}^{p}\\beta_j^2$\n - Reduce coefficient size\n - Fast due to analytical solution\n \n*To note:* The *Elastic Net* uses a combination of L1 and L2 regularization.\n\n## Regularization (4)\n\n*How the Lasso (L1 reg.) deviates from OLS*\n\n\n\n## Regularization (5)\n\n*How the Ridge regression (L2 reg.) deviates from OLS*\n\n\n\n## Regularization (6)\n\n*How might we describe the $\\lambda$ of Lasso and Ridge?*\n\nThese are hyperparameters that we can optimize over. \n\n- More about this tomorrow.\n\n# Implementation details\n\n## The devils in the details (1)\n\n*So we just run regularization?*\n\n# NO\n\nWe need to rescale our features:\n- convert to zero mean: \n- standardize to unit std: \n\nCompute in Python:\n- option 1: `StandardScaler` in `sklearn` \n- option 2: `(X - np.mean(X)) / np.std(X)`\n\n\n\n## The devils in the details (2)\n*So we just scale our test and train?*\n\n# NO\n\nFit to the distribution in the training data first, then rescale train and test! See more [here](https://stats.stackexchange.com/questions/174823/how-to-apply-standardization-normalization-to-train-and-testset-if-prediction-i).\n\n## The devils in the details (3)\n*So we just rescale before using polynomial features?*\n\n# NO\n\nOtherwise the interacted varaibles are not gaussian distributed.\n\n## The devils in the details (4)\n*Does sklearn's `PolynomialFeatures` work for more than variable?*\n\n# YES!\n\n# The end\n[Return to agenda](#Agenda)\n", "meta": {"hexsha": "d085f3b4f8579b757e6f47c3c952c25ef1e33f10", "size": 203689, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "Test_karl/material/session_12/lecture_12.ipynb", "max_stars_repo_name": "karlbindslev/sds_group29", "max_stars_repo_head_hexsha": "6f5263b08b35f35374b7f01b31a0e90d1cf4d53e", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test_karl/material/session_12/lecture_12.ipynb", "max_issues_repo_name": "karlbindslev/sds_group29", "max_issues_repo_head_hexsha": "6f5263b08b35f35374b7f01b31a0e90d1cf4d53e", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test_karl/material/session_12/lecture_12.ipynb", "max_forks_repo_name": "karlbindslev/sds_group29", "max_forks_repo_head_hexsha": "6f5263b08b35f35374b7f01b31a0e90d1cf4d53e", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 166.1411092985, "max_line_length": 82000, "alphanum_fraction": 0.9037797819, "converted": true, "num_tokens": 2517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3062052208820547}} {"text": "# XGBoost原理与应用\n\n作者:杨岱川\n\n时间:2019年11月\n\ngithub:https://github.com/DrDavidS/basic_Machine_Learning\n\n开源协议:[MIT](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/LICENSE)\n\n参考文章:\n\n- [XGBoost PPT](https://homes.cs.washington.edu/~tqchen/pdf/BoostedTree.pdf)\n- [XGBoost: A Scalable Tree Boosting System](https://arxiv.org/abs/1603.02754)\n- [Introduction to Boosted Trees](https://xgboost.readthedocs.io/en/latest/tutorials/model.html)\n- [XGBoost原理](https://www.zhihu.com/question/58883125/answer/206813653)\n- [XGBoost原理及目标函数推导详解](https://blog.csdn.net/htbeker/article/details/91517805)\n\n## XGBoost\n\n在[2.10 提升方法](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/02机器学习基础/2.10%20提升方法.ipynb)中我们简单提到过,在SKLearn之外还有很多优秀的,基于Boosting Tree方法的衍生框架。包括XGBoost,LightGBM等,而各种开源比赛方案对它们的应用,也从事实上证明了这些框架的优秀性能。\n\n因此这一节会简要介绍XGBoost这一新框架的原理和用法。\n\n### 简介\n\n**XGBoost** 全称为“eXtreme Gradient Boosting”,是一种基于决策树的集成机器学习算法,使用梯度提升框架,适用于分类和回归问题。XGBoost 在各种比赛及比赛平台中大放异彩,比如Kaggle,天池,DataCastle等等,可以说是所有选手的必备武器之一。XGBoost 的项目主页参见[这里](https://xgboost.ai)。\n\nXGBoost 最初由陈天奇开发。陈天奇本科毕业于上海交通大学 ACM 班,博士毕业于华盛顿大学计算机系,研究方向为大规模机器学习,2020年他将加入 CMU 出任助理教授。有兴趣的可以看看他的文章[《陈天奇:机器学习科研的十年》](http://www.sohu.com/a/328234576_129720)以及[访谈](https://cosx.org/2015/06/interview-of-tianqi),也可以看看他的[知乎主页](https://www.zhihu.com/people/crowowrk/activities)。\n\n下图展示了从决策树到 XGBoost 算法的发展过程:\n\n\n\n图片刷不出来的请看[这里](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/back_up_images/xgboost发展历程.jpeg)\n\n在 [XGBoost.ai](https://xgboost.ai) 官网有对 XGBoost原理有通俗易懂的解释。\n\n现在简要介绍如下,部分基础知识之前也已经讨论过了,现在就当复习。其中的各种符号跟这里和论文保持一致,所以和之前的 GBDT 介绍可能有少许差别。\n\n### 目标函数:经验损失 + 正则化\n\n训练模型的目标是找到最好的参数 $\\theta$ ,能够最佳拟合训练数据 $x_i$ 和标签 $y_i$。所以XGBoost为了训练模型,定义了一个**目标函数(objective function)** 来告诉模型如何去拟合训练数据。\n\n目标函数由两部分组成:**经验损失**(又叫**训练损失**,**training loss**)和**正则项(regularization term)**。\n\n$$\\large {\\rm obj}(\\theta)=L(\\theta)+\\Omega(\\theta)$$\n\n其中, $L$ 就是训练损失,而 $\\Omega$ 就是正则项。\n\n通常,$L$ 会选择均方误差,如下:\n\n$$\\large L(\\theta)=\\sum_i(y_i-\\hat y_i)^2$$\n\n其中,$\\hat y_i=\\sum_j \\theta_j x_{ij}$,也就是模型的预测值。\n\n另一种常见的损失函数叫做**logistic loss**,也就是之前在逻辑回归中讲过的损失函数:\n\n$$\\large L(\\theta) = \\sum_i \\left[ y_i \\ln(1+e^{-\\hat y_i})+(1-y_i)\\ln(1+e^{-\\hat y_i}) \\right]$$\n\n至于正则项$\\Omega$,就是控制模型复杂度的,让模型不至于过拟合,以前的章节讲过多次,这里不再赘述。\n\n### 决策树的集成\n\nXGBoost模型是基于决策树的集成(**decision tree ensembles**)而来,这个集成模型是由一组**分类与回归树(CART)**所构成的,CART 的分裂基于 gini 系数,关于 CART 的详细描述可以参见《统计学习方法》中决策树一章。\n\n这里给了一个简单的例子,比如我们要运用 CART 来判断某人是否喜欢电脑游戏。我们输入一家人的年龄、性别、职业等信息,然后得到一颗决策树:\n\n\n\n图片刷不出来的看这里:[CART](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/back_up_images/cart.png)\n\n我们将家庭成员分为不同的叶子结点(leaves),然后在相应的叶子上给他们分配分数(score)。\n\n>**score** 怎么来的?\n>\n>由于这里使用的是 CART,所以当作是回归树而不要当作分类树来看,叶子结点上给出的是回归预测值,而非分类预测值。\n>\n>在每个叶子结点采用这种真实分数,可以提供超越“分类”的更丰富的解释,比如给出分类概率等,也会更方便优化,在后面会有展示。\n\n之前有提到,一棵决策树树是不够强大的,不管是随机森林、AdaBoost还是GBDT,都是集成模型,我们需要把多个**弱分类器**(基本分类器)的预测结果汇总在一起,形成一个**强分类器**,这就是**集成模型(ensemble model)**。\n\n在这里,我们汇总的方法就是把多棵树的 score 加起来,如图:\n\n\n\n图片刷不出来的看这里:[two CART](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/back_up_images/twocart.png)\n\n以上图两棵 CART 树为例,可以看出模型的集成就是简单地把两棵树叶子结点对实例的预测分数相加即可。上面这个例子表达了一个重要的点,就是两棵 CART 互为补充,以数学的形式展示就是:\n\n$$\\large \\hat y_i=\\sum^K_{k=1}f_k(x_i),\\quad f_k\\in \\Bbb F$$\n\n其中 $K$ 是树的数量, $f$ 就是一棵CART树的函数,属于函数空间 $\\Bbb F$,而 $\\Bbb F$ 是所有可能的 CART 的集合。\n\n我们待优化的目标函数在一开始已经给出了,这里对其稍作细化:\n\n$$\\large {\\rm obj}(\\theta)=\\sum_i^n l(y_i,\\hat y_i) + \\sum^K_{k=1}\\Omega(f_k)$$\n\n左边的 $\\sum_i^n l(y_i,\\hat y_i)$ 是损失函数,右边的 $\\sum^K_{k=1}\\Omega(f_k)$ 是正则项。\n\n现在的回顾一下,随机森林中使用的 *模型* 是也是集成的树(Tree ensembles),所以 boosted trees 和 random forests 的核心原理还是一样的,只不过训练过程中有点点区别。这也是我们在讲Boost算法的时候叙述过的。\n\n### 树的Boosting\n\n如何训练模型?相信大家肯定不陌生,老样子,那就是 *定义目标函数然后对其优化* !\n\n将下式作为目标函数。需要说明的是,记住它始终包含了正则项,而在我们 2.10节中讲的 AdaBoost 和 GBDT,是没有涉及正则项的。\n\n$$\\large {\\rm obj}= \\sum_{i=1}^n l(y_i,\\hat y_i^{(t)}) + \\sum^t_{i=1}\\Omega(f_k)$$\n\n#### Additive Training\n\n第一个问题:树的 **参数** 是什么?我们要学习的是那些 $f_i$ 函数,每个函数都包含树的结构和叶子得分(leaf scores)。\n\n在这里针对树的训练,采用加法策略(前向分步算法),也就是和之前 Boosting 讲的一样,根据学习结果进行权重修正,然后新增一棵树。\n\n我们定义在时间步 $t$ 时候的预测值为 $\\large \\hat y_i^{(t)}$,有:\n\n$$\n\\large\n\\begin{equation}\\begin{split} \n\\hat y_i^{(0)}&=0 \\\\\n\\hat y_i^{(1)}&=f_1(x_i)=\\hat y_i^{(0)}+f_1(x_i)\\\\ \n\\hat y_i^{(2)}&=f_1(x_i)+f_2(x_i)=\\hat y_i^{(1)}+f_2(x_i)\\\\ \n\\cdots\\\\ \n\\hat y_i^{(t)}&=\\sum^t_{k-1}f_k(x_i)=\\hat y_i^{(t-1)}+f_t(x_i)\n\\end{split}\\end{equation}\n$$\n\n还有一个问题就是,我们在每一步要的是那棵树?我们自然要选择能优化我们**目标函数**的那棵。\n\n在 $t$ 步的时候,目标函数 ${\\rm obj}^{(t)}$ 为:\n\n$$\n\\large\n\\begin{equation}\\begin{split} \n{\\rm obj}^{(t)} &= \\sum_{i=1}^n l(y_i,\\hat y_i^{(t)}) + \\sum^t_{i=1}\\Omega(f_i)\\\\\n&= \\sum_{i=1}^n l(y_i,\\hat y_i^{(t-1)}+f_t({x_i})) + \\Omega(f_t)+\\sum^{t-1}_{k=1}\\Omega(f_t)\\\\\n&= \\sum_{i=1}^n l(y_i,\\hat y_i^{(t-1)}+f_t({x_i})) + \\Omega(f_t)+{\\rm constant}\n\\end{split}\\end{equation}\n$$\n\n> 这个 $\\rm constant$ 就是常数的意思。由于前向分步算法,在 $t$ 步时候,前 $t-1$ 步的树都是已经确定了的,因此其结构是一个常数。\n>\n> 相当于 $\\large \\sum^{t-1}_{k=1}\\Omega(f_t)={\\rm constant}$\n\n如果我们使用**均方误差(mean squared error ,MSE)**作为我们的损失函数,即替换 $l(y_i,\\hat y_i^{(t)})$,那么目标函数就变成了:\n\n$$\n\\large\n\\begin{equation}\\begin{split} \n{\\rm obj}^{(t)} &= \\sum_{i=1}^n \\left(y_i - \\left(\\hat y_i^{(t-1)}+f_t(x_i)\\right)\\right)^2 + \\sum^t_{i=1}\\Omega(f_i)\\\\\n&= \\sum_{i=1}^n \\left[ 2\\left( \\hat y_i^{(t-1)}-y_i \\right)f_t(x_i)+f_t(x_i)^2 \\right] + \\Omega(f_t)+{\\rm constant}\n\\end{split}\\end{equation}\n$$\n\n> 注意这里 $\\large \\hat y_i^{(t)}$ 实际上就是 $t-1$ 步之前的 CART 森林加上第 $t$ 步生成的 CART 树的集成模型的预测结果,即:\n>\n> $$\\large \\hat y_i^{(t)} = \\hat y_i^{(t-1)}+f_t(x_i)$$\n>\n>故均方误差为:\n>\n> $$\\large \\left(y_i-\\hat y_i^{(t)}\\right)^2$$\n\n均方误差的表示形式非常方便,存在一次项和二次项。但是如果损失函数换为其他损失,比如 logistic loss,要获得这样的直观形式就比较困难了。所以,在一般情况下,我们将损失函数的**泰勒展开式(Taylor expansion)**扩展到二阶:\n\n$$\\large {\\rm obj}^{(t)}=\\sum_{i=1}^n \\left[l(y_i,\\hat y_i^{(t-1)}) + g_if_t(x_i) + \\frac{1}{2}h_if_t^2(x_i)\\right] + \\Omega(f_t)+{\\rm constant}$$\n\n其中 $g_i$ 和 $h_i$ 定义为:\n\n$$\\large g_i=\\partial_{\\hat y_i^{(t-1)}}l(y_i,\\hat y_i^{(t-1)})$$\n\n$$\\large h_i=\\partial^2_{\\hat y_i^{(t-1)}}l(y_i,\\hat y_i^{(t-1)})$$\n\n就是对损失函数求预测值 $\\large \\hat y_i^{(t-1)}$ 的一阶和二阶偏导数。\n\n> 泰勒公式的二阶近似可以表示为:\n>\n>$$\\large f(x_0+\\Delta x) \\approx f(x_0)+f'(x_0)\\Delta x+\\frac{1}{2}f''(x_0)(\\Delta x)^2$$\n>\n> 这里的增量 $\\Delta x$ 相当于 $t-1$ 步的森林中新增一棵 $t$ 时间步的树,也就是 $f_t(x_i)$\n>\n> 至于为什么要求偏导数,因为 $\\hat y_i^{(t)}$ 是我们要优化的目标,而不是 $y_i$,可以看看**梯度下降**相关内容。\n\n现在我们去掉所有常数项,因为在优化过程中保留常数没啥必要,目标函数在 $t$ 步时候就变成了:\n\n$$\\large \\sum^n_{i=1}\\left[ g_if_t(x_i) + \\frac{1}{2}h_if_t^2(x_i) \\right] + \\Omega(f_t)$$\n\n这就是我们对新的树的优化目标。\n\n我们新优化目标的优点在于目标函数的取值仅仅取决于 $g_i$ 和 $h_i$,也就是损失函数的一二阶导数,所以 XGBoost 支持自定义损失函数,只要它二阶可导。\n\n> XGBoost 的特点就是将损失函数泰勒展开到了二阶,GBDT只用到了一阶,可以回头看看[2.10 提升方法](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/%E6%9D%AD%E7%94%B5%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E8%AF%BE%E7%A8%8B%E5%8F%8A%E4%BB%A3%E7%A0%81/2.10%20%E6%8F%90%E5%8D%87%E6%96%B9%E6%B3%95.ipynb)中求负梯度那部分。\n\n### 模型复杂度\n\n刚刚已经介绍过了训练的过程,但是还没有涉及非常重要的**正则项(regularization term)**,所以这里我们先定义树的复杂度 $\\Omega(f)$。\n\n首先将树的函数 $f(x)$ 细化为:\n\n$$\\large f_t(x)=w_{q(x)},\\quad w \\in R^T,q:R_d \\rightarrow \\{1,2,\\cdots,T\\}$$\n\n其中 $w$ 是叶子上分数的矢量,$q$ 是将每个数据实例分配给相应叶子结点的函数,$T$ 是叶子的总数。\n\n换句话说,$q(x)$ 就是输出的叶子节点的序号,$w_{q(x)}$ 表示对应的叶子节点的得分。\n\n在 XGBoost中,我们将复杂度定义为:\n\n$$\\large \\Omega(f)=\\gamma T+\\frac{1}{2}\\lambda\\sum^T_{j=1}w^2_j$$\n\n相当于**叶子的总数** $T$ 加上 **叶子分数的L2正则**,$j$ 是叶子结点的编号。\n\n定义模型复杂度的方法很多,但是这种定义方法在实践中表现的很好。在以前的很多基于决策树的工具中不是很在意这部分,一般都是把复杂度的控制留给了一些启发式算法。在 XGBoost 中给出了一个正式的定义,我们可以更好地了解模型的训练过程。\n\n### The Structure Score\n\n定义了模型的复杂度之后,我们将模型的目标函数重写:\n\n$$\n\\large\n\\begin{equation}\\begin{split} \n{\\rm obj}^{(t)} &\\approx \\sum_{i=1}^n \\left[ g_iw_{q(x_i)}+\\frac{1}{2}h_iw^2_{q(x_i)} \\right] + \\gamma T+\\frac{1}{2}\\lambda\\sum^T_{j=1}w^2_j \\\\\n&= \\sum_{j=1}^T \\left[ \\left( \\sum_{i\\in I_j}g_i \\right)w_j + \\frac{1}{2}\\left( \\sum_{i\\in I_j}h_i + \\lambda \\right)w_j^2 \\right] + \\gamma T\n\\end{split}\\end{equation}\n$$\n\n其中,$I_j=\\{ i|q(x_i)=j \\}$,表示分配给第 $j$ 个叶子的样本 $x_i$ 的索引,换句话说就是回归树中的叶结点区域。\n\n然后上式把所有的样本点做了一下合并,因为同一个叶子结点上所有样本的分数都是一样的。\n\n定义:\n\n$$\\large G_j=\\sum_{j\\in I_j}g_i$$\n\n$$\\large H_j=\\sum_{j\\in I_j}h_i$$\n\n我们可以进一步简化目标函数 ${\\rm obj}^{(t)}$:\n\n$$\\large {\\rm obj}^{(t)}=\\sum^T_{j=1}\\left[ G_jw_j + \\frac{1}{2}(H_j+\\lambda)w_j^2 \\right]+\\gamma T$$\n\n在这个等式中,$w_j$ 是彼此独立的,$G_jw_j + \\cfrac{1}{2}(H_j+\\lambda)w_j^2$ 是关于 $w_j$ 的一元二次函数,对于给定的 $q(x)$,对 $w_j$ 求导可以得到最优的 $w_j$ 取值:\n\n$$\\large w_j^*=-\\frac{G_j}{H_j+\\lambda}$$\n\n把上式代入回 ${\\rm obj}^{(t)}$:\n\n$$\\large {\\rm obj}^*=-\\frac{1}{2}\\sum^T_{j=1}\\frac{G_j^2}{H_j+\\lambda}+\\gamma T$$\n\n得到最终的目标函数 ${\\rm obj}^*$,它也称为**打分函数(scoring function)**,用以衡量树结构 $q(x)$ 的好坏,值越小代表结构越好。我们采用这个打分函数来选择 CART 的最佳切分点。\n\n\n\n图片刷不出来的看这里:[struct_score](https://github.com/DrDavidS/basic_Machine_Learning/blob/master/back_up_images/struct_score.png)\n\n如图,基本上对于给定的树结构,我们将统计实例的一二阶导数,也就是梯度信息 $g_i$ 和 $h_i$ ,然后放入它们所对应的叶子结点。再对叶子上实例的梯度信息求和,使用上面推出的公式计算树的质量。其实有点类似于计算一棵 CART 决策树的 gini 不纯度,但是不同之处在于它还考虑的模型的复杂度。\n\n关于**gini不纯度**可以参考《统计学习方法》中决策树一章对 CART 的讲解。\n\n### 学习树的结构\n\n到目前为止,我们有了一种衡量一棵决策树质量的方法,理想情况下,我们会列举出所有可能的决策树,然后选择最好的一棵。但是实际上这是几乎不可能的。所以我们会试着一次优化树的一层(level),层层深入。\n\n具体来说,我们把一个结点切分为两个子结点,其得分为:\n\n$$\\large Gain=\\frac{1}{2}\\left[ \\frac{G^2_L}{H_L+\\lambda}+\\frac{G^2_R}{H_R+\\lambda}-\\frac{(G_L+G_R)^2}{H_L+H_R+\\lambda} \\right]-\\gamma$$\n\n该公式可以理解为新切分的左叶子结点的分数加上新切分的右叶子结点的分数减去原来叶子结点的分数,外加一个叶上的正则化。\n\n这里有一个重要的事实,就是如果新切分的增益小于 $\\gamma$,就不要添加该分支,这相当于是决策树的剪枝技术。这个 $\\gamma$ 值是一个超参数,人工设定。\n\n我们希望搜索到一个最佳的切分,而为了达成这个目标,将所有实例按照排序顺序放置,如图,按照年龄排序:\n\n\n\n然后我们从左到右开始扫描分裂点,计算这些 CART 树的得分,就可以高效地找到最佳拆分点。\n\n> 前向算法的局限性\n>\n> 在少部分边缘情况下,前向算法可能会失败,扩展阅读:[Can Gradient Boosting Learn Simple Arithmetic?](http://mariofilho.com/can-gradient-boosting-learn-simple-arithmetic/)\n\n### 结语\n\n到现在我们已经完成了对 XGBoost 原理的学习,而 XGBoost 也根据以上原理编写成了 XGBoost 工具,记得尝试一下这一款优秀的机器学习工具吧!\n\n## XGBoost 安装和使用\n\n参考[Get Started with XGBoost](https://xgboost.readthedocs.io/en/latest/get_started.html)\n\n示例代码请先参考官方文档,本 NoteBook 待补充。\n\n\n```python\n\n```\n", "meta": {"hexsha": "2368c50223739c20f243ff39c1bc6d6e756b9e90", "size": 14209, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "02机器学习基础/2.11 XGBoost原理与应用.ipynb", "max_stars_repo_name": "DrDavidS/basic_Machine_Learning", "max_stars_repo_head_hexsha": "d6f6538a13ed68543569f595fa833e6d220beedd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15, "max_stars_repo_stars_event_min_datetime": "2019-09-12T01:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-01T02:30:51.000Z", "max_issues_repo_path": "02机器学习基础/2.11 XGBoost原理与应用.ipynb", "max_issues_repo_name": "DrDavidS/basic_Machine_Learning", "max_issues_repo_head_hexsha": "d6f6538a13ed68543569f595fa833e6d220beedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02机器学习基础/2.11 XGBoost原理与应用.ipynb", "max_forks_repo_name": "DrDavidS/basic_Machine_Learning", "max_forks_repo_head_hexsha": "d6f6538a13ed68543569f595fa833e6d220beedd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11, "max_forks_repo_forks_event_min_datetime": "2019-10-19T03:12:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T05:14:01.000Z", "avg_line_length": 37.5899470899, "max_line_length": 286, "alphanum_fraction": 0.5697093392, "converted": true, "num_tokens": 6214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.3062052208820547}} {"text": "\n\n\n```python\npip install tensorflow==2.4.1 tensorflow-quantum\n```\n\n\n```python\n# Update package resources to account for version changes.\nimport importlib, pkg_resources\nimportlib.reload(pkg_resources)\n```\n\n\n\n\n \n\n\n\n\n```python\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n\n\n\n```python\nimport sys\nsys.path.append('/content/drive/My Drive')\n```\n\n\n```python\nimport eecs598\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport statistics\nimport numpy as np\n```\n\n\n```python\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\n\nimport cirq\nimport sympy\nimport numpy as np\nimport seaborn as sns\nimport collections\n\n# visualization tools\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\n```\n\n\n```python\n\n# Control qrid size for visualization\nplt.rcParams['figure.figsize'] = (10.0, 8.0)\nplt.rcParams['font.size'] = 16\n```\n\n\n```python\nx_train, y_train, x_test, y_test = eecs598.data.cifar10()\n\nprint('Training set:', )\nprint(' data shape:', x_train.shape)\nprint(' labels shape: ', y_train.shape)\nprint('Test set:')\nprint(' data shape: ', x_test.shape)\nprint(' labels shape', y_test.shape)\n```\n\n Training set:\n data shape: torch.Size([50000, 3, 32, 32])\n labels shape: torch.Size([50000])\n Test set:\n data shape: torch.Size([10000, 3, 32, 32])\n labels shape torch.Size([10000])\n\n\n\n```python\n#Visualization of the dataset\n\nimport random\nfrom torchvision.utils import make_grid\n\nclasses = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\nsamples_per_class = 12\nsamples = []\nfor y, cls in enumerate(classes):\n plt.text(-4, 34 * y + 18, cls, ha='right')\n idxs, = (y_train == y).nonzero(as_tuple=True)\n for i in range(samples_per_class):\n idx = idxs[random.randrange(idxs.shape[0])].item()\n samples.append(x_train[idx])\nimg = torchvision.utils.make_grid(samples, nrow=samples_per_class)\nplt.imshow(eecs598.tensor_to_image(img))\nplt.axis('off')\nplt.show()\n```\n\n\n```python\n\n```\n\n\n```python\nfrom tensorflow.keras.datasets import cifar10\n(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()\n```\n\n\n```python\ny_train=train_labels.flatten()\ny_test=test_labels.flatten()\n# We have reduced the dimension\n```\n\n\n\n\n```python\nx_train=tf.image.rgb_to_grayscale(train_images)\nx_test=tf.image.rgb_to_grayscale(test_images)\n#to convert grayscale\n```\n\n\n```python\n#Filter the dataset to keep just the cat and frog, remove the other classes\ndef filter_36(x, y):\n keep = (y == 3) | (y == 6)\n x, y = x[keep], y[keep]\n y = y == 3\n return x,y\n```\n\n\n```python\nx_train, y_train = filter_36(x_train, y_train)\nx_test, y_test = filter_36(x_test, y_test)\n\nprint(\"Number of filtered training examples:\", len(x_train))\nprint(\"Number of filtered test examples:\", len(x_test))\n```\n\n Number of filtered training examples: 10000\n Number of filtered test examples: 2000\n\n\n\n```python\nplt.imshow(x_train[0, :, :, 0])\nplt.colorbar()\n```\n\n\n```python\nx_train_s = tf.image.resize(x_train, (4,4)).numpy()\nx_test_s = tf.image.resize(x_test, (4,4)).numpy()\n```\n\n\n```python\n\nTHRESHOLD = 0.5\n\nx_train_bin = np.array(x_train_s > THRESHOLD, dtype=np.float32)\nx_test_bin = np.array(x_test_s > THRESHOLD, dtype=np.float32)\n```\n\n\n```python\ndef convert_to_circuit(image):\n \"\"\"Encode truncated classical image into quantum datapoint.\"\"\"\n values = np.ndarray.flatten(image)\n qubits = cirq.GridQubit.rect(4, 4)\n circuit = cirq.Circuit()\n for i, value in enumerate(values):\n if value:\n \n circuit.append(cirq.Circuit(cirq.X(qubits[i]), cirq.Y(qubits[i]),cirq.Z(qubits[i]) ))\n\n return circuit\n\n\nx_train_circ = [convert_to_circuit(x) for x in x_train_bin]\nx_test_circ = [convert_to_circuit(x) for x in x_test_bin]\n```\n\n\n```python\nSVGCircuit(x_train_circ[0])\n\n```\n\n\n\n\n \n\n \n\n\n\n\n```python\nx_train_tfcirc = tfq.convert_to_tensor(x_train_circ)\nx_test_tfcirc = tfq.convert_to_tensor(x_test_circ)\n```\n\n\n```python\nclass CircuitLayerBuilder():\n def __init__(self, data_qubits, readout):\n self.data_qubits = data_qubits\n self.readout = readout\n\n def add_layer(self, circuit, gate, prefix):\n for i, qubit in enumerate(self.data_qubits):\n symbol = sympy.Symbol(prefix + '-' + str(i))\n circuit.append(gate(qubit, self.readout)**symbol)\n```\n\n\n```python\ndemo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1),\n readout=cirq.GridQubit(-1,-1))\n\ncircuit = cirq.Circuit()\ndemo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx')\nSVGCircuit(circuit)\n```\n\n\n\n\n \n\n \n\n\n\n\n```python\ndef create_quantum_model():\n \"\"\"Create a QNN model circuit and readout operation to go along with it.\"\"\"\n data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.\n readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]\n circuit = cirq.Circuit()\n\n # Prepare the readout qubit.\n circuit.append(cirq.X(readout))\n circuit.append(cirq.H(readout))\n\n builder = CircuitLayerBuilder(\n data_qubits = data_qubits,\n readout=readout)\n\n # Then add layers (experiment by adding more).\n builder.add_layer(circuit, cirq.XX, \"xx1\")\n builder.add_layer(circuit, cirq.ZZ, \"zz1\")\n\n # Finally, prepare the readout qubit.\n circuit.append(cirq.H(readout))\n\n return circuit, cirq.Z(readout)\n```\n\n\n```python\nmodel_circuit, model_readout = create_quantum_model()\n```\n\n\n```python\nmodel = tf.keras.Sequential([\n # The input is the data-circuit, encoded as a tf.string\n tf.keras.layers.Input(shape=(), dtype=tf.string),\n # The PQC layer returns the expected value of the readout gate, range [-1,1].\n tfq.layers.PQC(model_circuit, model_readout),\n])\n```\n\n\n```python\ny_train_hinge = 2.0*y_train-1.0\ny_test_hinge = 2.0*y_test-1.0\n\n```\n\n\n```python\ndef hinge_accuracy(y_true, y_pred):\n y_true = tf.squeeze(y_true) > 0.0\n y_pred = tf.squeeze(y_pred) > 0.0\n result = tf.cast(y_true == y_pred, tf.float32)\n\n return tf.reduce_mean(result)\n```\n\n\n```python\nmodel.compile(\n loss=tf.keras.losses.Hinge(),\n optimizer=tf.keras.optimizers.Adam(),\n metrics=[hinge_accuracy])\n\n```\n\n\n```python\nprint(model.summary())\n```\n\n Model: \"sequential_1\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n pqc_1 (PQC) (None, 1) 18 \n =================================================================\n Total params: 18\n Trainable params: 18\n Non-trainable params: 0\n _________________________________________________________________\n None\n\n\n\n```python\nEPOCHS = 3\nBATCH_SIZE = 128\n\nNUM_EXAMPLES = len(x_train_tfcirc)\n\n```\n\n\n```python\nx_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES]\ny_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES]\n\n```\n\n\n```python\nimport time\nstart_time = time.time()\n```\n\n\n```python\nqnn_history = model.fit(\n x_train_tfcirc_sub, y_train_hinge_sub,\n batch_size=32,\n epochs=EPOCHS,\n verbose=1,\n validation_data=(x_test_tfcirc, y_test_hinge))\n\nqnn_results = model.evaluate(x_test_tfcirc, y_test)\n\n```\n\n Epoch 1/3\n 313/313 [==============================] - 487s 2s/step - loss: 1.0004 - hinge_accuracy: 0.5010 - val_loss: 1.0021 - val_hinge_accuracy: 0.5015\n Epoch 2/3\n 313/313 [==============================] - 483s 2s/step - loss: 1.0041 - hinge_accuracy: 0.4933 - val_loss: 1.0021 - val_hinge_accuracy: 0.5015\n Epoch 3/3\n 313/313 [==============================] - 484s 2s/step - loss: 1.0015 - hinge_accuracy: 0.4947 - val_loss: 1.0022 - val_hinge_accuracy: 0.5015\n 63/63 [==============================] - 19s 302ms/step - loss: 1.0022 - hinge_accuracy: 0.5015\n\n\n\n```python\nqnn_accuracy = qnn_results[1]\nqnn_accuracy\n```\n\n\n\n\n 0.5014880895614624\n\n\n\n\n```python\nmodel.predict_classes(x_train_tfcirc[0:7])\n```\n\n /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/sequential.py:450: UserWarning: `model.predict_classes()` is deprecated and will be removed after 2021-01-01. Please use instead:* `np.argmax(model.predict(x), axis=-1)`, if your model does multi-class classification (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype(\"int32\")`, if your model does binary classification (e.g. if it uses a `sigmoid` last-layer activation).\n warnings.warn('`model.predict_classes()` is deprecated and '\n\n\n\n\n\n array([[0],\n [0],\n [0],\n [0],\n [0],\n [0],\n [0]], dtype=int32)\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.gridspec import GridSpec\n\ndef format_axes(fig):\n for i, ax in enumerate(fig.axes):\n ax.tick_params(labelbottom=False, labelleft=False)\n\nfig = plt.figure(figsize=(10, 10))\n\ngs = GridSpec(3, 3, figure=fig)\nax1 = fig.add_subplot(gs[0, 0])\n# identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))\n\nfor i in range(3):\n for j in range(3):\n ax = fig.add_subplot(gs[i, j])\n \n ax.imshow(x_train[i+j, :, :, 0])\n\nfig.suptitle(\"GridSpec\")\nformat_axes(fig)\n\nplt.show()\n```\n\n\n```python\nplt.plot(qnn_history.history['hinge_accuracy'], label='QNN')\n#plt.plot(hybrid_history.history['val_custom_accuracy'], label='Hybrid CNN')\n#plt.title('Quantum vs Hybrid CNN performance')\nplt.xlabel('Epochs')\nplt.legend()\nplt.ylabel('Validation Accuracy')\nplt.show()\n```\n", "meta": {"hexsha": "42864898b0a337586108e1e1635e90a5b952f08e", "size": 762111, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "X_Y_Zgate.ipynb", "max_stars_repo_name": "WebheadTech/QCourse511-1", "max_stars_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "X_Y_Zgate.ipynb", "max_issues_repo_name": "WebheadTech/QCourse511-1", "max_issues_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "X_Y_Zgate.ipynb", "max_forks_repo_name": "WebheadTech/QCourse511-1", "max_forks_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 854.384529148, "max_line_length": 607250, "alphanum_fraction": 0.9407973379, "converted": true, "num_tokens": 2729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.30620522088205465}} {"text": "```python\nimport pandas as pd\nimport ms3 \nfrom ms3.utils import *\nimport os \nfrom ms3 import Score\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\nfrom scipy import stats\n# include directory \nhome_dir = '/home/nulpe/Desktop/Tresillo/'\n```\n\n# Towards a Rhythmical Definition of the Tressilio beat and a Tracing of it in Popular Music \n\n## 1) Introduction & Research Question \n\n### 1.1) Research question: \n\"Can we compute to which extent a defined rhythm, which we refer to as Tresillo rhythm, is used in a given pop song and if so can we measure the intensity of Tresillo rhythm use in top-20-billboard songs over the past twenty years?\" \n\n**Discussion:** \nIn our project we would like to discuss the use of a rhythm, which we refer to as 'Tresillo rhythm', in the popular music of the last 20 years. We define this rhythm in our project, given secondary literature, and thus obtain a precise notation and formulization of the Tresillo rhythm. Given this definition we can then compute the similarity between the Tresillo rhythm and the rhythm of a given pop song. Thus, we hope to obtain a similarity coefficient which measures how similar the rythm of a given pop song is to our self defined Tresillo rythm. Given the computed similarity coefficients, we hope to measure the use of the Tresillo rhythm in the top 20 billboard songs of the past 20 years (1999-2019).\n\n\n### 1.2) Assumptions\n\n- We assume that for most pop songs present in the billboaard charts, one can identify one dominant rythm per song.This assumption is supported by [insert bibliographie or use our rythm space and a time trajectory over the bars of the songs and show that a vector of a song is not changing a lot over the bars of the song]. \n- For our presntation of songs in rythm space, we also assume that the majority of the songs in the billboard charts is in the time signature of 4/4. The following data exploration justifies this assumption.(There are 420 songs with 4/4, 6 with 3/4 and 16 with changing time signature). \n- We assume that a time sample longer than [40] seconds is suitable to present the main rythm of a pop song. We need to discuss which treshold we want to set. The lower the more songswe have ,the higher the time treshold the weaker our assumption.\n \n\n\n```python\n#Some numbers regarding our song length assumption, not adressed in the former notebooks\nlist_midis = os.listdir(r\"C:/Users/Florian/Documents/GitHub/Tresillo/dataset/project_midi/billboard\")\nlength_midis = []\nfor el in list_midis:\n midi_data = pretty_midi.PrettyMIDI(\"C:/Users/Florian/Documents/GitHub/Tresillo/dataset/project_midi/billboard\" +'/'+el)\n length_midis.append(midi_data.get_end_time())\n\naverage_midi_length = (sum(length_midis)/len(length_midis))\nplt.figure(1)\nplt.hist(length_midis, 20)\nmidi_length_standart_dev = statistics.stdev(length_midis)\ncounter_30 = 0\ncounter_40 = 0\ncounter_30 = sum (i < 30 for i in length_midis)\ncounter_40 = sum (i < 40 for i in length_midis)\n\nprint(\"Samples shorter than 30 sec: \" + counter)\nprint(\"Samples shorter 40 sec: \" + counter_40)\nprint (\"Average sample length\" + average_midi_length)\nprint(\"Standart deveiation sample length\" + midi_length_standart_dev)\n```\n\n### 1.3) Data Representation\nInitially our data is represented in the MIDI file format. The representation of music in the MIDI format has the advantage, that often several voices of different instruments are represented in such files. In contrast to musescore, where often only the voice of one instrument (mostly piano) is notated. \nHowever, to obtain a list of onsets of every musical event in a given song, we have to convert our MIDI (.midi) files to Musescore (.mscx) files. \nTo convert and further analyze our files, we will use the [ms3](https://pypi.org/project/ms3/) python library. \nTo convert a directory of .midi files to .mscx files we use following command:\n\n\n\n```python\npath_midi = '/home/nulpe/Desktop/Tresillo/dataset/project_midi/tresillo/'\ntarget = '/home/nulpe/Desktop/Tresillo/dataset/project_mscx/mscx_tresillos_billboard/'\n\ndir_list = os.listdir(path_midi)\n\nfor el in dir_list:\n convert(path_midi+el, target+el[:-4]+'.mscx', MS='musescore3')\n```\n\n**TA instructions**: Precision of Research Question\n\n- State the final version of your research question as you understand it now.\n\n- Make all assumptions and hypotheses explicit.\n\n- In case Milestone 2 did not include the final data representation that you are analyzing, present the representation you finally used and the necessary steps to get to it.\n\n**Thoughts Aurel:** \n - Reasearch Question: Move to a fuzzy definition of Tresillio-ness: E.g.: \n Are pop songs increasingly using a rythm pattern which is similar to a rythm pattern which we reffer to as 'Tresillio rythm'? \n \n - Assumptions are very important for them. Here we have to note our definition(s) of the Tresillio rythm pattern and how we derive them (incl sources). Furthermore, we have to discuss cases where there are Rythms which are similar to the Tresillio rythm but not equivalent (e.g.: reggaeton) and how we deal with them computationally. \n \n - Here we have to discuss the conversion of our MIDI files to the musescore3 file format. Furthermore, we have to discuss what the musescore3 format offers us, and why it is the better choice for our analysis. \n \n **Toughts Florian:**\n -Assumptions:\n \n -30 second piece of pop song is suitable to identfy the main rythm\n \n -Main rythm can be identified by counting the onsets\n \n -the great majority of pop songs comes in 4/4 (not shure if we really need that assumption)\n \n\n\n \n\n## 2) Methods\n\n### 2.1) Definition of the Tresillo rhythm\nWe notate a clean version of a rythm wich we from now on use as our defintion for the clean tresillo rythm, in the following context also called vanilla tresillo. \n\n\n\nThe rhythm pattern consists of a dotted eighth note, followed by a sixteenth note, an eighth rest and an eighth note and is repeated two times in a 4/4 bar. The rytm pattern is beeing used as a own rythm or as a rythmic part of a more complex rythm, for example the \"clave\" pattern or the ragaetton rythm.\nBy notating the rythm in MuseScore 3 and saving it as a .mscx file, we can use it our data processing pipeline described in the following sections.\n\n### 2.2) Rhythm histograms and vectors \n\nTo be able to measure the similarity between rhythm we must have a clear definition and thus following representation of rhythm. In general, one can define rhythm as \"a series of onsets and durations of musical events.” (Rohrmeier, 2020). In our specific case however, we are interested in the dominat and repeating rhythm of a given song. Therefore we prefer a narrower definition of rhythm as “repeated recurrences in alternate heavy and light beats” (Chin and Wu, 1992). To furthermore simplify our data, we assume that the main rhythm of a song can be defined by the onsets of its musical events (notes). \nTo obtain a representation of the dominate rhythm of a song, we preceed to aggregate all musical onset to one bar. Collapsing all musical onsets to one bar and thus obtaining onset 'histograms' is a common pratice and has been used beside others to analyze western classical music (Palmer and Krumhansl, 1990) and american folk music (Huron and Ommen, 2006). \nWith the onset histogram of a song we can compile a n dimensional vector for each song, which we refer to as a 'rhythm vector'. Given that the number of songs with meters other than 4/4 is negible, we only consider songs with a 4/4 meter in our analysis. Given that we only consider songs with 4/4 meters, we obtain for each song a 16 dimensional vector. \n\n\n\n\n### 2.3) Naive approach: Rhythm simularity measured with cosine simularity \nGiven the 16 dimensional rhythm vectors we obtain following the methode described above, we can now compute simple similarity metrics. \nIn rhythm analysis a common similarity metric which is used to calculate the similarity between two rhythm vectors is the cosine distance (see: Panteli et al., 2014; Parry and Essa, 2003). The cosine similarity metric is scale invariante, which as such is interesting for rhythm similarity given that thus only relative frequencies of onsets are important and not absolute frequencies. \nThe cosine distance between two vectors A and B is defined as following: \n\\begin{equation}\n\\cos ({\\bf A},{\\bf B})= {{\\bf A}*{\\bf B} \\over \\|{\\bf A}\\| \\|{\\bf B}\\|} = \\frac{ \\sum_{i=1}^{n}{{\\bf A}_i{\\bf B}_i} }{ \\sqrt{\\sum_{i=1}^{n}{({\\bf A}_i)^2}} \\sqrt{\\sum_{i=1}^{n}{({\\bf B}_i)^2}} }\n\\end{equation}\n\nGiven the definition of the cosine similarity we can now compute the similarity between our self defined Tresillo rhythm and the billboard songs. \nFirst, however we will validate this similarity metric by testing it on our self compiled list of songs which do comprise a Tresillo rhythm and songs which do not comprise a Tresillo rhythm. We then compute the mean 'Tresillo-ness' (similarity to Tresillo rhythm) of both samples. By employing the Bootstrapping method we can also obtain a measurement of uncertainty, as provided by 2.5% and 97.5% confidence intervals.\n\n### 2.4) Reducing noise: (pushkar)\n\n**TA instructions**: \n- How did you deal with the problems you mentioned in Milestone 2?\n\n- Which methods did you use to obtain the final results? Provide self-contained explanations and make sure to cite relevant literature where appropriate.\n\n- Explain your core calculations using equations.\n\n- Do not describe all the methods you tried out but only those that lead to the results: the final analysis is not an exploratory analysis anymore.\n\n- Specify any adjustments you made to pre-existing methods\n\n\n**Thoughts Aurel**: \n - Talk about how we got to the bar representation of our music. Furthermore, also discuss how we get to a 'perfect Tresillio Histogram'\n \n - Here I propose we try out several things and compare the results of several methods:\n \n a) A first big topics is how we define the perfect Tresillo: \n 1. Given predefined rythm patterns (by Florian)\n 2. Given songs with high Tresillio-ness\n - All instruments collapsed\n - Only key instruments\n - Certain instruments \n \n a) The second big question is how do we measure Tresillio-ness in the pop songs, I would suggest three approaches. All aproaches require that we first obtain 16 dimensional Rythm vectors of each song of interest: \n 1. Compare our vanilla self defined Tresillio rythm vector with all vectors of our pop songs. Measure distance or simularity with some commonly used distance measure in the literature\n 2. Very similar to 1) but this time use the Tresillio rythm vector as defined by our songs\n 3. Prior clustering of the rythm vectors. Obtaining centroid and measuring with it Tresillio ness in the charts (method as proposed by Pushkar)\n \n- Equations should be included in the prior part\n- Discuss critically any outliers, problems and limitations of our methodology. Extra focus on the question how we deal with related but not the same rythm (e.g.: Reggaeton)\n\n\n**Toughts Florian**\n- Following the last paper discussion one measuurement we could use is the Cosin distance \n- Not sure about an instrument selection. We can mention that a reduction seems not favorable as the tresillo rythm is presented with different instruments throughout the dataset\n\n\n\n## 3) Final Results\n\n### 3.1) Onset histograms and rhythm vectors \nIn this first part we will use onset histograms to compute rhythm vectors. \nTo obtain the onset histogram of a given song, we use the notes representation provided by the [ms3](https://pypi.org/project/ms3/) libary and colapse all musical onsets to one bar. In the example below we will compile the histograms for our self defined 'Vanilla Tresillo' and for the example song 'shape of you' by Ed Sheran. Then we will proceed to compute the rhythm vectors for both songs\n\n\n```python\n#paths to both examples\nshape_of_you = home_dir+'dataset/project_mscx/mscx_tresillos_billboard/Shape of you-Ed Sheran.mscx'\nvanilla_tresillo = home_dir+'dataset/project_mscx/mscx_tresillos/Vanilla_Tresillo.mscx'\n\n\n# get the note scores of both examples \ndf_shape_of_you = Score(shape_of_you).mscx.notes\ndf_vanilla_tresillo = Score(vanilla_tresillo).mscx.notes\n\n#calculate quarter note position for each note\ndf_shape_of_you['quarter_beats'] = (df_shape_of_you.mc_onset*16).astype('int32')\ndf_vanilla_tresillo['quarter_beats'] = (df_vanilla_tresillo.mc_onset*16).astype('int32')\n\n\nfig, ax = plt.subplots(1,2, figsize=(12,3))\n\nax[0].hist(df_shape_of_you['quarter_beats'], bins=16)\nax[1].hist(df_vanilla_tresillo['quarter_beats'], bins=16)\nax[0].set_xlabel('quarter_beats')\nax[1].set_xlabel('quarter_beats')\nax[0].xaxis.set_ticks(np.arange(0, 16, 1))\nax[1].xaxis.set_ticks(np.arange(0, 16, 1))\nax[0].set_ylabel('count')\nax[0].set_title('Shape of you')\nax[1].set_title('Vanilla Tresillo')\n\n#mention somewhere that we are working with quarter notes \n```\n\nIn a next step we want to compile rhythm of each song given this notion of histograms. E.g: every dimension incorporates the absolute frequency of onsets on one given quarter note. This is done as follows:\n\n\n```python\nrhythm_vector_shape_you = df_shape_of_you.groupby(['quarter_beats'])['mn'].agg(['count'])\nrhythm_vector_shape_you = rhythm_vector_shape_you.reindex(list(range(0,16)),fill_value=0).T\nrhythm_vector_shape_you \n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
quarter_beats0123456789101112131415
count20633441197237169122002975112752716710
\n
\n\n\n\nIn the assumption that the rhythm vectors of distinct voices within a song might include information we want to preserve, we compiled one rhythm vector per instrument in a song as follows:\n\n\n```python\n# Define instruments \nshape_of_you_score = Score(shape_of_you)\ninstrument_dict = {}\nfor key in shape_of_you_score.mscx.metadata['parts']:\n for staff in shape_of_you_score.mscx.metadata['parts'][key].keys():\n instrument_dict[staff] = key\n\n\n#staff to voice/instruments \ndf_shape_of_you['instrument'] = [instrument_dict[el] if el in instrument_dict else 'na' for el in df_shape_of_you.staff]\n\n#compute rhythm vectors per voice\nrhythm_vector_shape_you_instruments = df_shape_of_you.groupby(['instrument','quarter_beats'])['mn'].agg(['count'])\nrhythm_vector_shape_you_instruments = rhythm_vector_shape_you_instruments.groupby(level=0).apply(lambda x: x.reset_index(level = 0).drop(['instrument'],axis=1).reindex(list(range(0,16)),fill_value=0).T)\nrhythm_vector_shape_you_instruments = rhythm_vector_shape_you_instruments.reset_index()\nrhythm_vector_shape_you_instruments\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
quarter_beatsinstrumentlevel_10123456789101112131415
0Grand Pianocount660000000660000000
1Marimba, untitledcount660053140630680057170630
2Melodic Drumcount00333613193900050281019380
3Overdrive Gtrcount6211446261626160
4Percussioncount242302192222212112192232
5Tenor Saxcount2081081612168167186155148
6Woodblockcount2002002020012020
7Xylophonecount2200176021021001660210
\n
\n\n\n\nIf we want to compile rhythm vectors (per voice) for all mscx files in one directory we can use following loop:\n\n\n```python\ndef rythm_vectors(in_dir, out_dir):\n list_sheet_music = os.listdir(in_dir)\n df_rythm_vectors =[]\n\n for idx, el in enumerate(list_sheet_music):\n if el[-4:] == 'mscx':\n\n \n #Get notes with onsets\n s = Score(dir_sheet_music+el)\n df = s.mscx.notes\n\n # Define instruments \n instrument_dict = {}\n for key in s.mscx.metadata['parts']:\n for staff in s.mscx.metadata['parts'][key].keys():\n instrument_dict[staff] = key\n\n\n #staff to instruments \n df['instrument'] = [instrument_dict[el] if el in instrument_dict else 'na' for el in df.staff]\n\n\n # define quarter beat \n df['quarter_beats'] = (df.mc_onset*16).astype('int32')\n\n\n #make rythm matrix & data frame\n df_histogram = df.groupby(['instrument','quarter_beats'])['mn'].agg(['count'])\n df_histogram = df_histogram.groupby(level=0).apply(lambda x: x.reset_index(level = 0).drop(['instrument'],axis=1).reindex(list(range(0,16)),fill_value=0).T)\n df_histogram = df_histogram.reset_index()\n\n df_histogram.insert(loc=0, column='song_artist', value=el[:-5])\n\n #concat to big rythm vector df\n if len(df_rythm_vectors) == 0: df_rythm_vectors = df_histogram\n\n df_rythm_vectors = pd.concat([df_rythm_vectors,df_histogram], axis=0)\n\n df_rythm_vectors.to_csv(out_dir, index = False)\n\n \ndir_sheet_music = home_dir + '/dataset/project_mscx/mscx_billboard/'\nout_dir = home_dir + '/dataset/rythm_vectors/rythm_vectors_billboard.csv'\nrythm_vectors(dir_sheet_music, out_dir)\n```\n\n### 3.2) Tresilio-ness with Cosine Similarity\nIn a first naive analysis we will employ the cosine similarity measurement to assess if the vector of a given song is similar to our defined Tresillo rhythm. We will need some helper functions. \nFollowing two helper functions will help us to collapse all rhythms of all instruments to one rhythm vector per song. \nThe second function calculates the cosine similarity between a pandas data frame of rhythm vectors and one single rhythm vector. \nThe third function calculates the 2.5% and the 97.5% confidence intervals of the distribution of a mean of a given data set. This function will allow us to assess, how big the uncerntaingty is in our data set and if the means of two distributions are indeed significantly different.\n\n\n```python\ndef collapse_normalize_vectors(df_rythm_vectors):\n rythm_vector_collaped = df_rythm_vectors.groupby(['song_artist']).agg(['sum'])\n rythm_vector_collaped.columns = rythm_vector_collaped.columns.droplevel(1)\n rythm_vector_collaped = rythm_vector_collaped.drop(['instrument', 'level_1'],axis=1)\n rythm_vector_collaped[\"sum\"] = rythm_vector_collaped.sum(axis=1)\n rythm_vector_collaped = rythm_vector_collaped.loc[:,\"0\":\"15\"].div(rythm_vector_collaped[\"sum\"], axis=0)\n return rythm_vector_collaped\n\ndef calc_cosine_sim(rythm_vectors, tresillo_vector):\n rythm_vectors['cosine_sim_tresillo'] = cosine_similarity(rythm_vectors.loc[:,\"0\":\"15\"],tresillo_vector)\n return rythm_vectors\n\ndef bootstrap_CI(data, nbr_draws):\n means = np.zeros(nbr_draws)\n data = np.array(data)\n\n for n in range(nbr_draws):\n indices = np.random.randint(0, len(data), len(data))\n data_tmp = data[indices] \n means[n] = np.nanmean(data_tmp)\n return [np.nanpercentile(means, 2.5),np.nanpercentile(means, 97.5)]\n```\n\nNow lets read in the rhythm vector of our vanilla Tresillo.\n\n\n```python\ndf_synt_tresillo = pd.read_csv(home_dir + '/dataset/rythm_vectors/rythm_vectors_tresillio.csv') # read in all defined 'tresillos' and variations\ndf_vanilla_tresillo = df_synt_tresillo[df_synt_tresillo['song_artist']=='Vanilla_Tresillo'].loc[: ,\"0\":\"15\"] # only use the 16d vector of our vanilla_tresillo\nvector_vanilla_tresillo = np.asarray(df_vanilla_tresillo)\nvector_vanilla_tresillo\n```\n\n\n\n\n array([[20, 0, 0, 20, 0, 0, 20, 0, 20, 0, 0, 20, 0, 0, 20, 0]])\n\n\n\nWe will now calculate the cosine similarity between our vanilla Tresillo vector and between a hand selected set of Tresillo songs. \nThis set of songs has been selected by us ourself and none of those 'validation' songs are included in the billboard data sets.\n\n\n```python\n\ntresillo_test_set_vectors = pd.read_csv(home_dir + '/dataset/rythm_vectors/rythm_vectors_tresillo_not_billboard.csv')\n#tresillo_test_set_vectors = pd.read_csv(home_dir + '/dataset/rythm_vectors/rythm_vectors_tresillos_billboard.csv')\ntresillo_test_set_vectors = collapse_normalize_vectors(tresillo_test_set_vectors)\ntresillo_test_set_vectors = calc_cosine_sim(tresillo_test_set_vectors, vector_vanilla_tresillo)\nprint(tresillo_test_set_vectors['cosine_sim_tresillo'])\n```\n\n song_artist\n Attention Charlie Puth 0.613390\n Chandelier Sia 0.605698\n Cold Water Major Lazer 0.896750\n Hips Don't Lie Shakira 0.819003\n I Don't Care Ed Sheeran & Justin Bieber 0.876542\n One Dance - Drake & Wizkid, Kyla Reid 0.717454\n Rockabye Baby Clean Bandit 0.880677\n Sorry Justin Bieber 0.853424\n Titanium David Guetta 0.652046\n Name: cosine_sim_tresillo, dtype: float64\n\n\nLet's calculate the mean Tresillo-ness and also the 2.5% and 97.5% confidence intervals of the mean as obtained by bootstrapping.\n\n\n```python\nprint('mean Tresillo-ness in the test set: ', tresillo_test_set_vectors['cosine_sim_tresillo'].mean())\nlower_tresillo_ci, upper_tresillo_ci = bootstrap_CI(tresillo_test_set_vectors['cosine_sim_tresillo'], 100)\nprint('tresillo upper and lower ci on 100 draws: ', lower_tresillo_ci, upper_tresillo_ci)\n```\n\n mean Tresillo-ness in the test set: 0.7683315382006799\n tresillo upper and lower ci on 100 draws: 0.6808770780048731 0.8481138158323536\n\n\nLet's do exact same thing, but with a comparison data set of songs which we kno to not include any Tresillo songs. \nAlso calculating the mean and the confidence intervals of the not Tresillo songs.\n\n\n```python\nnon_tresillio_vectors = pd.read_csv(home_dir + '/dataset/rythm_vectors/rythm_vectors_not_tresillo_validation.csv')\n#non_tresillio_vectors = pd.read_csv(home_dir + '/dataset/rythm_vectors/rythm_vectors_no_tresillos_4_4.csv')\n\nnon_tresillio_vectors = collapse_normalize_vectors(non_tresillio_vectors)\nnon_tresillio_vectors = calc_cosine_sim(non_tresillio_vectors, vector_vanilla_tresillo)\nprint(non_tresillio_vectors['cosine_sim_tresillo'])\n\nprint('mean Tresillo-ness in the test set: ', non_tresillio_vectors['cosine_sim_tresillo'].mean())\nlower_non_tresillo_ci, upper_non_tresillo_ci = bootstrap_CI(non_tresillio_vectors['cosine_sim_tresillo'], 100)\nprint('tresillo upper and lower ci on 100 draws: ', lower_non_tresillo_ci, upper_non_tresillo_ci)\n```\n\n song_artist\n Dress You Up 0.666450\n Fear of the Dark 0.689443\n Folsom Prison Blues 0.657568\n Immigrant Song 0.584275\n Jailhouse Rock 0.593940\n One Step Closer 0.523399\n Sweet Child O'Mine 0.724700\n Sweet Home Alabama 0.534338\n Name: cosine_sim_tresillo, dtype: float64\n mean Tresillo-ness in the test set: 0.6217641548092555\n tresillo upper and lower ci on 100 draws: 0.5792063648094466 0.6717705312519476\n\n\nAlready looking at the means of the two samples and their confidence intervalls, they seem to be significantly different. \nHowever let's also calculate the t-test statistics to ensure that the distributions are actually different.\n\n\n```python\nttest_pvalue = stats.ttest_ind(tresillo_test_set_vectors['cosine_sim_tresillo'], non_tresillio_vectors['cosine_sim_tresillo']).pvalue\nprint('p value that the means are the same: ', ttest_pvalue)\n```\n\n p value that the means are the same: 0.009618772484088895\n\n\n**Discussion:** \nLooking at the the Tresillio cosine similarity metrics of both data sets and comparing the distributions of the means whit each others (confidence intervals and t-test), we see that their mean Tresillo-ness is indeed significantly diffferent. \nHowever, we also see that 1) this Tresillo-ness measurement seems to be quite noisy 2) The distribution of the two samples are not as far apart as we would like them to be. \nThe noisiness of this metric, can be especially seen, if one looks at the individual cosine Tresillo-ness values of the songs. Here we see that there is great variance in Tresillo-ness in the hand selected Tresillo data set. Values can be as small as 0.6, which corresponds to the value of a none Tresillo song. \nFurthermore, it seems that also songs wich we classified to have no Tresillo, have a cosine Tresillo-ness up to 0.72. \nIn general we can state that the cosine similarity methods seems to identify a ceratin Tresillo-ness, however it is questionable how robust this method is.\n\n### 3.3) Tresilio-ness over Time\n\nNow that we explored several ways to compute Tresillo-ness, we can calculate the Tresilo-ness of ou billboard data set. \nFirst let us load the rhythm vectors of our billboard songs and let's also merge it to the metadata of the billboard songs. \nThe metadata of the billboard songs includes time signatures with which we can Tresillo-ness over time.\n\n\n```python\ndf_billboard = pd.read_csv(home_dir + '/dataset/rythm_vectors/rythm_vectors_billboard.csv')\ndf_billboard_meta = pd.read_csv(home_dir + '/dataset/billboard_data_sets/billboard_1999-2019_unique_top_20_selection.csv')\n\n#calculate cosine simularity\ndf_billboard = collapse_normalize_vectors(df_billboard)\ndf_billboard_sim = calc_cosine_sim(df_billboard, vector_vanilla_tresillo)\n\n#prepare for merge with meta data\ndf_billboard_sim['song_artist'] = df_billboard_sim.index\ndf_billboard_sim['song'] = df_billboard_sim.song_artist.apply(lambda x: x.split('_')[0])\ndf_billboard_sim['artist'] = df_billboard_sim.song_artist.apply(lambda x: x.split('_')[1][:-1])\ndf_billboard_sim = df_billboard_sim.drop(['song_artist'], axis=1)\n\n#merge data frames\ndf_billboard_merged = df_billboard_sim.merge(df_billboard_meta, left_on=['song','artist'], right_on=['Name', 'Artists'], how='left')\ndf_billboard_reduced = df_bilboard_merged[['Name', 'Artists', 'Peak.position', 'Week', 'Genre', 'cosine_sim_tresillo']]\n#let's look at some songs with very high tresillo-ness\ndf_billboard_reduced[df_billboard_reduced['cosine_sim_tresillo']>0.85]\n\n```\n\n\n\n\n
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
NameArtistsPeak.positionWeekGenrecosine_sim_tresillo
89Cheap ThrillsSia19.02016-06-18Jamaica,Remix,Australia,Rap,Synth-Pop,Pop0.908945
293Rather BeClean Bandit19.02014-08-08Electro-Pop,Deep House,Eurodance,Dance-Pop,Cla...0.861075
319Shape Of YouEd Sheeran1.02017-01-28Tropical House,Dancehall,Pop,UK0.915565
387Treat You BetterShawn Mendes20.02016-07-30Canada,Pop0.883772
389Turn Me OnKevin Lyttle20.02004-06-23Pop0.937243
423Where Have You BeenRihanna18.02012-05-25House,Electro-Pop,Pop0.947448
\n
\n\n\n\nLet's plot weekly cosine Tresillo-ness \n\n\n```python\ndf_bilboard_merged_weekly = df_bilboard_merged.groupby(['Week'])['cosine_sim_tresillo'].agg(['mean']).reset_index()\nplt.plot(pd.to_datetime(df_bilboard_merged_weekly.Week), df_bilboard_merged_weekly['mean'])\nplt.title('Weekly Cosine Tresillo-ness in the Top 20 Billboards')\nplt.xlabel('Time')\nplt.ylabel('Cosine Tresillo-ness')\n```\n\nThe time trend above is very noisy and hard to read. By calculating a 4 weeks moveing average we might get smoother results.\n\n\n```python\ndf_bilboard_merged_weekly['rolling_mean'] = df_bilboard_merged_weekly.iloc[:,1].rolling(window=4).mean()\n\nplt.plot(pd.to_datetime(df_bilboard_merged_weekly.Week), df_bilboard_merged_weekly['rolling_mean'])\nplt.title('4 Weeks Moving Average Cosine Tresillo-ness in the Top 20 Billboards')\nplt.xlabel('Time')\nplt.ylabel('Cosine Tresillo-ness')\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n**TA instructions**: \n- Present your results in relation to your research question.\n- Present them in a logical order that does not have to be the order in which you achieved them.\n\n**Thoughts Aurel:** \n\n 4. Discussion of the clustering method, either k-mean clustering or something we dont have to set the cluster number\n 5. Finding Tresillio-ness in the pop charts with all three methods a) Vanilla Tresillio-ness b) Tresillio songs vector c) \n \n \n\n## 4) Outlook on final interpretation\n\nPoints to discuss as stated by TAs: \n- Interpreting your results is the final step that you will do in preparing Milestone 4 (your presentations). Please end your submission by giving a first,preliminary outlook on this final step: what aspects of your results do you find interesting with respect to your hypotheses and previous literature? What do you think might be the main points to elaborate upon in the discussion? \n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## References\n\n- Chin, F. and Wu, S. (1992). An efficient algorithm for rhythm-finding.Computer MusicJournal, 16(2):35–44.\n- Dixon, S., Gouyon, F., Widmer, G., et al. (2004). Towards characterisation of music viarhythmic patterns. InISMIR.\n- Huron, D. and Ommen, A. (2006). An empirical study of syncopation in american popularmusic, 1890–1939.Music Theory Spectrum, 28(2):211–231.\n- Palmer, C. and Krumhansl, C. L. (1990). Mental representations for musical meter.Journalof Experimental Psychology: Human Perception and Performance, 16(4):728.\n- Panteli, M., Bogaards, N., Honingh, A. K., et al. (2014). Modeling rhythm similarity forelectronic dance music. InISMIR, pages 537–542.\n- Parry, M. and Essa, I. (2003). Rhythmic similarity through elaboration.\n- Pohle, T., Schnitzer, D., Schedl, M., Knees, P., and Widmer, G. (2009). On rhythm andgeneral music similarity. InISMIR, pages 525–530. \n- Rohrmeier, M. (2020). Towards a formalization of musical rhythm. InProc. of the 21st Int.Society for Music Information Retrieval Conf\n- Floyd, Samuel A. \"Black music in the circum-Caribbean.\" American Music (1999): 1-38.\n\n\n```python\n\n```\n", "meta": {"hexsha": "6ba0b94b40496795ef038808790a6eedf09951c4", "size": 157129, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "src/milestone_3_sugessted_structure_safty copy_18.05_1500.ipynb", "max_stars_repo_name": "pushkarjajoria/Tresillo", "max_stars_repo_head_hexsha": "9b72373746192d00d82c6e9c2de19d70648108eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/milestone_3_sugessted_structure_safty copy_18.05_1500.ipynb", "max_issues_repo_name": "pushkarjajoria/Tresillo", "max_issues_repo_head_hexsha": "9b72373746192d00d82c6e9c2de19d70648108eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/milestone_3_sugessted_structure_safty copy_18.05_1500.ipynb", "max_forks_repo_name": "pushkarjajoria/Tresillo", "max_forks_repo_head_hexsha": "9b72373746192d00d82c6e9c2de19d70648108eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 115.706185567, "max_line_length": 43848, "alphanum_fraction": 0.8285930668, "converted": true, "num_tokens": 9946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.305940459699723}} {"text": "\n\n\n# Tutorial-IllinoisGRMHD: inlined_functions.C\n\n## Authors: Leo Werneck & Zach Etienne\n\n**This module is currently under development**\n\n## In this tutorial module we explain a series of inline functions that are used by major functions within IllinoisGRMHD.\n\n### Required and recommended citations:\n\n* **(Required)** Etienne, Z. B., Paschalidis, V., Haas R., Mösta P., and Shapiro, S. L. IllinoisGRMHD: an open-source, user-friendly GRMHD code for dynamical spacetimes. Class. Quantum Grav. 32 (2015) 175009. ([arxiv:1501.07276](http://arxiv.org/abs/1501.07276)).\n* **(Required)** Noble, S. C., Gammie, C. F., McKinney, J. C., Del Zanna, L. Primitive Variable Solvers for Conservative General Relativistic Magnetohydrodynamics. Astrophysical Journal, 641, 626 (2006) ([astro-ph/0512420](https://arxiv.org/abs/astro-ph/0512420)).\n* **(Recommended)** Del Zanna, L., Bucciantini N., Londrillo, P. An efficient shock-capturing central-type scheme for multidimensional relativistic flows - II. Magnetohydrodynamics. A&A 400 (2) 397-413 (2003). DOI: 10.1051/0004-6361:20021641 ([astro-ph/0210618](https://arxiv.org/abs/astro-ph/0210618)).\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis module is organized as follows\n\n0. [Step 0](#src_dir): **Source directory creation**\n1. [Step 1](#introduction): **Introduction**\n1. [Step 2](#pow): **`pow`**\n1. [Step 3](#find_cp_cm): **`find_cp_cm`**\n1. [Step 4](#compute_v02): **`compute_v02`**\n1. [Step 5](#ppeos__c_code): **Polytropic Equations of State**\n 1. [Step 5.a](#ppeos__c_code__prelim): *Preliminary treatment of the input*\n 1. [Step 5.a.i](#ppeos__c_code__prelim__computing_ktab): Determining $\\left\\{K_{1},K_{2},\\ldots,K_{\\rm neos}\\right\\}$\n 1. [Step 5.a.ii](#ppeos__c_code__prelim__computing_eps_integ_consts): Determining $\\left\\{C_{0},C_{1},C_{2},\\ldots,C_{\\rm neos}\\right\\}$\n 1. [Step 5.b](#ppeos__c_code__eos_struct_setup) *Setting up the `eos_struct`*\n 1. [Step 5.c](#ppeos__c_code__find_polytropic_k_and_gamma_index) *The `find_polytropic_K_and_Gamma_index()` function*\n 1. [Step 5.d](#ppeos__c_code__compute_P_cold__eps_cold__dPcold_drho__eps_th__h__Gamma_cold): *The new `compute_P_cold__eps_cold__dPcold_drho__eps_th__h__Gamma_cold()` function*\n 1. [Step 5.d.i](#ppeos__c_code__compute_P_cold__eps_cold__dPcold_drho__eps_th__h__Gamma_cold__case1__rhob_equal_zero): Case 1: $\\rho_{b} = 0$\n 1. [Step 5.d.ii](#ppeos__c_code__compute_P_cold__eps_cold__dPcold_drho__eps_th__h__Gamma_cold__case2__single_polytropic_eos): Case 2: Polytropic EOSs\n 1. [Step 5.e](#font_fix__rhob_loop): The `font_fix__rhob_loop()` function\n1. [Step 6](#lower_4vector_output_spatial_part): **`lower_4vector_output_spatial_part`**\n1. [Step 7](#impose_speed_limit_output_u0): **`impose_speed_limit_output_u0`**\n1. [Step 8](#enforce_pressure_floor_ceiling): **`enforce_pressure_floor_ceiling`**\n1. [Step 9](#compute_smallba_b2_and_u_i_over_u0_psi4): **`compute_smallba_b2_and_u_i_over_u0_psi4`**\n1. [Step 11](#code_validation): **Code validation**\n1. [Step 12](#latex_pdf_output): **Output this notebook to $\\LaTeX$-formatted PDF file**\n\n\n\n# Step 0: Source directory creation \\[Back to [top](#toc)\\]\n$$\\label{src_dir}$$\n\nWe will now use the [cmdline_helper.py NRPy+ module](Tutorial-Tutorial-cmdline_helper.ipynb) to create the source directory within the `IllinoisGRMHD` NRPy+ directory, if it does not exist yet.\n\n\n```python\n# Step 0: Creation of the IllinoisGRMHD source directory\n# Step 0a: Add NRPy's directory to the path\n# https://stackoverflow.com/questions/16780014/import-file-from-parent-directory\nimport os,sys\nnrpy_dir_path = os.path.join(\"..\",\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Step 0b: Load up cmdline_helper and create the directory\nimport cmdline_helper as cmd\nIGM_src_dir_path = os.path.join(\"..\",\"src\")\ncmd.mkdir(IGM_src_dir_path)\n\n# Step 0c: Create the output file path\noutfile_path__inlined_functions__C = os.path.join(IGM_src_dir_path,\"inlined_functions.C\")\n```\n\n\n\n# Step 1: Introduction \\[Back to [top](#toc)\\]\n$$\\label{introduction}$$\n\nIn this tutorial notebook we explain functions of `IllinoisGRMHD` which are called for various purposes. This means that this notebook does not have a specific \"theme\". We will cover functions whose purposes vary from a simple optimization when squaring numbers to computing minimum and maximum characteristic speeds at cell interfaces.\n\nWe have tried our best to keep this tutorial module as independent from the others as possible. When new concepts appear, we offer useful references. The mathematical requirements of each function are also covered in great detailed.\n\n\n\n# Step 2: `pow` \\[Back to [top](#toc)\\]\n$$\\label{pow}$$\n\nThis is an extremely simple function which simply checks whether or not we are trying to square a number before calling C's `pow()` function. This is because in C it is computationally quicker to do `x*x` than to use the function call `pow(x,2)`. Notice that we also use the \"function\" `SQR()`, which is declared in `IllinoisGRMHD_headers.h`, which is defined as\n\n```c\n#define SQR(x) ( (x) * (x) )\n```\n\n\n\n# Step 3: `find_cp_cm` \\[Back to [top](#toc)\\]\n$$\\label{find_cp_cm}$$\n\nWe will now explain the inlined function `find_cp_cm`. Keep in mind that this function depend on the function `compute_v02`, [which is implemented below](#compute_v02). This function is called with the objective of computing the minimum ($-$) and maximum ($+$) characteristic speeds at each cell interface, $c_{\\pm}^{r,l}$.\n\nWe approximate the general GRMHD dispersion relation (eq. 27 of [Gammie & McKinney (2003)](https://arxiv.org/pdf/astro-ph/0301509.pdf)) by the simpler expression\n\n$$\n\\omega_{\\rm cm}^{2} = \\left[v_{\\rm A}^{2} + c_{\\rm s}^{2}\\left(1-v_{\\rm A}^{2}\\right)\\right]k_{\\rm cm}^{2}\\ ,\n$$\n\nwhere $\\omega_{\\rm cm}=-k_{\\mu}u^{\\mu}$ is the frequency and $k_{\\rm cm}^{2} = K_{\\mu}K^{\\mu}$ the wavenumber of an MHD wave mode in the frame comoving with the fluid, where $K_{\\mu}$ is defined as the projection of the wave vector $k^{\\nu}$ onto the direction normal to $u^{\\nu}$: $K_{\\mu} = \\left(g_{\\mu\\nu}+u_{\\mu}u_{\\nu}\\right)k^{\\nu}$. $c_{\\rm s}$ is the sound speed, and $v_{\\rm A}$ is the Alfvén speed, given by\n\n$$\nv_{\\rm A} = \\sqrt{\\frac{b^{2}}{\\rho_{b}h + b^{2}}}\\ .\n$$\n\nWith these definitions, we may then solve the approximate dispersion relation above along direction $i$, noting that in the comoving frame $k_{\\mu} = \\left(-\\omega,k_{j}\\delta^{j}_{\\ i}\\right)$ and the wave (phase) velocity is $c_{\\pm} = \\left.\\omega\\middle/\\left(k_{j}\\delta^{j}_{\\ i}\\right)\\right.$. The dispersion can then be written as a quadratic equation for $c_{\\pm}$:\n\n$$\nac_{\\pm}^{2} + bc_{\\pm} + c = 0\\ ,\n$$\n\nwith\n\n$$\n\\boxed{\n\\begin{align}\na &= \\left(1-v_{0}^{2}\\right)\\left(u^{0}\\right)^{2} - v_{0}^{2}g^{00}\\ ,\\\\\nb &= 2v_{0}^{2}g^{i0} - 2u^{i}u^{0}\\left(1-v^{2}_{0}\\right)\\ ,\\\\\nc &= \\left(1-v_{0}^{2}\\right)\\left(u^{i}\\right)^{2} - v_{0}^{2}g^{ii}\\ ,\\\\\nv_{0}^{2} &= v_{\\rm A}^{2} + c_{\\rm s}^{2}\\left(1-v_{\\rm A}^{2}\\right)\\ ,\\\\\nc_{\\rm s} &= \\left.\\left[\\frac{dP_{\\rm cold}}{d\\rho_{b}} + \\Gamma_{\\rm th}\\left(\\Gamma_{\\rm th}-1\\right)\\epsilon_{\\rm th}\\right]\\middle/h\\right.\\ ,\\\\\nc_{+} &= \\max\\left(\\frac{-b \\pm \\sqrt{b^{2}-4ac}}{2a}\\right)\\ ,\\\\\nc_{-} &= \\min\\left(\\frac{-b \\pm \\sqrt{b^{2}-4ac}}{2a}\\right)\\ .\n\\end{align}\n}\n$$\n\nFor the implementation of $v_{0}^{2}$, please see [Step 4 below](#compute_v02).\n\n\n```python\n%%writefile $outfile_path__inlined_functions__C\n\n\nstatic inline void find_cp_cm(CCTK_REAL &cplus,CCTK_REAL &cminus,CCTK_REAL v02,CCTK_REAL u0,\n CCTK_REAL vi,CCTK_REAL ONE_OVER_LAPSE_SQUARED,CCTK_REAL shifti,CCTK_REAL psim4,CCTK_REAL gupii) {\n // This computes phase speeds in the direction given by flux_dirn.\n // Note that we replace the full dispersion relation with a simpler\n // one, which overestimates the max. speeds by a factor of ~2.\n // See full discussion around Eqs. 49 and 50 in\n // http://arxiv.org/pdf/astro-ph/0503420.pdf .\n // What follows is a complete derivation of the quadratic we solve.\n // wcm = (-k_0 u0 - k_x ux)\n // kcm^2 = K_{\\mu} K^{\\mu},\n // K_{\\mu} K^{\\mu} = (g_{\\mu a} + u_{\\mu} u_a) k^a * g^{\\mu b} [ (g_{c b} + u_c u_b) k^c ]\n // --> g^{\\mu b} (g_{c b} + u_{c} u_{b}) k^c = (\\delta^{\\mu}_c + u_c u^{\\mu} ) k^c\n // = (g_{\\mu a} + u_{\\mu} u_a) k^a * (\\delta^{\\mu}_c + u_c u^{\\mu} ) k^c\n // =[(g_{\\mu a} + u_{\\mu} u_a) \\delta^{\\mu}_c + (g_{\\mu a} + u_{\\mu} u_a) u_c u^{\\mu} ] k^c k^a\n // =[(g_{c a} + u_c u_a) + (u_c u_a - u_a u_c] k^c k^a\n // =(g_{c a} + u_c u_a) k^c k^a\n // = k_a k^a + u^c u^a k_c k_a\n // k^a = g^{\\mu a} k_{\\mu} = g^{0 a} k_0 + g^{x a} k_x\n // k_a k^a = k_0 g^{0 0} k_0 + k_x k_0 g^{0 x} + g^{x 0} k_0 k_x + g^{x x} k_x k_x\n // = g^{00} (k_0)^2 + 2 g^{x0} k_0 k_x + g^{xx} (k_x)^2\n // u^c u^a k_c k_a = (u^0 k_0 + u^x k_x) (u^0 k_0 + u^x k_x) = (u^0 k_0)^2 + 2 u^x k_x u^0 k_0 + (u^x k_x)^2\n // (k_0 u0)^2 + 2 k_x ux k_0 u0 + (k_x ux)^2 = v02 [ (u^0 k_0)^2 + 2 u^x k_x u^0 k_0 + (u^x k_x)^2 + g^{00} (k_0)^2 + 2 g^{x0} k_0 k_x + g^{xx} (k_x)^2]\n // (1-v02) (u^0 k_0 + u^x k_x)^2 = v02 (g^{00} (k_0)^2 + 2 g^{x0} k_0 k_x + g^{xx} (k_x)^2)\n // (1-v02) (u^0 k_0/k_x + u^x)^2 = v02 (g^{00} (k_0/k_x)^2 + 2 g^{x0} k_0/k_x + g^{xx})\n // (1-v02) (u^0 X + u^x)^2 = v02 (g^{00} X^2 + 2 g^{x0} X + g^{xx})\n // (1-v02) (u0^2 X^2 + 2 ux u0 X + ux^2) = v02 (g^{00} X^2 + 2 g^{x0} X + g^{xx})\n // X^2 ( (1-v02) u0^2 - v02 g^{00}) + X (2 ux u0 (1-v02) - 2 v02 g^{x0}) + (1-v02) ux^2 - v02 g^{xx}\n // a = (1-v02) u0^2 - v02 g^{00} = (1-v02) u0^2 + v02/lapse^2 <-- VERIFIED\n // b = 2 ux u0 (1-v02) - 2 v02 shiftx/lapse^2 <-- VERIFIED, X->-X, because X = -w/k_1, and we are solving for -X.\n // c = (1-v02) ux^2 - v02 (gupxx*psim4 - (shiftx/lapse)^2) <-- VERIFIED\n // v02 = v_A^2 + c_s^2 (1 - v_A^2)\n CCTK_REAL u0_SQUARED=SQR(u0);\n```\n\n Writing ../src/inlined_functions.C\n\n\nWe start by setting\n\n$$\n\\boxed{\n\\begin{align}\na &= \\left(1-v_{0}^{2}\\right)\\left(u^{0}\\right)^{2} - v_{0}^{2}g^{00}\\\\\nb &= 2v_{0}^{2}g^{i0} - 2u^{i}u^{0}\\left(1-v^{2}_{0}\\right)\\\\\nc &= \\left(1-v_{0}^{2}\\right)\\left(u^{i}\\right)^{2} - v_{0}^{2}g^{ii}\n\\end{align}\n}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\n //Find cplus, cminus:\n CCTK_REAL a = u0_SQUARED * (1.0-v02) + v02*ONE_OVER_LAPSE_SQUARED;\n CCTK_REAL b = 2.0* ( shifti*ONE_OVER_LAPSE_SQUARED * v02 - u0_SQUARED * vi * (1.0-v02) );\n CCTK_REAL c = u0_SQUARED*SQR(vi) * (1.0-v02) - v02 * ( psim4*gupii -\n SQR(shifti)*ONE_OVER_LAPSE_SQUARED);\n```\n\n Appending to ../src/inlined_functions.C\n\n\nThen we find the minimum ($-$) and maximum ($+$) characteristic speeds\n\n$$\n\\boxed{\n\\begin{align}\nc_{+} &= \\max\\left(\\frac{-b \\pm \\sqrt{b^{2}-4ac}}{2a}\\right)\\ ,\\\\\nc_{-} &= \\min\\left(\\frac{-b \\pm \\sqrt{b^{2}-4ac}}{2a}\\right)\\ .\n\\end{align}\n}\n$$\n\n\n```python\n%%writefile -a $IGM_src_dir_path/inlined_functions.C\n\n CCTK_REAL detm = b*b - 4.0*a*c;\n //ORIGINAL LINE OF CODE:\n //if(detm < 0.0) detm = 0.0;\n //New line of code (without the if() statement) has the same effect:\n detm = sqrt(0.5*(detm + fabs(detm))); /* Based on very nice suggestion from Roland Haas */\n\n cplus = 0.5*(detm-b)/a;\n cminus = -0.5*(detm+b)/a;\n if (cplus < cminus) {\n CCTK_REAL cp = cminus;\n cminus = cplus;\n cplus = cp;\n }\n}\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n# Step 4: `compute_v02` \\[Back to [top](#toc)\\]\n$$\\label{compute_v02}$$\n\nThis function is used to evaluate $v_{0}^{2}$, a quantity necessary for the computation of the minimum and maximum characteristic speeds at each cell interface, $c_{\\pm}^{r,l}$. For more information on this procedure, please see the [implementation of the `find_cp_cm` function in Step 3](#find_cp_cm).\n\nWe start with the sound speed:\n\n$$\n\\boxed{\nc_{\\rm s} = \\left.\\left[\\frac{dP_{\\rm cold}}{d\\rho_{b}} + \\Gamma_{\\rm th}\\left(\\Gamma_{\\rm th}-1\\right)\\epsilon_{\\rm th}\\right]\\middle/h\\right.\n}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\nstatic inline void compute_v02(CCTK_REAL dPcold_drho,CCTK_REAL Gamma_th,CCTK_REAL eps_th,CCTK_REAL h,CCTK_REAL *smallb,CCTK_REAL *U, CCTK_REAL &v02L) {\n\n if(U[RHOB]<=0) { v02L=1.0; return; }\n\n /* c_s = sound speed = (dP_c/drho + \\Gamma(\\Gamma-1) \\epsilon_th)/h */\n CCTK_REAL c_s_squared = (dPcold_drho + Gamma_th*(Gamma_th-1.0)*eps_th)/(h);\n```\n\n Appending to ../src/inlined_functions.C\n\n\nNext we compute the square of the Alfén speed, $v_{\\rm A}$, which is given by\n\n$$\n\\boxed{v_{\\rm A}^{2} = \\frac{b^{2}}{\\rho_{b}h + b^{2}}}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n /* v_A = Alfven speed = sqrt( b^2/(rho0 h + b^2) ) */\n CCTK_REAL v_A_squared = smallb[SMALLB2]/(smallb[SMALLB2] + U[RHOB]*(h));\n```\n\n Appending to ../src/inlined_functions.C\n\n\nFinally, $v_{0}$ is related to the sound speed and the Alfén speed via\n\n$$\n\\boxed{v_{0}^{2} = v_{\\rm A}^{2} + c_{\\rm s}^{2}\\left(1-v_{\\rm A}^{2}\\right)}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n v02L = v_A_squared + c_s_squared*(1.0-v_A_squared);\n}\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n## Step 5.e: The `font_fix__rhob_loop()` function \\[Back to [top](#toc)\\]\n$$\\label{font_fix__rhob_loop}$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n/* Function : font_fix__rhob_loop()\n * Authors : Leo Werneck\n * Description : Determines rhob using the font fix prescription\n * Dependencies: find_polytropic_K_and_Gamma_index()\n * : compute_P_cold__eps_cold()\n * Reference : Etienne et al. (2011) [https://arxiv.org/pdf/1112.0568.pdf]\n *\n * Inputs : maxits - maximum number of iterations allowed\n * : tol - font fix tolerance\n * : W - See eq. (A26)\n * : Sf2 - S_{fluid}^{2}, see eq. (A24)\n * : Psim6 - This is equal to sqrt(\\gamma)\n * : sdots - \\tilde{S}_{\\mu}\\tilde{S}^{\\mu}\n * : BbardotS2 - (\\bar{B}^{\\mu}S_{\\mu})^{2},\n * : B2bar - \\bar{B}^{2}, see eq. (A28)\n * : CONSERVS - Array of conservative variables\n * : eos - Struct of EOS parameters\n * : rhob_in - Initial value of rhob\n * : rhob_out - Output variable\n *\n * Outputs : rhob_out - Updated value of rhob\n * : return value: 0 - Font fix worked\n * : return value: 1 - Font fix failed\n */\ninline int font_fix__rhob_loop( int maxits, CCTK_REAL tol,\n CCTK_REAL W, CCTK_REAL Sf2, CCTK_REAL Psim6, CCTK_REAL sdots, CCTK_REAL BbardotS2, CCTK_REAL B2bar,\n CCTK_REAL *CONSERVS,\n eos_struct eos, CCTK_REAL rhob_in, CCTK_REAL &rhob_out ) {\n\n /* Declare basic variables */\n bool fontcheck=true;\n int itcount = 0, j0, j1;\n CCTK_REAL W0, Sf20, rhob0, rhob1, h, P_cold, eps_cold;\n\n //////////////////////\n // OUTER LOOP START //\n //////////////////////\n while(fontcheck && itcount < maxits) {\n\n /* Set variables to their input values */\n itcount++;\n W0 = W;\n Sf20 = Sf2;\n rhob1 = rhob_in;\n\n /* Based on rhob_in (i.e. rhob1), determine the\n * polytropic index j1\n */\n j1 = find_polytropic_K_and_Gamma_index(eos,rhob1);\n\n //////////////////////\n // INNER LOOP START //\n //////////////////////\n do {\n\n /* Set rhob0/j0 to be equal to the rhob/j used\n * in the previous iteration, i.e. rhob1/j1.\n */\n rhob0 = rhob1;\n j0 = j1;\n\n /* Compute h using h_cold and our polytropic EOS\n * .------------------------------------------.\n * | h = h_cold = 1 + eps_cold + P_cold/rhob. |\n * .------------------------------------------.\n */\n compute_P_cold__eps_cold(eos,rhob0, P_cold, eps_cold);\n h = 1.0 + eps_cold + P_cold/rhob0;\n\n /* Update rhob using eq. (A62) in Etienne et al. (2011)\n * https://arxiv.org/pdf/1112.0568.pdf\n * .---------------------------------------------------------------------------.\n * | rhob = rho_star * Psi^{-6} / sqrt( 1 + S_fluid^{2}/( (rho_star*h)^{2} ) ) |\n * .---------------------------------------------------------------------------.\n */\n rhob1 = CONSERVS[RHOSTAR]*Psim6/sqrt(1.0+Sf20/SQR(CONSERVS[RHOSTAR]*h));\n\n /* Update j1 */\n j1 = find_polytropic_K_and_Gamma_index(eos,rhob1);\n\n } while( fabs(rhob1-rhob0) > rhob1*tol || j1 != j0);\n //////////////////////\n // INNER LOOP END //\n //////////////////////\n\n /* Output the last value of rhob */\n rhob_out = rhob1;\n\n /* Perform physical checks on the variables\n * and output the last value of h obtained\n */\n compute_P_cold__eps_cold(eos,rhob_out, P_cold, eps_cold);\n h = 1.0 + eps_cold + P_cold/rhob_out;\n\n /* Set W based on eq. (A60) in Etienne et al. (2011)\n * https://arxiv.org/pdf/1112.0568.pdf\n * .-------------------------------------------------------.\n * | W = psi^{-6} * sqrt( S_fluid^{2} + (rho_star*h)^{2} ) |\n * .-------------------------------------------------------.\n */\n W = sqrt( Sf20 + SQR(CONSERVS[RHOSTAR]*h))*Psim6;\n\n /* Then update S_{fluid}^{2} using eq. (A61) in Etienne et al. (2011)\n * https://arxiv.org/pdf/1112.0568.pdf\n * .---------------------------------------------------------------------------.\n * | S_fluid^{2} = ( W^{2}*S^{2} + (B.S)^2*(B^{2} + 2W) )/( ( W + B^{2} )^{2} )|\n * .---------------------------------------------------------------------------.\n */\n Sf2 = (SQR(W)*sdots + BbardotS2*(B2bar + 2.0*W))/SQR(W+B2bar);\n\n if ( fabs(W-W0) < W*tol && fabs(Sf20-Sf2) < Sf2*tol) fontcheck=false;\n\n }\n //////////////////////\n // OUTER LOOP END //\n //////////////////////\n\n /* If the code converged before the max\n * number of iterations were exceeded,\n * return 0, otherwise return 1.\n */\n if(fontcheck || itcount >= maxits) {\n return 1;\n }\n else {\n return 0;\n }\n}\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n# Step 6: `lower_4vector_output_spatial_part` \\[Back to [top](#toc)\\]\n$$\\label{lower_4vector_output_spatial_part}$$\n\nThis function is used to lower the indices of the spatial components of 4-vectors, $b^{\\mu}$. Consider\n\n$$\n\\begin{align}\nb_{i} &= g_{i\\mu}b^{\\mu} \\\\\n &= g_{i0}b^{0} + g_{ij}b^{j} \\\\\n &= \\left(\\gamma_{ij}\\beta^{j}\\right)b^{0} + \\gamma_{ij}b^{j} \\\\\n &= \\gamma_{ij}\\left(b^{j} + \\beta^{j}b^{0}\\right)\\ ,\n\\end{align}\n$$\n\nor, using the conformal metric and each component seperately\n\n$$\n\\boxed{\n\\begin{align}\nb_{x} &= \\psi^{4}\\left[\\bar{\\gamma}_{xx}\\left(b^{x} + \\beta^{x}b^{0}\\right)+\\bar{\\gamma}_{xy}\\left(b^{y} + \\beta^{y}b^{0}\\right)+\\bar{\\gamma}_{xz}\\left(b^{z} + \\beta^{z}b^{0}\\right)\\right]\\\\\nb_{y} &= \\psi^{4}\\left[\\bar{\\gamma}_{yx}\\left(b^{x} + \\beta^{x}b^{0}\\right)+\\bar{\\gamma}_{yy}\\left(b^{y} + \\beta^{y}b^{0}\\right)+\\bar{\\gamma}_{yz}\\left(b^{z} + \\beta^{z}b^{0}\\right)\\right]\\\\\nb_{z} &= \\psi^{4}\\left[\\bar{\\gamma}_{zx}\\left(b^{x} + \\beta^{x}b^{0}\\right)+\\bar{\\gamma}_{zy}\\left(b^{y} + \\beta^{y}b^{0}\\right)+\\bar{\\gamma}_{zz}\\left(b^{z} + \\beta^{z}b^{0}\\right)\\right]\n\\end{align}\n}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\n// b_x = g_{\\mu x} b^{\\mu}\n// = g_{t x} b^t + g_{i x} b^i\n// = b^t gamma_{xj} beta^j + gamma_{ix} b^i\n// = gamma_{xj} (b^j + beta^j b^t)\nstatic inline void lower_4vector_output_spatial_part(CCTK_REAL psi4,CCTK_REAL *METRIC,CCTK_REAL *smallb, CCTK_REAL *smallb_lower) {\n smallb_lower[SMALLBX] = psi4*( METRIC[GXX]*(smallb[SMALLBX]+smallb[SMALLBT]*METRIC[SHIFTX]) + METRIC[GXY]*(smallb[SMALLBY]+smallb[SMALLBT]*METRIC[SHIFTY]) +\n METRIC[GXZ]*(smallb[SMALLBZ]+smallb[SMALLBT]*METRIC[SHIFTZ]) );\n smallb_lower[SMALLBY] = psi4*( METRIC[GXY]*(smallb[SMALLBX]+smallb[SMALLBT]*METRIC[SHIFTX]) + METRIC[GYY]*(smallb[SMALLBY]+smallb[SMALLBT]*METRIC[SHIFTY]) +\n METRIC[GYZ]*(smallb[SMALLBZ]+smallb[SMALLBT]*METRIC[SHIFTZ]) );\n smallb_lower[SMALLBZ] = psi4*( METRIC[GXZ]*(smallb[SMALLBX]+smallb[SMALLBT]*METRIC[SHIFTX]) + METRIC[GYZ]*(smallb[SMALLBY]+smallb[SMALLBT]*METRIC[SHIFTY]) +\n METRIC[GZZ]*(smallb[SMALLBZ]+smallb[SMALLBT]*METRIC[SHIFTZ]) );\n}\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n# Step 7: `impose_speed_limit_output_u0` \\[Back to [top](#toc)\\]\n$$\\label{impose_speed_limit_output_u0}$$\n\nWe now call upon the `impose_speed_limit_output_u0()` function inside the `inlined_functions.C` code file of `IllinoisGRMHD`. The basic algorithm performed by this function is summarized here. We start by evaluating the quantity\n\n$$\n\\begin{align}\n{\\rm one\\_minus\\_one\\_over\\_alpha\\_u0\\_squared} \\equiv A \n&= \\gamma_{ij}\\left(\\frac{v^{i}+\\beta^{i}}{\\alpha}\\right)\\left(\\frac{v^{j}+\\beta^{j}}{\\alpha}\\right)\\\\\n&= \\frac{\\gamma_{ij}}{\\alpha^{2}}\\left[\\frac{\\gamma^{ik}u_{k}}{u^{0}} - \\beta^{i} + \\beta^{i}\\right]\\left[\\frac{\\gamma^{j\\ell}u_{\\ell}}{u^{0}} - \\beta^{j} + \\beta^{j}\\right]\\\\\n&=\\frac{\\gamma_{ij}u^{i}u^{j}}{\\left(\\alpha u^{0}\\right)^{2}}\\\\\n&=\\frac{\\left(\\alpha u^{0}\\right)^{2}-1}{\\left(\\alpha u^{0}\\right)^{2}}\\\\\n&=1 - \\frac{1}{\\left(\\alpha u^{0}\\right)^{2}}\\ \\\\\n\\implies \\boxed{A = 1 - \\frac{1}{\\left(\\alpha u^{0}\\right)^{2}}}\\ ,\n\\end{align}\n$$\n\nwhere when going from line 1 to 2 and from line 3 to 4 we have used eqs. (53) and (56) from [Duez *et al.*](https://arxiv.org/pdf/astro-ph/0503420.pdf), respectively. Keep in mind that the equation we are going to implement below is\n\n$$\n\\boxed{{\\rm one\\_minus\\_one\\_over\\_alpha\\_u0\\_squared} = \\gamma_{ij}\\left(\\frac{v^{i}+\\beta^{i}}{\\alpha}\\right)\\left(\\frac{v^{j}+\\beta^{j}}{\\alpha}\\right)}\\ ,\n$$\n\nbut it is important to know that this equation also equals $A$ above.\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\nstatic inline void impose_speed_limit_output_u0(CCTK_REAL *METRIC,CCTK_REAL *U,CCTK_REAL psi4,CCTK_REAL ONE_OVER_LAPSE,output_stats &stats, CCTK_REAL &u0_out) {\n\n#ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n DECLARE_CCTK_PARAMETERS;\n#endif\n\n\n // Derivation of first equation:\n // \\gamma_{ij} (v^i + \\beta^i)(v^j + \\beta^j)/(\\alpha)^2\n // = \\gamma_{ij} 1/(u^0)^2 ( \\gamma^{ik} u_k \\gamma^{jl} u_l /(\\alpha)^2 <- Using Eq. 53 of arXiv:astro-ph/0503420\n // = 1/(u^0 \\alpha)^2 u_j u_l \\gamma^{jl} <- Since \\gamma_{ij} \\gamma^{ik} = \\delta^k_j\n // = 1/(u^0 \\alpha)^2 ( (u^0 \\alpha)^2 - 1 ) <- Using Eq. 56 of arXiv:astro-ph/0503420\n // = 1 - 1/(u^0 \\alpha)^2 <= 1\n CCTK_REAL one_minus_one_over_alpha_u0_squared = psi4*(METRIC[GXX]* SQR(U[VX] + METRIC[SHIFTX]) +\n 2.0*METRIC[GXY]*(U[VX] + METRIC[SHIFTX])*(U[VY] + METRIC[SHIFTY]) +\n 2.0*METRIC[GXZ]*(U[VX] + METRIC[SHIFTX])*(U[VZ] + METRIC[SHIFTZ]) +\n METRIC[GYY]* SQR(U[VY] + METRIC[SHIFTY]) +\n 2.0*METRIC[GYZ]*(U[VY] + METRIC[SHIFTY])*(U[VZ] + METRIC[SHIFTZ]) +\n METRIC[GZZ]* SQR(U[VZ] + METRIC[SHIFTZ]) )*SQR(ONE_OVER_LAPSE);\n```\n\n Appending to ../src/inlined_functions.C\n\n\nThen we construct the \"speed limit quantity\"\n\n$$\n{\\rm ONE\\_MINUS\\_ONE\\_OVER\\_GAMMA\\_SPEED\\_LIMIT\\_SQUARED} \\equiv B = 1-\\frac{1}{\\gamma^{2}_{\\rm speed\\ limit}}\\ .\n$$\n\nIf $A > B$, then we construct the correction factor $C\\equiv A / B$, and adjust the velocities using\n\n$$\n\\boxed{v^{i} \\to \\left(v^{i}+\\beta^{i}\\right)C - \\beta^{i}}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\n /*** Limit velocity to GAMMA_SPEED_LIMIT ***/\n const CCTK_REAL ONE_MINUS_ONE_OVER_GAMMA_SPEED_LIMIT_SQUARED = 1.0-1.0/SQR(GAMMA_SPEED_LIMIT);\n if(one_minus_one_over_alpha_u0_squared > ONE_MINUS_ONE_OVER_GAMMA_SPEED_LIMIT_SQUARED) {\n CCTK_REAL correction_fac = sqrt(ONE_MINUS_ONE_OVER_GAMMA_SPEED_LIMIT_SQUARED/one_minus_one_over_alpha_u0_squared);\n U[VX] = (U[VX] + METRIC[SHIFTX])*correction_fac-METRIC[SHIFTX];\n U[VY] = (U[VY] + METRIC[SHIFTY])*correction_fac-METRIC[SHIFTY];\n U[VZ] = (U[VZ] + METRIC[SHIFTZ])*correction_fac-METRIC[SHIFTZ];\n one_minus_one_over_alpha_u0_squared=ONE_MINUS_ONE_OVER_GAMMA_SPEED_LIMIT_SQUARED;\n stats.failure_checker+=1000;\n }\n```\n\n Appending to ../src/inlined_functions.C\n\n\nFinally, since $A$ is evaluated using the first line above, namely\n\n$$\n\\gamma_{ij}\\left(\\frac{v^{i}+\\beta^{i}}{\\alpha}\\right)\\left(\\frac{v^{j}+\\beta^{j}}{\\alpha}\\right) = A = 1 - \\frac{1}{\\left(\\alpha u^{0}\\right)^{2}}\\ ,\n$$\n\nwe can then compute $u_{0}$ by simply doing\n\n$$\n\\boxed{u^{0} = \\frac{1}{\\alpha\\sqrt{1-A}}}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\n // A = 1.0-one_minus_one_over_alpha_u0_squared = 1-(1-1/(al u0)^2) = 1/(al u0)^2\n // 1/sqrt(A) = al u0\n //CCTK_REAL alpha_u0_minus_one = 1.0/sqrt(1.0-one_minus_one_over_alpha_u0_squared)-1.0;\n //u0_out = (alpha_u0_minus_one + 1.0)*ONE_OVER_LAPSE;\n CCTK_REAL alpha_u0 = 1.0/sqrt(1.0-one_minus_one_over_alpha_u0_squared);\n if(std::isnan(alpha_u0*ONE_OVER_LAPSE)) printf(\"BAD FOUND NAN U0 CALC: %.15e %.15e %.15e | %.15e %.15e\\n\",alpha_u0,ONE_OVER_LAPSE,one_minus_one_over_alpha_u0_squared,psi4, U[VX]);\n u0_out = alpha_u0*ONE_OVER_LAPSE;\n}\n\n// The two lines of code below are written to reduce roundoff error and were in the above function. I don't think they reduce error.\n// one_over_alpha_u0 = sqrt(1.0-one_minus_one_over_alpha_u0_squared);\n/* Proof of following line: */\n/* [ 1-1/(alphau0)^2 ] / [ 1/(alphau0) (1 + 1/(alphau0)) ] */\n/* = [ (alphau0)^2 - 1)/((alphau0)^2) ] / [ 1/(alphau0) + 1/(alphau0)^2 ] */\n/* = [ (alphau0)^2 - 1)/((alphau0)^2) ] / [ (alphau0 + 1)/(alphau0)^2 ] */\n/* = [ (alphau0)^2 - 1) ] / [ (alphau0 + 1) ] */\n/* [ (alphau0 + 1) (alphau0 - 1) ] / [ (alphau0 + 1) ] */\n/* = alphau0 - 1 */\n//alpha_u0_minus_one = one_minus_one_over_alpha_u0_squared/one_over_alpha_u0/(1.0+one_over_alpha_u0);\n//u0_out = (alpha_u0_minus_one+1.0)*ONE_OVER_LAPSE;\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n# Step 8: `enforce_pressure_floor_ceiling` \\[Back to [top](#toc)\\]\n$$\\label{enforce_pressure_floor_ceiling}$$\n\nAfter the Newton-Raphson solver has successfully found a set of primitives, the primitives are checked for physicality, and if they are not in the physical range, they are minimally modified until they return to the physical range. First,if the velocity is found to be superluminal, the speed is reduced to `IllinoisGRMHD`’s default Lorentz factor limit, a procedure which we already explained above when we discussed the `impose_speed_limit_output_u0` function.\n\nNext, `IllinoisGRMHD` does not include any cooling mechanism, which means that for evolutions adopting a $\\Gamma$-law equation of state, the pressure should not physically drop below $P_{\\rm cold}$. So a pressure floor of $0.9P_{\\rm cold}$ is imposed. Increasing this floor to $P_{\\rm cold}$ exactly results in large central density drifts in TOV star evolutions.\n\n**NOTE**: Please keep in mind that the floor and ceiling values presented here were found ***empirically***.\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\nstatic inline void enforce_pressure_floor_ceiling(output_stats &stats,CCTK_REAL kpoly,CCTK_REAL P_cold,CCTK_REAL Psi6,const CCTK_REAL Psi6threshold,CCTK_REAL rho_b,const CCTK_REAL rhobatm, CCTK_REAL &P) {\n CCTK_REAL P_min=0.9*P_cold;\n if(P \\psi^{6}_{\\rm threshold}$, the primary goal is to keep the evolution stable and prevent inaccurate data from leaking out of the BH horizon. It was determined that in this situation, a better ceiling on $P$ is $10^{5}P_{\\rm cold}$.\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\n //CCTK_REAL P_max = 10.0*P_cold;\n CCTK_REAL P_max = 100.0*P_cold;\n if(Psi6 > Psi6threshold) P_max = 1e5*P_cold; // <-- better than 10.\n\n if((rho_b < 100.0*rhobatm || Psi6 > Psi6threshold) && P>P_max) {\n P=P_max;\n stats.failure_checker+=100;\n }\n\n /*\n CCTK_REAL rho_horiz_cap = 1000.0*rhobatm;\n\n //New density damping mechanism inside the horizon\n if(Psi6 > Psi6threshold && rho_b>rho_horiz_cap) {\n CCTK_REAL six_phi=log(Psi6);\n CCTK_REAL six_phithreshold=log(Psi6threshold);\n CCTK_REAL Psi6max_approx=350000;\n rho_b = rho_horiz_cap+(rho_b-rho_horiz_cap)*exp(-200.0*SQR((six_phi-six_phithreshold)/log(Psi6max_approx)));\n }\n */\n}\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n# Step 9: `compute_smallba_b2_and_u_i_over_u0_psi4` \\[Back to [top](#toc)\\]\n$$\\label{compute_smallba_b2_and_u_i_over_u0_psi4}$$\n\nIn this inlined function we will compute quantities related to the magnetic field measured in the comoving fluid frame, $b^{\\mu}$.\n\nWe will need the following identities\n\n$$\n\\begin{align}\nv^{i} &= \\frac{u^{i}}{u^{0}}\\ ,\\\\\nB^{0}_{(u)} &= \\frac{u_{i}B^{i}}{\\alpha}\\ ,\\\\\nB^{i}_{(u)} &= \\frac{1}{u^{0}}\\left(\\frac{B^{i}}{\\alpha} + u^{i}B^{0}_{(u)}\\right)\\ ,\\\\\nb^{\\mu} &= \\frac{B^{\\mu}_{(u)}}{\\sqrt{4\\pi}}\\ .\n\\end{align}\n$$\n\nWe start by setting the relation\n\n$$\nb^{0} = \\frac{u_{i}B^{i}}{\\alpha\\sqrt{4\\pi}} \\implies \\boxed{\\alpha\\sqrt{4\\pi}b^{0} = u_{i}B^{i}}\\ .\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\nstatic inline void compute_smallba_b2_and_u_i_over_u0_psi4(CCTK_REAL *METRIC,CCTK_REAL *METRIC_LAP_PSI4,CCTK_REAL *U,CCTK_REAL u0L,CCTK_REAL ONE_OVER_LAPSE_SQRT_4PI,\n CCTK_REAL &u_x_over_u0_psi4,CCTK_REAL &u_y_over_u0_psi4,CCTK_REAL &u_z_over_u0_psi4,CCTK_REAL *smallb) {\n\n // NOW COMPUTE b^{\\mu} and b^2 = b^{\\mu} b^{\\nu} g_{\\mu \\nu}\n CCTK_REAL ONE_OVER_U0 = 1.0/u0L;\n CCTK_REAL shiftx_plus_vx = (METRIC[SHIFTX]+U[VX]);\n CCTK_REAL shifty_plus_vy = (METRIC[SHIFTY]+U[VY]);\n CCTK_REAL shiftz_plus_vz = (METRIC[SHIFTZ]+U[VZ]);\n\n // Eq. 56 in http://arxiv.org/pdf/astro-ph/0503420.pdf:\n // u_i = gamma_{ij} u^0 (v^j + beta^j), gamma_{ij} is the physical metric, and gamma_{ij} = Psi4 * METRIC[Gij], since METRIC[Gij] is the conformal metric.\n u_x_over_u0_psi4 = METRIC[GXX]*shiftx_plus_vx + METRIC[GXY]*shifty_plus_vy + METRIC[GXZ]*shiftz_plus_vz;\n u_y_over_u0_psi4 = METRIC[GXY]*shiftx_plus_vx + METRIC[GYY]*shifty_plus_vy + METRIC[GYZ]*shiftz_plus_vz;\n u_z_over_u0_psi4 = METRIC[GXZ]*shiftx_plus_vx + METRIC[GYZ]*shifty_plus_vy + METRIC[GZZ]*shiftz_plus_vz;\n\n // Eqs. 23 and 31 in http://arxiv.org/pdf/astro-ph/0503420.pdf:\n // Compute alpha sqrt(4 pi) b^t = u_i B^i\n CCTK_REAL alpha_sqrt_4pi_bt = ( u_x_over_u0_psi4*U[BX_CENTER] + u_y_over_u0_psi4*U[BY_CENTER] + u_z_over_u0_psi4*U[BZ_CENTER] ) * METRIC_LAP_PSI4[PSI4]*u0L;\n```\n\n Appending to ../src/inlined_functions.C\n\n\nThen we compute\n\n$$\n\\begin{align}\nb^{i} &= \\frac{B^{i}_{(u)}}{\\sqrt{4\\pi}}\\\\\n &= \\frac{1}{u^{0}\\sqrt{4\\pi}}\\left(\\frac{B^{i}}{\\alpha} + B^{0}_{(u)}u^{i}\\right)\\\\\n &= \\frac{1}{u^{0}\\sqrt{4\\pi}}\\left(\\frac{B^{i}}{\\alpha} + \\sqrt{4\\pi}b^{0}u^{i}\\right)\\\\\n &= \\frac{1}{\\alpha\\sqrt{4\\pi}}\\left(\\frac{B^{i}}{u^{0}} + \\alpha\\sqrt{4\\pi}b^{0}\\frac{u^{i}}{u^{0}}\\right)\\\\\n\\implies &\\boxed{b^{i} = \\frac{1}{\\alpha\\sqrt{4\\pi}}\\left(\\frac{B^{i}}{u^{0}} + \\alpha\\sqrt{4\\pi}b^{0}v^{i}\\right)}\\ .\n\\end{align}\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n // Eq. 24 in http://arxiv.org/pdf/astro-ph/0503420.pdf:\n // b^i = B^i_u / sqrt(4 pi)\n // b^i = ( B^i/alpha + B^0_u u^i ) / ( u^0 sqrt(4 pi) )\n // b^i = ( B^i/alpha + sqrt(4 pi) b^t u^i ) / ( u^0 sqrt(4 pi) )\n // b^i = ( B^i + alpha sqrt(4 pi) b^t u^i ) / ( alpha u^0 sqrt(4 pi) )\n // b^i = ( B^i/u^0 + alpha sqrt(4 pi) b^t u^i/u^0 ) / ( alpha sqrt(4 pi) )\n // b^i = ( B^i/u^0 + alpha sqrt(4 pi) b^t v^i ) / ( alpha sqrt(4 pi) )\n smallb[SMALLBX] = (U[BX_CENTER]*ONE_OVER_U0 + U[VX]*alpha_sqrt_4pi_bt)*ONE_OVER_LAPSE_SQRT_4PI;\n smallb[SMALLBY] = (U[BY_CENTER]*ONE_OVER_U0 + U[VY]*alpha_sqrt_4pi_bt)*ONE_OVER_LAPSE_SQRT_4PI;\n smallb[SMALLBZ] = (U[BZ_CENTER]*ONE_OVER_U0 + U[VZ]*alpha_sqrt_4pi_bt)*ONE_OVER_LAPSE_SQRT_4PI;\n // Eq. 23 in http://arxiv.org/pdf/astro-ph/0503420.pdf, with alpha sqrt (4 pi) b^2 = u_i B^i already computed above\n smallb[SMALLBT] = alpha_sqrt_4pi_bt * ONE_OVER_LAPSE_SQRT_4PI;\n```\n\n Appending to ../src/inlined_functions.C\n\n\nFinally, we compute\n\n$$\n\\begin{align}\nb^{2} &= g_{\\mu\\nu}b^{\\mu}b^{\\nu}\\\\\n &= g_{00}\\left(b^{0}\\right)^{2} + g_{ij}b^{i}b^{j} + 2g_{0i}b^{0}b^{i}\\\\\n &= \\left(-\\alpha^{2} + \\gamma_{ij}\\beta^{i}\\beta^{j}\\right)\\left(b^{0}\\right)^{2} + \\gamma_{ij}b^{i}b^{j} + 2b^{0}\\gamma_{ij}\\beta^{j}b^{i}\\\\\n &= -\\left(\\alpha b^{0}\\right)^{2} + \\gamma_{ij}\\left[b^{i}b^{j} + 2b^{0}b^{i}\\beta^{j} + \\left(b^{0}\\right)^{2}\\beta^{i}\\beta^{j}\\right]\\\\\n\\implies &\\boxed{b^{2} = -\\left(\\alpha b^{0}\\right)^{2} + \\gamma_{ij}\\left(b^{i} + b^{0}\\beta^{i}\\right)\\left(b^{j} + b^{0}\\beta^{j}\\right)}\n\\end{align}\n$$\n\n\n```python\n%%writefile -a $outfile_path__inlined_functions__C\n\n\n // b^2 = g_{\\mu \\nu} b^{\\mu} b^{\\nu}\n // = gtt bt^2 + gxx bx^2 + gyy by^2 + gzz bz^2 + 2 (gtx bt bx + gty bt by + gtz bt bz + gxy bx by + gxz bx bz + gyz by bz)\n // = (-al^2 + gamma_{ij} betai betaj) bt^2 + b^i b^j gamma_{ij} + 2 g_{t i} b^t b^i\n // = - (alpha b^t)^2 + (b^t)^2 gamma_{ij} beta^i beta^j + b^i b^j gamma_{ij} + 2 b^t g_{t i} b^i\n // = - (alpha b^t)^2 + (b^t)^2 gamma_{ij} beta^i beta^j + b^i b^j gamma_{ij} + 2 b^t (gamma_{ij} beta^j) b^i\n // = - (alpha b^t)^2 + gamma_{ij} ((b^t)^2 beta^i beta^j + b^i b^j + 2 b^t beta^j b^i)\n // = - (alpha b^t)^2 + gamma_{ij} ((b^t)^2 beta^i beta^j + 2 b^t beta^j b^i + b^i b^j)\n // = - (alpha b^t)^2 + gamma_{ij} (b^i + b^t beta^i) (b^j + b^t beta^j)\n CCTK_REAL bx_plus_shiftx_bt = smallb[SMALLBX]+METRIC[SHIFTX]*smallb[SMALLBT];\n CCTK_REAL by_plus_shifty_bt = smallb[SMALLBY]+METRIC[SHIFTY]*smallb[SMALLBT];\n CCTK_REAL bz_plus_shiftz_bt = smallb[SMALLBZ]+METRIC[SHIFTZ]*smallb[SMALLBT];\n smallb[SMALLB2] = -SQR(METRIC_LAP_PSI4[LAPSE]*smallb[SMALLBT]) +\n ( METRIC[GXX]*SQR(bx_plus_shiftx_bt) + METRIC[GYY]*SQR(by_plus_shifty_bt) + METRIC[GZZ]*SQR(bz_plus_shiftz_bt) +\n 2.0*( METRIC[GXY]*(bx_plus_shiftx_bt)*(by_plus_shifty_bt) +\n METRIC[GXZ]*(bx_plus_shiftx_bt)*(bz_plus_shiftz_bt) +\n METRIC[GYZ]*(by_plus_shifty_bt)*(bz_plus_shiftz_bt) ) ) * METRIC_LAP_PSI4[PSI4]; // mult by psi4 because METRIC[GIJ] is the conformal metric.\n /***********************************************************/\n}\n\n\n```\n\n Appending to ../src/inlined_functions.C\n\n\n\n\n# Step 10: Code validation \\[Back to [top](#toc)\\]\n$$\\label{code_validation}$$\n\nFirst we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook.\n\n\n```python\n# Verify if the code generated by this tutorial module\n# matches the original IllinoisGRMHD source code\n\n# First download the original IllinoisGRMHD source code\nimport urllib\nfrom os import path\n\noriginal_IGM_file_url = \"https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/IllinoisGRMHD/src/inlined_functions.C\"\noriginal_IGM_file_name = \"inlined_functions-original.C\"\noriginal_IGM_file_path = os.path.join(IGM_src_dir_path,original_IGM_file_name)\n\n# Then download the original IllinoisGRMHD source code\n# We try it here in a couple of ways in an attempt to keep\n# the code more portable\ntry:\n original_IGM_file_code = urllib.request.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n # Write down the file the original IllinoisGRMHD source code\n with open(original_IGM_file_path,\"w\") as file:\n file.write(original_IGM_file_code)\nexcept:\n try:\n original_IGM_file_code = urllib.urlopen(original_IGM_file_url).read().decode(\"utf-8\")\n # Write down the file the original IllinoisGRMHD source code\n with open(original_IGM_file_path,\"w\") as file:\n file.write(original_IGM_file_code)\n except:\n # If all else fails, hope wget does the job\n !wget -O $original_IGM_file_path $original_IGM_file_url\n\n# Perform validation\nValidation__inlined_functions__C = !diff $original_IGM_file_path $outfile_path__inlined_functions__C\n\nif Validation__inlined_functions__C == []:\n # If the validation passes, we do not need to store the original IGM source code file\n !rm $original_IGM_file_path\n print(\"Validation test for inlined_functions.C: PASSED!\")\nelse:\n # If the validation fails, we keep the original IGM source code file\n print(\"Validation test for inlined_functions.C: FAILED!\")\n # We also print out the difference between the code generated\n # in this tutorial module and the original IGM source code\n print(\"Diff:\")\n for diff_line in Validation__inlined_functions__C:\n print(diff_line)\n```\n\n Validation test for inlined_functions.C: FAILED!\n Diff:\n 1,4c1\n < static inline CCTK_REAL fasterpow_ppm_reconstruct(CCTK_REAL inputvar,CCTK_REAL inputpow) {\n < if(inputpow==2.0) return SQR(inputvar);\n < return pow(inputvar,inputpow);\n < }\n ---\n > \n 10c7\n < // one, which overestimates the max. speeds by a factor of ~2. \n ---\n > // one, which overestimates the max. speeds by a factor of ~2.\n 15c12\n < // kcm^2 = K_{\\mu} K^{\\mu}, \n ---\n > // kcm^2 = K_{\\mu} K^{\\mu},\n 38a36\n > \n 43a42\n > \n 49c48\n < \n ---\n > \n 59c58,59\n < static inline void compute_v02(CCTK_REAL dPcold_drho,CCTK_REAL gamma_th,CCTK_REAL eps_th,CCTK_REAL h,CCTK_REAL *smallb,CCTK_REAL *U, CCTK_REAL &v02L) {\n ---\n > \n > static inline void compute_v02(CCTK_REAL dPcold_drho,CCTK_REAL Gamma_th,CCTK_REAL eps_th,CCTK_REAL h,CCTK_REAL *smallb,CCTK_REAL *U, CCTK_REAL &v02L) {\n 64c64,65\n < CCTK_REAL c_s_squared = (dPcold_drho + gamma_th*(gamma_th-1.0)*eps_th)/(h);\n ---\n > CCTK_REAL c_s_squared = (dPcold_drho + Gamma_th*(Gamma_th-1.0)*eps_th)/(h);\n > \n 66a68\n > \n 70,84c72,180\n < static inline void compute_P_cold__eps_cold__dPcold_drho__eps_th__h__gamma_cold(CCTK_REAL *U, eos_struct &eos,\n < CCTK_REAL &P_cold,CCTK_REAL &eps_cold,CCTK_REAL &dPcold_drho,CCTK_REAL &eps_th,CCTK_REAL &h,\n < CCTK_REAL &gamma_cold) {\n < // This code handles equations of state of the form defined\n < // in Eqs 13-16 in http://arxiv.org/pdf/0802.0200.pdf\n < \n < if(U[RHOB]==0) {\n < P_cold = 0.0;\n < eps_cold = 0.0;\n < dPcold_drho = 0.0;\n < eps_th = 0.0;\n < h = 0.0;\n < gamma_cold = eos.gamma_tab[0];\n < return;\n < }\n ---\n > /* Function : font_fix__rhob_loop()\n > * Authors : Leo Werneck\n > * Description : Determines rhob using the font fix prescription\n > * Dependencies: find_polytropic_K_and_Gamma_index()\n > * : compute_P_cold__eps_cold()\n > * Reference : Etienne et al. (2011) [https://arxiv.org/pdf/1112.0568.pdf]\n > *\n > * Inputs : maxits - maximum number of iterations allowed\n > * : tol - font fix tolerance\n > * : W - See eq. (A26)\n > * : Sf2 - S_{fluid}^{2}, see eq. (A24)\n > * : Psim6 - This is equal to sqrt(\\gamma)\n > * : sdots - \\tilde{S}_{\\mu}\\tilde{S}^{\\mu}\n > * : BbardotS2 - (\\bar{B}^{\\mu}S_{\\mu})^{2},\n > * : B2bar - \\bar{B}^{2}, see eq. (A28)\n > * : CONSERVS - Array of conservative variables\n > * : eos - Struct of EOS parameters\n > * : rhob_in - Initial value of rhob\n > * : rhob_out - Output variable\n > *\n > * Outputs : rhob_out - Updated value of rhob\n > * : return value: 0 - Font fix worked\n > * : return value: 1 - Font fix failed\n > */\n > inline int font_fix__rhob_loop( int maxits, CCTK_REAL tol,\n > CCTK_REAL W, CCTK_REAL Sf2, CCTK_REAL Psim6, CCTK_REAL sdots, CCTK_REAL BbardotS2, CCTK_REAL B2bar,\n > CCTK_REAL *CONSERVS,\n > eos_struct eos, CCTK_REAL rhob_in, CCTK_REAL &rhob_out ) {\n > \n > /* Declare basic variables */\n > bool fontcheck=true;\n > int itcount = 0, j0, j1;\n > CCTK_REAL W0, Sf20, rhob0, rhob1, h, P_cold, eps_cold;\n > \n > //////////////////////\n > // OUTER LOOP START //\n > //////////////////////\n > while(fontcheck && itcount < maxits) {\n > \n > /* Set variables to their input values */\n > itcount++;\n > W0 = W;\n > Sf20 = Sf2;\n > rhob1 = rhob_in;\n > \n > /* Based on rhob_in (i.e. rhob1), determine the\n > * polytropic index j1\n > */\n > j1 = find_polytropic_K_and_Gamma_index(eos,rhob1);\n > \n > //////////////////////\n > // INNER LOOP START //\n > //////////////////////\n > do {\n > \n > /* Set rhob0/j0 to be equal to the rhob/j used\n > * in the previous iteration, i.e. rhob1/j1.\n > */\n > rhob0 = rhob1;\n > j0 = j1;\n > \n > /* Compute h using h_cold and our polytropic EOS\n > * .------------------------------------------.\n > * | h = h_cold = 1 + eps_cold + P_cold/rhob. |\n > * .------------------------------------------.\n > */\n > compute_P_cold__eps_cold(eos,rhob0, P_cold, eps_cold);\n > h = 1.0 + eps_cold + P_cold/rhob0;\n > \n > /* Update rhob using eq. (A62) in Etienne et al. (2011)\n > * https://arxiv.org/pdf/1112.0568.pdf\n > * .---------------------------------------------------------------------------.\n > * | rhob = rho_star * Psi^{-6} / sqrt( 1 + S_fluid^{2}/( (rho_star*h)^{2} ) ) |\n > * .---------------------------------------------------------------------------.\n > */\n > rhob1 = CONSERVS[RHOSTAR]*Psim6/sqrt(1.0+Sf20/SQR(CONSERVS[RHOSTAR]*h));\n > \n > /* Update j1 */\n > j1 = find_polytropic_K_and_Gamma_index(eos,rhob1);\n > \n > } while( fabs(rhob1-rhob0) > rhob1*tol || j1 != j0);\n > //////////////////////\n > // INNER LOOP END //\n > //////////////////////\n > \n > /* Output the last value of rhob */\n > rhob_out = rhob1;\n > \n > /* Perform physical checks on the variables\n > * and output the last value of h obtained\n > */\n > compute_P_cold__eps_cold(eos,rhob_out, P_cold, eps_cold);\n > h = 1.0 + eps_cold + P_cold/rhob_out;\n > \n > /* Set W based on eq. (A60) in Etienne et al. (2011)\n > * https://arxiv.org/pdf/1112.0568.pdf\n > * .-------------------------------------------------------.\n > * | W = psi^{-6} * sqrt( S_fluid^{2} + (rho_star*h)^{2} ) |\n > * .-------------------------------------------------------.\n > */\n > W = sqrt( Sf20 + SQR(CONSERVS[RHOSTAR]*h))*Psim6;\n > \n > /* Then update S_{fluid}^{2} using eq. (A61) in Etienne et al. (2011)\n > * https://arxiv.org/pdf/1112.0568.pdf\n > * .---------------------------------------------------------------------------.\n > * | S_fluid^{2} = ( W^{2}*S^{2} + (B.S)^2*(B^{2} + 2W) )/( ( W + B^{2} )^{2} )|\n > * .---------------------------------------------------------------------------.\n > */\n > Sf2 = (SQR(W)*sdots + BbardotS2*(B2bar + 2.0*W))/SQR(W+B2bar);\n 86c182\n < CCTK_REAL U_RHOB_inv = 1.0/U[RHOB];\n ---\n > if ( fabs(W-W0) < W*tol && fabs(Sf20-Sf2) < Sf2*tol) fontcheck=false;\n 88,111d183\n < if(eos.neos==1) {\n < // Eq. 14 of http://arxiv.org/pdf/0802.0200.pdf :\n < // P_{cold} = K_i rho_i^{\\Gamma_i}\n < P_cold = eos.k_tab[0]*fasterpow_ppm_reconstruct(U[RHOB],eos.gamma_tab[0]);\n < // Eq. 16 of http://arxiv.org/pdf/0802.0200.pdf :\n < // \\epsilon_{cold} = \\int ( P_{cold}(rho) / rho^2 ) drho \n < // = \\int ( K_0 \\rho^{\\Gamma_0 - 2} ) drho \n < // = ( K_0 \\rho^{\\Gamma_0 - 1} ) / (\\Gamma_0 - 1)\n < // = ( P_{cold} / rho ) / (\\Gamma_0 - 1)\n < eps_cold = P_cold*U_RHOB_inv/(eos.gamma_tab[0]-1.0);\n < // dPcold/drho = K_i \\Gamma_i rho_i^{\\Gamma_i-1} = \\Gamma_i P_{cold} / rho\n < dPcold_drho = eos.gamma_tab[0]*P_cold*U_RHOB_inv;\n < // Eq. 15 of http://arxiv.org/pdf/0802.0200.pdf :\n < // P_{th} = (\\Gamma_{th} - 1) \\rho_0 \\epsilon_{th},\n < // Eq. 13 of http://arxiv.org/pdf/0802.0200.pdf :\n < // P_{th} = P - P_{cold}\n < // -> P - P_{cold} = (\\Gamma_{th} - 1) \\rho_0 \\epsilon_{th}\n < // -> \\epsilon_{th} = ( P - P_{cold} ) / [ (\\Gamma_{th} - 1) \\rho_0 ]\n < eps_th = (U[PRESSURE] - P_cold)/(eos.gamma_th-1.0)*U_RHOB_inv;\n < // Just below Eq. 16 in http://arxiv.org/pdf/astro-ph/0503420.pdf :\n < // h = 1 + \\epsilon + P/rho\n < h = 1.0 + eps_cold + eps_th + U[PRESSURE]*U_RHOB_inv;\n < gamma_cold = eos.gamma_tab[0];\n < return;\n 113,125c185,194\n < \n < // See comments above for the eos.neos==1 case for relevant \n < // equations & references; the extension to arbitrary \"nn\"\n < // is straightforward.\n < for(int nn=1;nn eos.rho_tab[nn-1]) {\n < P_cold = eos.k_tab[nn]*fasterpow_ppm_reconstruct(U[RHOB],eos.gamma_tab[nn]);\n < eps_cold = eos.eps_tab[nn-1] + (P_cold*U_RHOB_inv - eos.P_tab[nn-1]/eos.rho_tab[nn-1])/(eos.gamma_tab[nn]-1.0);\n < dPcold_drho = eos.gamma_tab[nn]*P_cold*U_RHOB_inv;\n < eps_th = (U[PRESSURE] - P_cold)/(eos.gamma_th-1.0)*U_RHOB_inv;\n < h = 1.0 + eps_cold + eps_th + U[PRESSURE]*U_RHOB_inv;\n < gamma_cold = eos.gamma_tab[nn];\n < }\n ---\n > //////////////////////\n > // OUTER LOOP END //\n > //////////////////////\n > \n > /* If the code converged before the max\n > * number of iterations were exceeded,\n > * return 0, otherwise return 1.\n > */\n > if(fontcheck || itcount >= maxits) {\n > return 1;\n 127,133c196,197\n < if (U[RHOB] > eos.rho_tab[eos.neos-1]) {\n < P_cold = eos.k_tab[eos.neos]*fasterpow_ppm_reconstruct(U[RHOB],eos.gamma_tab[eos.neos]);\n < eps_cold = eos.eps_tab[eos.neos-1] + (P_cold*U_RHOB_inv - eos.P_tab[eos.neos-1]/eos.rho_tab[eos.neos-1])/(eos.gamma_tab[eos.neos]-1.0);\n < dPcold_drho = eos.gamma_tab[eos.neos]*P_cold*U_RHOB_inv;\n < eps_th = (U[PRESSURE] - P_cold)/(eos.gamma_th-1.0)*U_RHOB_inv;\n < h = 1.0 + eps_cold + eps_th + U[PRESSURE]*U_RHOB_inv;\n < gamma_cold = eos.gamma_tab[eos.neos];\n ---\n > else {\n > return 0;\n 136a201\n > \n 149a215\n > \n 150a217,218\n > \n > #ifndef ENABLE_STANDALONE_IGM_C2P_SOLVER\n 151a220,221\n > #endif\n > \n 154c224\n < // \\gamma_{ij} (v^i + \\beta^i)(v^j + \\beta^j)/(\\alpha)^2 \n ---\n > // \\gamma_{ij} (v^i + \\beta^i)(v^j + \\beta^j)/(\\alpha)^2\n 165a236\n > \n 176a248\n > \n 187,195c259,267\n < // one_over_alpha_u0 = sqrt(1.0-one_minus_one_over_alpha_u0_squared); \n < /* Proof of following line: */ \n < /* [ 1-1/(alphau0)^2 ] / [ 1/(alphau0) (1 + 1/(alphau0)) ] */ \n < /* = [ (alphau0)^2 - 1)/((alphau0)^2) ] / [ 1/(alphau0) + 1/(alphau0)^2 ] */ \n < /* = [ (alphau0)^2 - 1)/((alphau0)^2) ] / [ (alphau0 + 1)/(alphau0)^2 ] */ \n < /* = [ (alphau0)^2 - 1) ] / [ (alphau0 + 1) ] */ \n < /* [ (alphau0 + 1) (alphau0 - 1) ] / [ (alphau0 + 1) ] */ \n < /* = alphau0 - 1 */ \n < //alpha_u0_minus_one = one_minus_one_over_alpha_u0_squared/one_over_alpha_u0/(1.0+one_over_alpha_u0); \n ---\n > // one_over_alpha_u0 = sqrt(1.0-one_minus_one_over_alpha_u0_squared);\n > /* Proof of following line: */\n > /* [ 1-1/(alphau0)^2 ] / [ 1/(alphau0) (1 + 1/(alphau0)) ] */\n > /* = [ (alphau0)^2 - 1)/((alphau0)^2) ] / [ 1/(alphau0) + 1/(alphau0)^2 ] */\n > /* = [ (alphau0)^2 - 1)/((alphau0)^2) ] / [ (alphau0 + 1)/(alphau0)^2 ] */\n > /* = [ (alphau0)^2 - 1) ] / [ (alphau0 + 1) ] */\n > /* [ (alphau0 + 1) (alphau0 - 1) ] / [ (alphau0 + 1) ] */\n > /* = alphau0 - 1 */\n > //alpha_u0_minus_one = one_minus_one_over_alpha_u0_squared/one_over_alpha_u0/(1.0+one_over_alpha_u0);\n 197a270\n > \n 212a286\n > \n 224c298\n < \n ---\n > \n 235c309,310\n < static inline void compute_smallba_b2_and_u_i_over_u0_psi4(CCTK_REAL *METRIC,CCTK_REAL *METRIC_LAP_PSI4,CCTK_REAL *U,CCTK_REAL u0L,CCTK_REAL ONE_OVER_LAPSE_SQRT_4PI, \n ---\n > \n > static inline void compute_smallba_b2_and_u_i_over_u0_psi4(CCTK_REAL *METRIC,CCTK_REAL *METRIC_LAP_PSI4,CCTK_REAL *U,CCTK_REAL u0L,CCTK_REAL ONE_OVER_LAPSE_SQRT_4PI,\n 252a328\n > \n 265a342\n > \n 276c353\n < CCTK_REAL bz_plus_shiftz_bt = smallb[SMALLBZ]+METRIC[SHIFTZ]*smallb[SMALLBT]; \n ---\n > CCTK_REAL bz_plus_shiftz_bt = smallb[SMALLBZ]+METRIC[SHIFTZ]*smallb[SMALLBT];\n 283a361\n > \n\n\n\n\n# Step 11: Output this notebook to $\\LaTeX$-formatted PDF file \\[Back to [top](#toc)\\]\n$$\\label{latex_pdf_output}$$\n\nThe following code cell converts this Jupyter notebook into a proper, clickable $\\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename\n[Tutorial-IllinoisGRMHD__inlined_functions.pdf](Tutorial-IllinoisGRMHD__inlined_functions.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means).\n\n\n```python\nlatex_nrpy_style_path = os.path.join(nrpy_dir_path,\"latex_nrpy_style.tplx\")\n#!jupyter nbconvert --to latex --template $latex_nrpy_style_path --log-level='WARN' Tutorial-IllinoisGRMHD__inlined_functions.ipynb\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__inlined_functions.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__inlined_functions.tex\n#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__inlined_functions.tex\n!rm -f Tut*.out Tut*.aux Tut*.log\n```\n", "meta": {"hexsha": "d4f58f83a8e15671f0b8396e2c80df04f4cfc19e", "size": 67763, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__inlined_functions.ipynb", "max_stars_repo_name": "goncalo-andrade/nrpytutorial", "max_stars_repo_head_hexsha": "4fbcb51c936864b442daefd176bd6a5277c00116", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-06-09T16:16:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-09T16:16:21.000Z", "max_issues_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__inlined_functions.ipynb", "max_issues_repo_name": "goncalo-andrade/nrpytutorial", "max_issues_repo_head_hexsha": "4fbcb51c936864b442daefd176bd6a5277c00116", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__inlined_functions.ipynb", "max_forks_repo_name": "goncalo-andrade/nrpytutorial", "max_forks_repo_head_hexsha": "4fbcb51c936864b442daefd176bd6a5277c00116", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3871399866, "max_line_length": 476, "alphanum_fraction": 0.509319245, "converted": true, "num_tokens": 18387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.30572603913384694}} {"text": "\n\n\n# Start-to-Finish Example: `GiRaFFE_NRPy` 3D tests\n\n### Author: Patrick Nelson\n\n### Adapted from [Start-to-Finish Example: Head-On Black Hole Collision](../Tutorial-Start_to_Finish-BSSNCurvilinear-Two_BHs_Collide.ipynb)\n\n## This module implements a basic GRFFE code to evolve one-dimensional GRFFE waves.\n\n### NRPy+ Source Code for this module: \n* [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Exact_Wald.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Exact_Wald.py) [\\[**tutorial**\\]](Tutorial-GiRaFFEfood_NRPy_Exact_Wald.ipynb) Generates Exact Wald initial data\n* [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py) [\\[**tutorial**\\]](Tutorial-GiRaFFEfood_NRPy_Aligned_Rotator.ipynb) Generates Aligned Rotator initial data\n* [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_1D_tests.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_1D_tests.py) [\\[**tutorial**\\]](Tutorial-GiRaFFEfood_NRPy_1D_tests.ipynb) Generates Alfvén Wave initial data.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Afield_flux.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Afield_flux.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy_staggered-Afield_flux.ipynb) Generates the expressions to find the flux term of the induction equation.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_A2B.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_A2B.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy_staggered-A2B.ipynb) Generates the driver to compute the magnetic field from the vector potential/\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-BCs.ipynb) Generates the code to apply boundary conditions to the vector potential, scalar potential, and three-velocity.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_C2P_P2C.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_C2P_P2C.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-C2P_P2C.ipynb) Generates the conservative-to-primitive and primitive-to-conservative solvers.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_Metric_Face_Values.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_Metric_Face_Values.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-Metric_Face_Values.ipynb) Generates code to interpolate metric gridfunctions to cell faces.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_PPM.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_PPM.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-PPM.ipynb) Genearates code to reconstruct primitive variables on cell faces.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Source_Terms.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Source_Terms.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy_staggered-Source_Terms.ipynb) Generates the expressions to find the flux term of the Poynting flux evolution equation.\n* [GiRaFFE_NRPy/Stilde_flux.py](../../edit/in_progress/GiRaFFE_NRPy/Stilde_flux.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-Stilde_flux.ipynb) Generates the expressions to find the flux term of the Poynting flux evolution equation.\n* [../GRFFE/equations.py](../../edit/GRFFE/equations.py) [\\[**tutorial**\\]](../Tutorial-GRFFE_Equations-Cartesian.ipynb) Generates code necessary to compute the source terms.\n* [../GRHD/equations.py](../../edit/GRHD/equations.py) [\\[**tutorial**\\]](../Tutorial-GRHD_Equations-Cartesian.ipynb) Generates code necessary to compute the source terms.\n\nHere we use NRPy+ to generate the C source code necessary to set up initial data for an Exact Wald (see [the original GiRaFFE paper](https://arxiv.org/pdf/1704.00599.pdf)). Then we use it to generate the RHS expressions for [Method of Lines](https://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html) time integration based on the [explicit Runge-Kutta fourth-order scheme](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods) (RK4).\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis notebook is organized as follows\n\n1. [Step 1](#initializenrpy): Set core NRPy+ parameters for numerical grids\n1. [Step 2](#grffe): Output C code for GRFFE evolution\n 1. [Step 2.a](#mol): Output macros for Method of Lines timestepping\n1. [Step 3](#gf_id): Import `GiRaFFEfood_NRPy` initial data modules\n1. [Step 4](#cparams): Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h`\n1. [Step 5](#mainc): `GiRaFFE_NRPy_standalone.c`: The Main C Code\n\n\n\n# Step 1: Set up core functions and parameters for solving GRFFE equations \\[Back to [top](#toc)\\]\n$$\\label{setup}$$\n\n\n\n```python\nimport shutil, os, sys # Standard Python modules for multiplatform OS-level functions\n# First, we'll add the parent directory to the list of directories Python will check for modules.\nnrpy_dir_path = os.path.join(\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Step P1: Import needed NRPy+ core modules:\nfrom outputC import outCfunction, lhrh, add_to_Cfunction_dict # NRPy+: Core C code output module\nimport sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends\nimport finite_difference as fin # NRPy+: Finite difference C code generation module\nimport NRPy_param_funcs as par # NRPy+: Parameter interface\nimport grid as gri # NRPy+: Functions having to do with numerical grids\nimport indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support\nimport cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\n\n# Step P2: Create C code output directory:\nCcodesdir = os.path.join(\"GiRaFFE_staggered_new_way_standalone_Ccodes/\")\n# First remove C code output directory if it exists\n# Courtesy https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty\n# !rm -r ScalarWaveCurvilinear_Playground_Ccodes\nshutil.rmtree(Ccodesdir, ignore_errors=True)\n# Then create a fresh directory\ncmd.mkdir(Ccodesdir)\n\n# Step P3: Create executable output directory:\noutdir = os.path.join(Ccodesdir,\"output/\")\ncmd.mkdir(outdir)\n\n# Step P5: Set timestepping algorithm (we adopt the Method of Lines)\nREAL = \"double\" # Best to use double here.\ndefault_CFL_FACTOR= 0.5 # (GETS OVERWRITTEN WHEN EXECUTED.) In pure axisymmetry (symmetry_axes = 2 below) 1.0 works fine. Otherwise 0.5 or lower.\n\n# Step P6: Set the finite differencing order to 2.\npar.set_parval_from_str(\"finite_difference::FD_CENTDERIVS_ORDER\",2)\n\n# Step P7: Enable SIMD-optimized code?\n# I.e., generate BSSN and Ricci C code kernels using SIMD-vectorized\n# compiler intrinsics, which *greatly improve the code's performance*,\n# though at the expense of making the C-code kernels less\n# human-readable.\n# * Important note in case you wish to modify the BSSN/Ricci kernels\n# here by adding expressions containing transcendental functions\n# (e.g., certain scalar fields):\n# Note that SIMD-based transcendental function intrinsics are not\n# supported by the default installation of gcc or clang (you will\n# need to use e.g., the SLEEF library from sleef.org, for this\n# purpose). The Intel compiler suite does support these intrinsics\n# however without the need for external libraries.\nenable_SIMD = False\n\n# Step 1.b: Enable reference metric precomputation.\nenable_rfm_precompute = False\n\nif enable_SIMD and not enable_rfm_precompute:\n print(\"ERROR: SIMD does not currently handle transcendental functions,\\n\")\n print(\" like those found in rfmstruct (rfm_precompute).\\n\")\n print(\" Therefore, enable_SIMD==True and enable_rfm_precompute==False\\n\")\n print(\" is not supported.\\n\")\n sys.exit(1)\n\n# Step 1.c: Enable \"FD functions\". In other words, all finite-difference stencils\n# will be output as inlined static functions. This is essential for\n# compiling highly complex FD kernels with using certain versions of GCC;\n# GCC 10-ish will choke on BSSN FD kernels at high FD order, sometimes\n# taking *hours* to compile. Unaffected GCC versions compile these kernels\n# in seconds. FD functions do not slow the code performance, but do add\n# another header file to the C source tree.\n# With gcc 7.5.0, enable_FD_functions=True decreases performance by 10%\nenable_FD_functions = False\n\nthismodule = \"Start_to_Finish-GiRaFFE_NRPy-1D_tests\"\nTINYDOUBLE = par.Cparameters(\"REAL\", thismodule, \"TINYDOUBLE\", 1e-100)\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_Main_Driver_staggered_new_way as md\n# par.set_paramsvals_value(\"GiRaFFE_NRPy.GiRaFFE_NRPy_C2P_P2C::enforce_speed_limit_StildeD = False\")\npar.set_paramsvals_value(\"GiRaFFE_NRPy.GiRaFFE_NRPy_C2P_P2C::enforce_current_sheet_prescription = False\")\n```\n\n\n\n# Step 2: Output C code for GRFFE evolution \\[Back to [top](#toc)\\]\n$$\\label{grffe}$$\n\nWe will first write the C codes needed for GRFFE evolution. We have already written a module to generate all these codes and call the functions in the appropriate order, so we will import that here. We will take the slightly unusual step of doing this before we generate the initial data functions because the main driver module will register all the gridfunctions we need. It will also generate functions that, in addition to their normal spot in the MoL timestepping, will need to be called during the initial data step to make sure all the variables are appropriately filled in. \n\n\n\n## Step 2.a: Output macros for Method of Lines timestepping \\[Back to [top](#toc)\\]\n$$\\label{mol}$$\n\nNow, we generate the code to implement the method of lines using the fourth-order Runge-Kutta algorithm.\n\n\n```python\nRK_method = \"Euler\"\n\n# Step 3: Generate Runge-Kutta-based (RK-based) timestepping code.\n# As described above the Table of Contents, this is a 3-step process:\n# 3.A: Evaluate RHSs (RHS_string)\n# 3.B: Apply boundary conditions (post_RHS_string, pt 1)\nimport MoLtimestepping.C_Code_Generation as MoL\nfrom MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict\nRK_order = Butcher_dict[RK_method][1]\ncmd.mkdir(os.path.join(Ccodesdir,\"MoLtimestepping/\"))\nMoL.MoL_C_Code_Generation(RK_method,\n RHS_string = \"\"\"\nGiRaFFE_NRPy_RHSs(¶ms,auxevol_gfs,RK_INPUT_GFS,RK_OUTPUT_GFS);\"\"\",\n post_RHS_string = \"\"\"\nGiRaFFE_NRPy_post_step(¶ms,xx,auxevol_gfs,RK_OUTPUT_GFS,n+1);\\n\"\"\",\n outdir = os.path.join(Ccodesdir,\"MoLtimestepping/\"))\n```\n\n\n\n# Step 3: Import `GiRaFFEfood_NRPy` initial data modules \\[Back to [top](#toc)\\]\n$$\\label{gf_id}$$\n\nWith the preliminaries out of the way, we will write the C functions to set up initial data. There are two categories of initial data that must be set: the spacetime metric variables, and the GRFFE plasma variables. We will set up the spacetime first.\n\n\n```python\n# There are several initial data routines we need to test. We'll control which one we use with a string option\ninitial_data = \"ExactWald\" # Valid options: \"ExactWald\", \"AlignedRotator\"\nspacetime = \"ShiftedKerrSchild\" # Valid options: \"ShiftedKerrSchild\", \"flat\"\n\nif spacetime == \"ShiftedKerrSchild\":\n import BSSN.ShiftedKerrSchild as sks\n sks.ShiftedKerrSchild(True)\n import reference_metric as rfm\n par.set_parval_from_str(\"reference_metric::CoordSystem\",\"Cartesian\")\n rfm.reference_metric()\n # Use the Jacobian matrix to transform the vectors to Cartesian coordinates.\n par.set_parval_from_str(\"reference_metric::CoordSystem\",\"Spherical\")\n rfm.reference_metric()\n Jac_dUCart_dDrfmUD,Jac_dUrfm_dDCartUD = rfm.compute_Jacobian_and_inverseJacobian_tofrom_Cartesian()\n # Transform the coordinates of the Jacobian matrix from spherical to Cartesian:\n par.set_parval_from_str(\"reference_metric::CoordSystem\",\"Cartesian\")\n rfm.reference_metric()\n tmpa,tmpb,tmpc = sp.symbols(\"tmpa,tmpb,tmpc\")\n for i in range(3):\n for j in range(3):\n Jac_dUCart_dDrfmUD[i][j] = Jac_dUCart_dDrfmUD[i][j].subs([(rfm.xx[0],tmpa),(rfm.xx[1],tmpb),(rfm.xx[2],tmpc)])\n Jac_dUCart_dDrfmUD[i][j] = Jac_dUCart_dDrfmUD[i][j].subs([(tmpa,rfm.xxSph[0]),(tmpb,rfm.xxSph[1]),(tmpc,rfm.xxSph[2])])\n Jac_dUrfm_dDCartUD[i][j] = Jac_dUrfm_dDCartUD[i][j].subs([(rfm.xx[0],tmpa),(rfm.xx[1],tmpb),(rfm.xx[2],tmpc)])\n Jac_dUrfm_dDCartUD[i][j] = Jac_dUrfm_dDCartUD[i][j].subs([(tmpa,rfm.xxSph[0]),(tmpb,rfm.xxSph[1]),(tmpc,rfm.xxSph[2])])\n\n gammaSphDD = ixp.zerorank2()\n for i in range(3):\n for j in range(3):\n gammaSphDD[i][j] += sks.gammaSphDD[i][j].subs(sks.r,rfm.xxSph[0]).subs(sks.th,rfm.xxSph[1])\n\n betaSphU = ixp.zerorank1()\n for i in range(3):\n betaSphU[i] += sks.betaSphU[i].subs(sks.r,rfm.xxSph[0]).subs(sks.th,rfm.xxSph[1])\n alpha = sks.alphaSph.subs(sks.r,rfm.xxSph[0]).subs(sks.th,rfm.xxSph[1])\n\n gammaDD = rfm.basis_transform_tensorDD_from_rfmbasis_to_Cartesian(Jac_dUrfm_dDCartUD, gammaSphDD)\n\n unused_gammaUU,gammaDET = ixp.symm_matrix_inverter3x3(gammaDD)\n sqrtgammaDET = sp.sqrt(gammaDET)\n\n betaU = rfm.basis_transform_vectorD_from_rfmbasis_to_Cartesian(Jac_dUrfm_dDCartUD, betaSphU)\n\n loopopts_id =\"AllPoints,Read_xxs\"\n\nelif spacetime == \"flat\":\n gammaDD = ixp.zerorank2(DIM=3)\n for i in range(3):\n for j in range(3):\n if i==j:\n gammaDD[i][j] = sp.sympify(1) # else: leave as zero\n betaU = ixp.zerorank1() # All should be 0\n alpha = sp.sympify(1)\n\n # Description and options for this initial data\n desc = \"Generate a flat spacetime metric.\"\n loopopts_id =\"AllPoints\" # we don't need to read coordinates for flat spacetime.\n\ndesc = \"Generate a spinning black hole with Shifted Kerr Schild metric in a Cartesian basis.\"\nname = \"set_initial_spacetime_metric_data\"\nvalues_to_print = [\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD00\"),rhs=gammaDD[0][0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD01\"),rhs=gammaDD[0][1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD02\"),rhs=gammaDD[0][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD11\"),rhs=gammaDD[1][1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD12\"),rhs=gammaDD[1][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD22\"),rhs=gammaDD[2][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"betaU0\"),rhs=betaU[0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"betaU1\"),rhs=betaU[1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"betaU2\"),rhs=betaU[2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"alpha\"),rhs=alpha)\n ]\n\noutCfunction(\n outfile = os.path.join(Ccodesdir,name+\".h\"), desc=desc, name=name,\n params =\"const paramstruct *params,REAL *xx[3],REAL *auxevol_gfs\",\n body = fin.FD_outputC(\"returnstring\",values_to_print,params=\"outCverbose=False\"),\n loopopts = loopopts_id)\n\n```\n\n Output C function set_initial_spacetime_metric_data() to file GiRaFFE_staggered_new_way_standalone_Ccodes/set_initial_spacetime_metric_data.h\n\n\nNow, we will write out the initial data function for the GRFFE variables.\n\n\n```python\nimport GiRaFFEfood_NRPy.GiRaFFEfood_NRPy as gid\nif initial_data==\"ExactWald\":\n gid.GiRaFFEfood_NRPy_generate_initial_data(ID_type = initial_data, stagger_enable = True,M=sks.M,KerrSchild_radial_shift=sks.r0,gammaDD=gammaDD,sqrtgammaDET=sqrtgammaDET)\n desc = \"Generate exact Wald initial test data for GiRaFFEfood_NRPy.\"\nelif initial_data==\"SplitMonopole\":\n gid.GiRaFFEfood_NRPy_generate_initial_data(ID_type = initial_data, stagger_enable = True,M=sks.M,a=sks.a,KerrSchild_radial_shift=sks.r0,alpha=alpha,betaU=betaSphU,gammaDD=gammaDD,sqrtgammaDET=sqrtgammaSphDET)\n desc = \"Generate Split Monopole initial test data for GiRaFFEfood_NRPy.\"\nelse:\n print(\"Unsupported Initial Data string \"+initial_data+\"! Supported ID: ExactWald, or SplitMonopole\")\n\nname = \"initial_data\"\n\nvalues_to_print = [\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"AD0\"),rhs=gid.AD[0]),\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"AD1\"),rhs=gid.AD[1]),\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"AD2\"),rhs=gid.AD[2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"ValenciavU0\"),rhs=gid.ValenciavU[0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"ValenciavU1\"),rhs=gid.ValenciavU[1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"ValenciavU2\"),rhs=gid.ValenciavU[2]),\n# lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"BU0\"),rhs=gid.BU[0]),\n# lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"BU1\"),rhs=gid.BU[1]),\n# lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"BU2\"),rhs=gid.BU[2]),\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"psi6Phi\"),rhs=sp.sympify(0))\n ]\n\noutCfunction(\n outfile = os.path.join(Ccodesdir,name+\".h\"), desc=desc, name=name,\n params =\"const paramstruct *params,REAL *xx[3],REAL *auxevol_gfs,REAL *out_gfs\",\n body = fin.FD_outputC(\"returnstring\",values_to_print,params=\"outCverbose=False\"),\n loopopts =\"AllPoints,Read_xxs\")\n```\n\n Output C function initial_data() to file GiRaFFE_staggered_new_way_standalone_Ccodes/initial_data.h\n\n\n\n\n# Step 4: Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h` \\[Back to [top](#toc)\\]\n$$\\label{cparams}$$\n\nBased on declared NRPy+ Cparameters, first we generate `declare_Cparameters_struct.h`, `set_Cparameters_default.h`, and `set_Cparameters[-SIMD].h`.\n\nThen we output `free_parameters.h`, which sets initial data parameters, as well as grid domain & reference metric parameters, applying `domain_size` and `sinh_width`/`SymTP_bScale` (if applicable) as set above\n\n\n```python\n# Step 3.e: Output C codes needed for declaring and setting Cparameters; also set free_parameters.h\n# Step 3.e.i: Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h\npar.generate_Cparameters_Ccodes(os.path.join(Ccodesdir))\n\n# Step 3.e.ii: Set free_parameters.h\nwith open(os.path.join(Ccodesdir,\"free_parameters.h\"),\"w\") as file:\n file.write(\"\"\"// Override parameter defaults with values based on command line arguments and NGHOSTS.\nparams.Nxx0 = atoi(argv[1]);\nparams.Nxx1 = atoi(argv[2]);\nparams.Nxx2 = atoi(argv[3]);\nparams.Nxx_plus_2NGHOSTS0 = params.Nxx0 + 2*NGHOSTS;\nparams.Nxx_plus_2NGHOSTS1 = params.Nxx1 + 2*NGHOSTS;\nparams.Nxx_plus_2NGHOSTS2 = params.Nxx2 + 2*NGHOSTS;\n// Step 0d: Set up space and time coordinates\n// Step 0d.i: Declare \\Delta x^i=dxx{0,1,2} and invdxx{0,1,2}, as well as xxmin[3] and xxmax[3]:\nconst REAL xxmin[3] = {-1.5,-1.5,-1.5};\nconst REAL xxmax[3] = { 1.5, 1.5, 1.5};\n\nparams.dxx0 = (xxmax[0] - xxmin[0]) / ((REAL)params.Nxx0+1);\nparams.dxx1 = (xxmax[1] - xxmin[1]) / ((REAL)params.Nxx1+1);\nparams.dxx2 = (xxmax[2] - xxmin[2]) / ((REAL)params.Nxx2+1);\nprintf(\"dxx0,dxx1,dxx2 = %.15e,%.15e,%.15e\\\\n\",params.dxx0,params.dxx1,params.dxx2);\nparams.invdx0 = 1.0 / params.dxx0;\nparams.invdx1 = 1.0 / params.dxx1;\nparams.invdx2 = 1.0 / params.dxx2;\n\nconst int poison_grids = 1;\n// Standard GRFFE parameters:\nparams.GAMMA_SPEED_LIMIT = 2000.0;\nparams.diss_strength = 4.0;\n\"\"\")\nif initial_data==\"ExactWald\":\n with open(os.path.join(Ccodesdir,\"free_parameters.h\"),\"a\") as file:\n file.write(\"\"\"params.r0 = 0.4;\nparams.a = 0.0;\n\"\"\")\n\n```\n\n\n\n# Step 4: Set up boundary condition functions for chosen singular, curvilinear coordinate system \\[Back to [top](#toc)\\]\n$$\\label{bc_functs}$$\n\nNext apply singular, curvilinear coordinate boundary conditions [as documented in the corresponding NRPy+ tutorial notebook](Tutorial-Start_to_Finish-Curvilinear_BCs.ipynb)\n\n...But, for the moment, we're actually just using this because it writes the file `gridfunction_defines.h`.\n\n\n```python\nimport CurviBoundaryConditions.CurviBoundaryConditions as cbcs\ncbcs.Set_up_CurviBoundaryConditions(Ccodesdir,enable_copy_of_static_Ccodes=False)\n```\n\n Wrote to file \"GiRaFFE_staggered_new_way_standalone_Ccodes/parity_conditions_symbolic_dot_products.h\"\n Evolved parity: ( AD0:1, AD1:2, AD2:3, StildeD0:1, StildeD1:2, StildeD2:3,\n psi6Phi:0 )\n \n AuxEvol parity: ( BU0:1, BU1:2, BU2:3, B_lU0:1, B_lU1:2, B_lU2:3, B_rU0:1,\n B_rU1:2, B_rU2:3, BstaggerU0:1, BstaggerU1:2, BstaggerU2:3,\n Bstagger_lU0:1, Bstagger_lU1:2, Bstagger_lU2:3, Bstagger_rU0:1,\n Bstagger_rU1:2, Bstagger_rU2:3, Stilde_flux_HLLED0:1,\n Stilde_flux_HLLED1:2, Stilde_flux_HLLED2:3, ValenciavU0:1,\n ValenciavU1:2, ValenciavU2:3, Valenciav_lU0:1, Valenciav_lU1:2,\n Valenciav_lU2:3, Valenciav_llU0:1, Valenciav_llU1:2, Valenciav_llU2:3,\n Valenciav_lrU0:1, Valenciav_lrU1:2, Valenciav_lrU2:3, Valenciav_rU0:1,\n Valenciav_rU1:2, Valenciav_rU2:3, Valenciav_rlU0:1, Valenciav_rlU1:2,\n Valenciav_rlU2:3, Valenciav_rrU0:1, Valenciav_rrU1:2, Valenciav_rrU2:3,\n alpha:0, alpha_face:0, betaU0:1, betaU1:2, betaU2:3, beta_faceU0:1,\n beta_faceU1:2, beta_faceU2:3, cmax_x:0, cmax_y:0, cmax_z:0, cmin_x:0,\n cmin_y:0, cmin_z:0, gammaDD00:4, gammaDD01:5, gammaDD02:6, gammaDD11:7,\n gammaDD12:8, gammaDD22:9, gamma_faceDD00:4, gamma_faceDD01:5,\n gamma_faceDD02:6, gamma_faceDD11:7, gamma_faceDD12:8, gamma_faceDD22:9,\n psi6_temp:0, psi6center:0 )\n Wrote to file \"GiRaFFE_staggered_new_way_standalone_Ccodes/EigenCoord_Cart_to_xx.h\"\n\n\n\n\n# Step 5: `GiRaFFE_NRPy_standalone.c`: The Main C Code \\[Back to [top](#toc)\\]\n$$\\label{mainc}$$\n\n\n```python\n# Part P0: Define REAL, set the number of ghost cells NGHOSTS (from NRPy+'s FD_CENTDERIVS_ORDER),\n# and set the CFL_FACTOR (which can be overwritten at the command line)\n\nwith open(os.path.join(Ccodesdir,\"GiRaFFE_NRPy_REAL__NGHOSTS__CFL_FACTOR.h\"), \"w\") as file:\n file.write(\"\"\"\n// Part P0.a: Set the number of ghost cells, from NRPy+'s FD_CENTDERIVS_ORDER\n#define NGHOSTS \"\"\"+str(3)+\"\"\"\n#define NGHOSTS_A2B \"\"\"+str(2)+\"\"\"\n// Part P0.b: Set the numerical precision (REAL) to double, ensuring all floating point\n// numbers are stored to at least ~16 significant digits\n#define REAL \"\"\"+REAL+\"\"\"\n// Part P0.c: Set the CFL Factor. Can be overwritten at command line.\nREAL CFL_FACTOR = \"\"\"+str(default_CFL_FACTOR)+\";\")\n```\n\n\n```python\n#include \"GiRaFFE_NRPy_REAL__NGHOSTS__CFL_FACTOR.h\"\n#include \"declare_Cparameters_struct.h\"\ndef add_to_Cfunction_dict_main__GiRaFFE_NRPy_3D_tests_staggered():\n includes = [\"NRPy_basic_defines.h\", \"GiRaFFE_main_defines.h\", \"NRPy_function_prototypes.h\", \"time.h\", \"set_initial_spacetime_metric_data.h\", \"initial_data.h\"]\n desc = \"\"\"main() function:\nStep 0: Read command-line input, set up grid structure, allocate memory for gridfunctions, set up coordinates\nStep 1: Set up scalar wave initial data\nStep 2: Evolve scalar wave initial data forward in time using Method of Lines with RK4 algorithm,\n applying quadratic extrapolation outer boundary conditions.\nStep 3: Output relative error between numerical and exact solution.\nStep 4: Free all allocated memory\n\"\"\"\n prefunc = \"\"\"const int NSKIP_1D_OUTPUT = 1;\nconst REAL outer_integration_radius = 1.5; const REAL inner_integration_radius = 0.6;\n#define LOOP_ALL_GFS_GPS(ii) _Pragma(\"omp parallel for\") \\\n for(int (ii)=0;(ii) SQR(inner_integration_radius)) {\n const int idx = IDX3S(i0,i1,i2);\n // Compute the sum of the squares of the difference between numerical and exact:\n integrated_quantities[0] += SQR(auxevol_gfs[IDX4ptS(BU0GF,idx)] - auxevol_gfs_exact[IDX4ptS(BU0GF,idx)]);\n integrated_quantities[1] += SQR(auxevol_gfs[IDX4ptS(BU1GF,idx)] - auxevol_gfs_exact[IDX4ptS(BU1GF,idx)]);\n integrated_quantities[2] += SQR(auxevol_gfs[IDX4ptS(BU2GF,idx)] - auxevol_gfs_exact[IDX4ptS(BU2GF,idx)]);\n integrated_quantities[3] += SQR(y_n_gfs[IDX4ptS(AD0GF,idx)] - evol_gfs_exact[IDX4ptS(AD0GF,idx)]);\n integrated_quantities[4] += SQR(y_n_gfs[IDX4ptS(AD1GF,idx)] - evol_gfs_exact[IDX4ptS(AD1GF,idx)]);\n integrated_quantities[5] += SQR(y_n_gfs[IDX4ptS(AD2GF,idx)] - evol_gfs_exact[IDX4ptS(AD2GF,idx)]);\n integrated_quantities[6] += SQR(y_n_gfs[IDX4ptS(STILDED0GF,idx)] - evol_gfs_exact[IDX4ptS(STILDED0GF,idx)]);\n integrated_quantities[7] += SQR(y_n_gfs[IDX4ptS(STILDED1GF,idx)] - evol_gfs_exact[IDX4ptS(STILDED1GF,idx)]);\n integrated_quantities[8] += SQR(y_n_gfs[IDX4ptS(STILDED2GF,idx)] - evol_gfs_exact[IDX4ptS(STILDED2GF,idx)]);\n integrated_quantities[9] += SQR(auxevol_gfs[IDX4ptS(VALENCIAVU0GF,idx)] - auxevol_gfs_exact[IDX4ptS(VALENCIAVU0GF,idx)]);\n integrated_quantities[10] += SQR(auxevol_gfs[IDX4ptS(VALENCIAVU1GF,idx)] - auxevol_gfs_exact[IDX4ptS(VALENCIAVU1GF,idx)]);\n integrated_quantities[11] += SQR(auxevol_gfs[IDX4ptS(VALENCIAVU2GF,idx)] - auxevol_gfs_exact[IDX4ptS(VALENCIAVU2GF,idx)]);\n integrated_quantities[12] += SQR(y_n_gfs[IDX4ptS(PSI6PHIGF,idx)] - evol_gfs_exact[IDX4ptS(PSI6PHIGF,idx)]);\n num_points++;\n }\n }\n }\n }\n // Divide by N, take the square root:\n for(int ii=0; ii t+dt) in time using\n // chosen RK-like MoL timestepping algorithm\n#include \"MoLtimestepping/RK_MoL.h\"\n } // End main loop to progress forward in time.\n\n // Step 4: Free all allocated memory\n#include \"MoLtimestepping/RK_Free_Memory.h\"\n free(auxevol_gfs);\n free(auxevol_gfs_exact);\n free(evol_gfs_exact);\n for(int i=0;i<3;i++) free(xx[i]);\n return 0;\n\"\"\"\n add_to_Cfunction_dict(\n includes=includes,\n desc=desc,\n c_type=c_type, name=name, params=params,\n prefunc = prefunc, body=body,\n rel_path_to_Cparams=os.path.join(\".\"), enableCparameters=False)\n```\n\n\n```python\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_staggered_Source_Terms as stgsrc\nstgsrc.add_to_Cfunction_dict__GiRaFFE_NRPy_staggered_Source_Terms()\n\nmd.add_to_Cfunction_dict__cons_to_prims(md.StildeD,md.BU,md.gammaDD,md.betaU,md.alpha,includes=[\"NRPy_basic_defines.h\",\"GiRaFFE_basic_defines.h\"])\nmd.add_to_Cfunction_dict__prims_to_cons(md.gammaDD,md.betaU,md.alpha,md.ValenciavU,md.BU,md.sqrt4pi,includes=[\"NRPy_basic_defines.h\",\"GiRaFFE_basic_defines.h\"])\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_Source_Terms as source\nsource.add_to_Cfunction_dict__functions_for_StildeD_source_term(md.outCparams,md.gammaDD,md.betaU,md.alpha,\n md.ValenciavU,md.BU,md.sqrt4pi,includes=[\"NRPy_basic_defines.h\",\"GiRaFFE_basic_defines.h\"])\nimport GiRaFFE_NRPy.Stilde_flux as Sf\nSf.add_to_Cfunction_dict__Stilde_flux(includes=[\"NRPy_basic_defines.h\",\"GiRaFFE_basic_defines.h\"], inputs_provided = True, alpha_face=md.alpha_face, gamma_faceDD=md.gamma_faceDD,\n beta_faceU=md.beta_faceU, Valenciav_rU=md.Valenciav_rU, B_rU=md.B_rU,\n Valenciav_lU=md.Valenciav_lU, B_lU=md.B_lU, sqrt4pi=md.sqrt4pi,write_cmax_cmin=True)\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_staggered_Afield_flux as Af\nAf.add_to_Cfunction_dict__GiRaFFE_NRPy_staggered_Afield_flux()\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_Metric_Face_Values as FCVAL\nFCVAL.add_to_Cfunction_dict__GiRaFFE_NRPy_FCVAL(includes=[\"NRPy_basic_defines.h\",\"GiRaFFE_basic_defines.h\"])\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_PPM as PPM\nPPM.add_to_Cfunction_dict__GiRaFFE_NRPy_PPM(Ccodesdir)\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_staggered_A2B as A2B\nA2B.add_to_Cfunction_dict__GiRaFFE_NRPy_staggered_A2B()\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_BCs as BC\nBC.add_to_Cfunction_dict__GiRaFFE_NRPy_BCs()\n\nmd.add_to_Cfunction_dict__driver_function()\nadd_to_Cfunction_dict_main__GiRaFFE_NRPy_3D_tests_staggered()\n```\n\nNow, we will register the remaining C functions and contributions to `NRPy_basic_defines.h`, then we output `NRPy_basic_defines.h` and `NRPy_function_prototypes.h`.\n\n\n```python\nimport outputC as outC\noutC.outputC_register_C_functions_and_NRPy_basic_defines() # #define M_PI, etc.\n# Declare paramstruct, register set_Cparameters_to_default(),\n# and output declare_Cparameters_struct.h and set_Cparameters[].h:\noutC.NRPy_param_funcs_register_C_functions_and_NRPy_basic_defines(os.path.join(Ccodesdir))\n\ngri.register_C_functions_and_NRPy_basic_defines(enable_griddata_struct=False, enable_bcstruct_in_griddata_struct=False,\n enable_rfmstruct=False,\n enable_MoL_gfs_struct=False,\n extras_in_griddata_struct=None) # #define IDX3S(), etc.\nfin.register_C_functions_and_NRPy_basic_defines(NGHOSTS_account_for_onezone_upwind=True,\n enable_SIMD=enable_SIMD) # #define NGHOSTS, and UPWIND() macro if SIMD disabled\n\n# Output functions for computing all finite-difference stencils.\n# Must be called after defining all functions depending on FD stencils.\nif enable_FD_functions:\n fin.output_finite_difference_functions_h(path=Ccodesdir)\n\n# Call this last: Set up NRPy_basic_defines.h and NRPy_function_prototypes.h.\noutC.construct_NRPy_basic_defines_h(Ccodesdir, enable_SIMD=enable_SIMD)\n\nwith open(os.path.join(Ccodesdir,\"GiRaFFE_basic_defines.h\"),\"w\") as file:\n file.write(\"\"\"#define NGHOSTS_A2B \"\"\"+str(2)+\"\\n\"+\"\"\"extern int kronecker_delta[4][3];\n\nextern int MAXFACE;\nextern int NUL;\nextern int MINFACE;\n\n// Some additional constants needed for PPM:\nextern int VX,VY,VZ,\n BX_CENTER,BY_CENTER,BZ_CENTER,BX_STAGGER,BY_STAGGER,BZ_STAGGER,\n VXR,VYR,VZR,VXL,VYL,VZL; //<-- Be _sure_ to define MAXNUMVARS appropriately!\nextern int NUM_RECONSTRUCT_GFS;\n\n// Structure to track ghostzones for PPM:\ntypedef struct __gf_and_gz_struct__ {\n REAL *gf;\n int gz_lo[4],gz_hi[4];\n} gf_and_gz_struct;\n\"\"\")\n\nwith open(os.path.join(Ccodesdir,\"GiRaFFE_main_defines.h\"),\"w\") as file:\n file.write(\"\"\"#define NGHOSTS_A2B \"\"\"+str(2)+\"\\n\"+PPM.kronecker_code+\"\"\"const int MAXFACE = -1;\nconst int NUL = +0;\nconst int MINFACE = +1;\n\n// Some additional constants needed for PPM:\nconst int VX=0,VY=1,VZ=2,\n BX_CENTER=3,BY_CENTER=4,BZ_CENTER=5,BX_STAGGER=6,BY_STAGGER=7,BZ_STAGGER=8,\n VXR=9,VYR=10,VZR=11,VXL=12,VYL=13,VZL=14; //<-- Be _sure_ to define MAXNUMVARS appropriately!\nconst int NUM_RECONSTRUCT_GFS = 15;\n\n// Structure to track ghostzones for PPM:\ntypedef struct __gf_and_gz_struct__ {\n REAL *gf;\n int gz_lo[4],gz_hi[4];\n} gf_and_gz_struct;\n\"\"\")\n\noutC.construct_NRPy_function_prototypes_h(Ccodesdir)\n```\n\n\n```python\ncmd.new_C_compile(Ccodesdir, os.path.join(\"output\", \"GiRaFFE_NRPy_standalone\"),\n uses_free_parameters_h=True, compiler_opt_option=\"fast\") # fastdebug or debug also supported\n\n# !gcc -g -O2 -fopenmp GiRaFFE_standalone_Ccodes/GiRaFFE_NRPy_standalone.c -o GiRaFFE_NRPy_standalone -lm\n\n# Change to output directory\nos.chdir(outdir)\n# Clean up existing output files\ncmd.delete_existing_files(\"out*.txt\")\ncmd.delete_existing_files(\"out*.png\")\n# cmd.Execute(os.path.join(Ccodesdir,\"output\",\"GiRaFFE_NRPy_standalone\"), \"640 16 16\", os.path.join(outdir,\"out640.txt\"))\ncmd.Execute(\"GiRaFFE_NRPy_standalone\", \"64 64 64\",\"out64.txt\")\n# cmd.Execute(\"GiRaFFE_NRPy_standalone\", \"239 15 15\",\"out239.txt\")\n# !OMP_NUM_THREADS=1 valgrind --track-origins=yes -v ./GiRaFFE_NRPy_standalone 1280 32 32\n# Return to root directory\nos.chdir(os.path.join(\"../../\"))\n```\n\n (EXEC): Executing `make -j10`...\n (BENCH): Finished executing in 0.8128435611724854 seconds.\n Finished compilation.\n (EXEC): Executing `taskset -c 0,1,2,3 ./GiRaFFE_NRPy_standalone 64 64 64`...\n (BENCH): Finished executing in 18.257782697677612 seconds.\n\n\nNow, we will load the data generated by the simulation and plot it in order to test for convergence. \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 0 1 2 3 4 5 6 7 8 9 10 11 12 13\nlabels = [\"x\",\"BU0\",\"BU1\",\"BU2\",\"AD0\",\"AD1\",\"AD2\",\"StildeD0\",\"StildeD1\",\"StildeD2\",\"ValenciavU0\",\"ValenciavU1\",\"ValenciavU2\", \"psi6Phi\"]\nData_numer = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out64-00000010.txt\"))\n# Data_num_2 = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out239-00000080.txt\"))\n# Data_old = np.loadtxt(\"/home/penelson/OldCactus/Cactus/exe/ABE-GiRaFFEfood_1D_AlfvenWave/giraffe-grmhd_primitives_bi.x.asc\")\n# Data_o_2 = np.loadtxt(\"/home/penelson/OldCactus/Cactus/exe/ABE-GiRaFFEfood_1D_AlfvenWave_2/giraffe-grmhd_primitives_bi.x.asc\")\n# Data_numer = Data_old[5000:5125,11:15] # The column range is chosen for compatibility with the plotting script.\n# Data_num_2 = Data_o_2[19600:19845,11:15] # The column range is chosen for compatibility with the plotting script.\nData_exact = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out64-00000010.txt\"))\n# Data_exa_2 = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out239-00000080_exact.txt\"))\n\npredicted_order = 2.0\ncolumn = 3\nplt.figure()\n# # plt.plot(Data_exact[2:-2,0],np.log2(np.absolute((Data_numer[2:-2,column]-Data_exact[2:-2,column])/\\\n# # (Data_num_2[2:-2:2,column]-Data_exa_2[2:-2:2,column]))),'.')\nplt.plot(Data_exact[:,0],Data_exact[:,column])\nplt.plot(Data_exact[:,0],Data_numer[:,column],'.')\n# plt.xlim(-0.0,1.0)\n# # plt.ylim(-1.0,5.0)\n# # plt.ylim(-0.0005,0.0005)\n# plt.xlabel(\"x\")\n# plt.ylabel(\"BU2\")\nplt.show()\n\n# Plotting scripts for comparison with original GiRaFFE:\n# old_files = [\"\",\n# \"giraffe-grmhd_primitives_bi.x.asc\",\"giraffe-grmhd_primitives_bi.x.asc\",\"giraffe-grmhd_primitives_bi.x.asc\",\n# \"giraffe-em_ax.x.asc\",\"giraffe-em_ay.x.asc\",\"giraffe-em_az.x.asc\",\n# \"giraffe-grmhd_conservatives.x.asc\",\"giraffe-grmhd_conservatives.x.asc\",\"giraffe-grmhd_conservatives.x.asc\",\n# \"giraffe-grmhd_primitives_allbutbi.x.asc\",\"giraffe-grmhd_primitives_allbutbi.x.asc\",\"giraffe-grmhd_primitives_allbutbi.x.asc\",\n# \"giraffe-em_psi6phi.x.asc\"]\n# column = 6\n# column_old = [0,12,13,14,12,12,12,12,13,14,12,13,14,12]\n# old_path = \"/home/penelson/Cactus/exe/ABE-GiRaFFEfood_ExactWald_newcode_agreement\"\n# perturb_path = \"/home/penelson/Cactus/exe/ABE-GiRaFFEfood_ExactWald_newcode_agreement_pert\"\n# new_path = os.path.join(Ccodesdir,\"output\")\n# data_old = np.loadtxt(os.path.join(old_path,old_files[column]))\n# data_per = np.loadtxt(os.path.join(perturb_path,old_files[column]))\n# n=80\n# data_old = data_old[n*70:n*70+70,:]# Select only the nth timestep\n# data_per = data_per[n*70:n*70+70,:]# Select only the nth timestep\n# data_new = np.loadtxt(os.path.join(new_path,\"out64-00000080.txt\"))\n\n# deltaA_old = data_old[125:250,:] - data_old[0:125,:]\n# data_new_t0 = np.loadtxt(os.path.join(new_path,\"out119-00000000.txt\"))\n# deltaA_new = data_new[:,:] - data_new_t0[:,:]\n\n# plt.figure()\n# plt.semilogy(data_new[:,0],(data_new[:,column]-data_old[:,column_old[column]])/(data_new[:,column]+data_old[:,column_old[column]]),label=\"Old vs. New\")\n\n# plt.plot(data_new[4:22,0],data_new[4:22,column]-data_old[4:22,column_old[column]])\n# plt.plot(data_new[49:-4,0],data_new[49:-4,column]-data_old[49:-4,column_old[column]])\n\n# plt.plot(data_new[:,0],data_old[:,column_old[column]])\n# plt.plot(data_new[:,0],data_new[:,column],'.')\n\n# plt.plot(data_new[:22,0],data_old[:22,column_old[column]])\n# plt.plot(data_new[49:,0],data_old[49:,column_old[column]])\n# plt.plot(data_new[:22,0],data_new[:22,column],'.')\n# plt.plot(data_new[49:,0],data_new[49:,column],'.')\n\n# plt.plot(data_new[3:-3,0],deltaA_new[3:-3,column],'.')\n# plt.plot(data_new[3:-3,0],deltaA_old[3:-3,column_old[column]]-deltaA_new[3:-3,column])\n# plt.xlabel(labels[0])\n# plt.ylabel(labels[column])\n# plt.show()\n\n# plt.figure()\n# plt.semilogy(data_new[:,0],(data_old[:,column_old[column]]-data_per[:,column_old[column]])/(data_old[:,column_old[column]]+data_per[:,column_old[column]]),label=\"Old vs. Perturbed\")\n# plt.xlabel(labels[0])\n# plt.ylabel(\"E_rel in \"+labels[column])\n# plt.legend()\n# plt.show()\n```\n\nHere, we will use the output L2 norm data and find its convergence to determine how well our code converges.\n\nBy doing so, we show that the truncation error dominates and converges to zero at the expected rate. In the code above, we output the L2 norm within a thick spherical shell; for some quantity $Q$, this is given as \n$$\n| Q_{\\rm approx} - Q_{\\rm exact}| = \\sqrt{\\frac{1}{N} \\sum_{ijk} \\left( Q_{\\rm approx} - Q_{\\rm exact} \\right)^2}\n$$\n\nHere, we import that data and calculate the convergence in the usual way, \n$$\nk = \\log_2 \\left( \\frac{F - F_1}{F - F_2} \\right),\n$$\nwhere $k$ is the convergence order, $F$ is the exact solution, $F_1$ is the approximate solution on the coarser grid with resolution $\\Delta x$, and $F_2$ is the approximate solution on the finer grid with resolution $\\Delta x/2$. Note that for the exact solution, the L2 norm is $0$.\n\n\n```python\n# l2_lo = np.loadtxt(os.path.join(new_path,\"out64-L2.txt\"))\n# l2_hi = np.loadtxt(os.path.join(new_path,\"out128-L2.txt\"))\n# # 0 1 2 3 4 5 6 7 8 9 10 11 12 13\n# labels = [\"n\",\"BU0\",\"BU1\",\"BU2\",\"AD0\",\"AD1\",\"AD2\",\"StildeD0\",\"StildeD1\",\"StildeD2\",\"ValenciavU0\",\"ValenciavU1\",\"ValenciavU2\", \"psi6Phi\"]\n\n# def conv_order(low,high):\n# order = np.log2(low/high)\n# return order\n\n# for column in range(1,len(labels)):\n# print(labels[column]+\": \"+str(conv_order(l2_lo[1,column],l2_hi[2,column])))\n```\n\nThis code will create an animation of the wave over time.\n\n\n```python\n# import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import savefig\nfrom IPython.display import HTML\nimport matplotlib.image as mgimg\n\nimport glob\nimport sys\nfrom matplotlib import animation\n\ncmd.delete_existing_files(\"out64-00*.png\")\nglobby = glob.glob(os.path.join(Ccodesdir,'output','out64-00*.txt'))\nfile_list = []\nfor x in sorted(globby):\n file_list.append(x)\n\nnumber_of_files = int(len(file_list))\n\nfor timestep in range(number_of_files):\n fig = plt.figure()\n numer_filename = file_list[timestep]\n exact_filename = os.path.join(Ccodesdir,'output','out64-00000000.txt')\n Numer = np.loadtxt(numer_filename)\n Exact = np.loadtxt(exact_filename)\n\n plt.title(\"Exact Wald\")\n plt.xlabel(\"x\")\n plt.ylabel(\"BU2\")\n# plt.xlim(-0.5,0.5)\n# plt.ylim(1.0,1.7)\n\n plt.plot(Numer[3:22,0],Numer[3:22,3],'.',label=\"Numerical\")\n plt.plot(Numer[49:-3,0],Numer[49:-3,3],'.',label=\"Numerical\")\n plt.plot(Exact[3:22,0],Exact[3:22,3],label=\"Exact\")\n plt.plot(Exact[49:-3,0],Exact[49:-3,3],label=\"Exact\")\n plt.legend()\n savefig(numer_filename+\".png\",dpi=150)\n plt.close(fig)\n sys.stdout.write(\"%c[2K\" % 27)\n sys.stdout.write(\"Processing file \"+numer_filename+\"\\r\")\n sys.stdout.flush()\n```\n\n \u001b[2KProcessing file GiRaFFE_staggered_new_way_standalone_Ccodes/output/out64-00000087.txt\r\n\n\n```python\n## VISUALIZATION ANIMATION, PART 2: Combine PNGs to generate movie ##\n# https://stackoverflow.com/questions/14908576/how-to-remove-frame-from-matplotlib-pyplot-figure-vs-matplotlib-figure-frame\n# https://stackoverflow.com/questions/23176161/animating-pngs-in-matplotlib-using-artistanimation\n# !rm -f GiRaFFE_NRPy-1D_tests.mp4\ncmd.delete_existing_files(\"GiRaFFE_NRPy-3D_tests.mp4\")\n\nfig = plt.figure(frameon=False)\nax = fig.add_axes([0, 0, 1, 1])\nax.axis('off')\n\nmyimages = []\n\nfor i in range(number_of_files):\n img = mgimg.imread(file_list[i]+\".png\")\n imgplot = plt.imshow(img)\n myimages.append([imgplot])\n\nani = animation.ArtistAnimation(fig, myimages, interval=100, repeat_delay=1000)\nplt.close()\nani.save('GiRaFFE_NRPy-1D_tests.mp4', fps=5,dpi=150)\n```\n\n\n```python\n%%HTML\n\n```\n\n\n\n\n\n\n\n```python\nimport cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\ncmd.output_Jupyter_notebook_to_LaTeXed_PDF(\"Tutorial-GiRaFFE_NRPy_Main_Driver\",location_of_template_file=os.path.join(\"..\"))\n```\n\n Created Tutorial-GiRaFFE_NRPy_Main_Driver.tex, and compiled LaTeX file to\n PDF file Tutorial-GiRaFFE_NRPy_Main_Driver.pdf\n\n", "meta": {"hexsha": "3b1a5de52858451a05a5e01be101074999cfc370", "size": 81732, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "in_progress/Tutorial-Start_to_Finish-GiRaFFE_NRPy-3D_tests-staggered_new_way.ipynb", "max_stars_repo_name": "stevenrbrandt/nrpytutorial", "max_stars_repo_head_hexsha": "219af363f810cc46ea8955a9d28cf075f2252582", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 66, "max_stars_repo_stars_event_min_datetime": "2018-06-26T22:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T21:12:33.000Z", "max_issues_repo_path": "in_progress/Tutorial-Start_to_Finish-GiRaFFE_NRPy-3D_tests-staggered_new_way.ipynb", "max_issues_repo_name": "stevenrbrandt/nrpytutorial", "max_issues_repo_head_hexsha": "219af363f810cc46ea8955a9d28cf075f2252582", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14, "max_issues_repo_issues_event_min_datetime": "2020-02-13T16:09:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-12T14:59:59.000Z", "max_forks_repo_path": "in_progress/Tutorial-Start_to_Finish-GiRaFFE_NRPy-3D_tests-staggered_new_way.ipynb", "max_forks_repo_name": "stevenrbrandt/nrpytutorial", "max_forks_repo_head_hexsha": "219af363f810cc46ea8955a9d28cf075f2252582", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 30, "max_forks_repo_forks_event_min_datetime": "2019-01-09T09:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T18:45:08.000Z", "avg_line_length": 67.6589403974, "max_line_length": 17704, "alphanum_fraction": 0.6753535947, "converted": true, "num_tokens": 15559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.30514129670474077}} {"text": "```python\n# 그래프, 수학 기능 추가\n# Add graph and math features\nimport pylab as py\nimport numpy as np\nimport numpy.linalg as nl\n# 기호 연산 기능 추가\n# Add symbolic operation capability\nimport sympy as sy\n\n\n```\n\n# 파이썬에서의 선형대수 : 표준 기능
Linear Algebra in Python: Standard Library\n\n\n(Karlijn Willems, SciPy Cheat Sheet: Linear Algebra in Python, DataCamp, 2017/02/07, https://www.datacamp.com/community/blog/python-scipy-cheat-sheet)\n\n\n\n(Wikipedia contributors. Linear algebra. Wikipedia, The Free Encyclopedia. August 2, 2018, 17:17 UTC. Available at: https://en.wikipedia.org/w/index.php?title=Linear_algebra&oldid=853134963. Accessed August 11, 2018. )\n\n\n\n**선형 대수**란 간단히 말하면 벡터와 행렬에 관한 수학의 한 분야이다.
\nIn short, **Linear Algebra** is an area of mathematics about vectors and matrices.\n\n\n\n파이썬 프로그래밍 언어의 기본 기능만으로도 선형 대수 문제를 해결하는 것이 가능은 하나, 보다 효율을 높이기 위해, 1990년대 이후, 여러 개발자들의 공헌으로 [**사이파이** 계열 확장 모듈](https://www.scipy.org/stackspec.html)을 개발하였다.
\nWe can solve linear algebra with default features of python. However, to make it more efficient, since 1990's, a group of community developers contributed in developing [**SciPy** stack](https://www.scipy.org/stackspec.html).\n\n\n\n여기서는 다른 모듈을 사용하지 않고 파이썬 자체의 문법만 사용할 것이다.
\nHere we would use the Python grammar itself without using other modules.\n\n\n\n# 벡터
Vector\n\n\n\n벡터는 크기만이 아니라 방향도 가지는 양이다.
\nVectors is a quantity having both its magnitude and its direction.\n\n\n\n벡터에 관해 아래 비디오 링크를 참고할 수 있다. (5:48)
\nRegarding the vector, you can check the following link. (5:48)
\n
\n[](https://www.youtube.com/watch?v=br7tS1t2SFE)\n\n\n\n예를 들어 2차원 벡터를 생각해 보자.
\nFor example, let's think about two-dimensional vectors (2D vectors).\n\n\n\n## 벡터 정의 : 표준 기능
Definition of vectors : Standard Library\n\n\n\n리스트 list 또는 튜플 tuple 을 이용하여 다음과 같이 벡터를 정의할 수 있다.
\nWe can define the vectors using the list or tuple as follows.\n\n\n\n\n```python\n# ref : https://www.youtube.com/watch?v=8QihetGj3pg\na = [6, -2] # list\nb = (-4, 4) # tuple\n\n\n```\n\n\n```python\na\n\n\n```\n\n\n```python\nb\n\n\n```\n\n위 2차원 벡터를 한번 그려 보자
\nLet's plot the 2D vectors above.\n\n\n\n\n```python\ndef draw_2dvec(x, y, x0=0, y0=0, color='k', name=None):\n py.quiver(x0, y0, x, y, color=color, angles='xy', scale_units='xy', scale=1)\n if name is not None:\n if not name.startswith('$'):\n vec_str = '$\\\\vec{%s}$' % name\n else:\n vec_str = name\n py.text(0.5 * x + x0, 0.5 * y + y0, vec_str)\n\n\n```\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], name='b')\n\npy.axis('equal')\npy.xlim((-8, 8))\npy.ylim((-8, 8))\npy.grid(True)\n\n\n```\n\n## 벡터 합 : 표준 기능
Sum of two vectors : Standard Library\n\n\n\n두 벡터를 더해 보자.
Let's add two vectors.\n\n\n\n\n```python\ndef add_two_vectors(a, b):\n\n result = []\n\n for ai, bi in zip(a, b):\n print(f\"zip : ai={ai}, bi={bi}\")\n result.append(ai + bi)\n \n return result\n\n\n```\n\n\n```python\na_plus_b = add_two_vectors(a, b)\n\n\n```\n\n\n```python\na_plus_b\n\n\n```\n\n이 벡터의 합을 그려보자.
\nLet's draw this sum of vectors.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a_plus_b[0], a_plus_b[1], name='$\\\\vec{a}+\\\\vec{b}$')\n\npy.axis('equal')\npy.xlim((-8, 8))\npy.ylim((-8, 8))\npy.grid(True)\n\n\n```\n\n어떻게 해서 벡터의 합은 이렇게 된 것일까? $\\vec{b}$ 벡터의 시작점을 $\\vec{a}$ 벡터의 끝점으로 옮겨 보자.
\nHow come this vector sum came up like this? Let's move the starting point of $\\vec{b}$ to the starting point of $\\vec{a}$.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], a[0], a[1], color=(0.5, 0.5, 0.5), name='b')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a_plus_b[0], a_plus_b[1], name='$\\\\vec{a}+\\\\vec{b}$')\n\npy.axis('equal')\npy.xlim((-8, 8))\npy.ylim((-8, 8))\npy.grid(True)\n\n\n```\n\n여기서 $\\vec{a}$, $\\vec{b}$ 그리고 $\\vec{a} + \\vec{b}$ 가 삼각형을 이룬다는 것을 알 수 있다.
\nHere, you can see that $\\vec{a}$, $\\vec{b}$, and $\\vec{a} + \\vec{b}$ form a triangle.\n\n\n\n$\\vec{b}$의 시작점을 $\\vec{a}$의 끝점으로 옮긴 결과, 회색 벡터의 끝점이 $\\vec{a} + \\vec{b}$ 의 끝점과 같다.
\nAs the result of moving the start point of $\\vec{b}$ to the end point of $\\vec{a}$, the end points of the gray vector and $\\vec{a} + \\vec{b}$ are identicial.\n\n\n\n### 교환법칙 : 표준 기능
Commutative Law : Standard Library\n\n\n\n벡터의 합의 순서를 바꾸어 보자.
Let's change the order of addition.\n\n\n\n\n```python\nb_plus_a = add_two_vectors(b, a)\n\n\n```\n\n\n```python\nb_plus_a\n\n\n```\n\n이는 $\\vec{a}+\\vec{b}$와 같다.
This is the same as $\\vec{a}+\\vec{b}$.\n\n\n\n이번에도 시각화 해 보자.
Let's visualize again.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a[0], a[1], b[0], b[1], color=(0.75, 0.75, 0.75), name='a')\ndraw_2dvec(b_plus_a[0], b_plus_a[1], name='$\\\\vec{b}+\\\\vec{a}$')\n\npy.axis('equal')\npy.xlim((-8, 8))\npy.ylim((-8, 8))\npy.grid(True)\n\n\n```\n\n비슷하게, $\\vec{a}$, $\\vec{b}$ 그리고 $\\vec{b} + \\vec{a}$ 가 삼각형을 이룬다는 것을 알 수 있다.
\nSimilarly, you can see that $\\vec{a}$, $\\vec{b}$, and $\\vec{b} + \\vec{a}$ form a triangle.\n\n\n\n이번에는 $\\vec{a}$의 시작점을 $\\vec{b}$의 끝점으로 옮겨 보았다. 덧셈의 순서와는 상관 없이, 회색 벡터의 끝점이 $\\vec{b} + \\vec{a}$ 의 끝점과 일치하는 것을 확인할 수 있다.
\nThis time, we moved the start point of $\\vec{a}$ to the end point of $\\vec{b}$. We can confirm that regardless of the order of addition, the end points of the gray vector and $\\vec{a} + \\vec{b}$ are identicial.\n\n\n\n두 방식을 모두 표시해 보자.
Let's indicate both ways.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a[0], a[1], b[0], b[1], color=(0.75, 0.75, 0.75), name='a')\ndraw_2dvec(b[0], b[1], a[0], a[1], color=(0.5, 0.5, 0.5), name='b')\ndraw_2dvec(b_plus_a[0], b_plus_a[1], name='$\\\\vec{a}+\\\\vec{b}$')\n\npy.axis('equal')\npy.xlim((-8, 8))\npy.ylim((-8, 8))\npy.grid(True)\n\n\n```\n\n벡터 합은 $\\vec{a}$와 $\\vec{b}$가 이루는 평행 사변형의 한 대각선임을 알 수 있다.
\nWe can see that the vector sum is one of diagonals of the parallogram of $\\vec{a}$'s and $\\vec{b}$'s.\n\n\n\n## 스칼라와 벡터의 곱 : 표준 기능
Product of a Scalar and a Vector : Standard Library\n\n\n\n벡터에 어떤 스칼라 값을 곱해 보자.
Let's multiply a scalar value to a vector.\n\n\n\n\n```python\ndef scalar_mul(a, x_vector):\n result = [0.0] * len(x_vector)\n \n for k in range(len(x_vector)):\n result[k] = a * x_vector[k]\n\n return result\n\n\n```\n\n\n```python\nx = (2, 1)\nalpha = 3\nalpha_x = scalar_mul(alpha, x)\n\n\n```\n\n\n```python\nalpha_x\n\n\n```\n\n그림으로 표시해 보자.
Let's draw.\n\n\n\n\n```python\ndraw_2dvec(alpha_x[0], alpha_x[1], name='$\\\\alpha\\\\vec{x}$', color=(0.5, 0.5, 0.5))\ndraw_2dvec(x[0], x[1], name='x')\n\npy.axis('equal')\npy.xlim((-6, 6))\npy.ylim((-6, 6))\npy.grid(True)\n\n\n```\n\n방향은 바뀌지 않고 크기만 달라지는 것을 알 수 있다.
\nThe direction does not change but the magnitude changes.\n\n\n\n스칼라 값이 음인 경우는 어떠할까?
What if scalar value is negative?\n\n\n\n\n```python\nx = (2, 1)\nbeta = -1\nbeta_x = scalar_mul(beta, x)\n\n\n```\n\n\n```python\nbeta_x\n\n\n```\n\n\n```python\ndraw_2dvec(alpha_x[0], alpha_x[1], name='$\\\\alpha\\\\vec{x}$', color=(0.5, 0.5, 0.5))\ndraw_2dvec(beta_x[0], beta_x[1], name='$\\\\beta\\\\vec{x}$', color=py.ones((1, 3)) * 0.25)\ndraw_2dvec(x[0], x[1], name='x')\n\npy.axis('equal')\npy.xlim((-6, 6))\npy.ylim((-6, 6))\npy.grid(True)\n\n\n```\n\n음의 스칼라를 곱하면 방향이 반대로 된다는 것을 알 수 있다.
\nIn case of the negative scalar, the direction becomes the opposite.\n\n\n\n## 벡터의 차 : 표준 기능
Difference of two vectors : Standard Library\n\n\n\n어떤 벡터 $\\vec{b}$를 다른 벡터 $\\vec{a}$에서 빼는 셈에 대해 생각해 보자.
\nLet's think about subtracting a vector $\\vec{b}$ from another vector $\\vec{a}$.\n\n\n\n\n```python\na_minus_b = add_two_vectors(a, scalar_mul(-1, b))\n\n\n```\n\n\n```python\na_minus_b\n\n\n```\n\n그림으로 표시보자.
\nLet's visualize.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a_minus_b[0], a_minus_b[1], name='$\\\\vec{a}-\\\\vec{b}$')\n\npy.axis('equal')\npy.xlim((-10, 10))\npy.ylim((-10, 10))\npy.grid(True)\n\n\n```\n\n이번에는 어떻게 해서 벡터의 차가 이렇게 된 것인지 알아 보자. $\\vec{b}$ 벡터에 -1을 곱해서 시작점을 $\\vec{a}$ 벡터의 끝점으로 옮겨 보자.
\nLet's figure out the vector subtraction. Let's multiply by -1 to $\\vec{b}$ and move the starting point to the end point of $\\vec{a}$.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(-b[0], -b[1], a[0], a[1], color=(0.5, 0.5, 0.5), name='$-\\\\vec{b}$')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a_minus_b[0], a_minus_b[1], name='$\\\\vec{a}-\\\\vec{b}$')\n\npy.axis('equal')\npy.xlim((-10, 10))\npy.ylim((-10, 10))\npy.grid(True)\n\n\n```\n\n벡터 뺄셈은 부호를 바꾸어 더하는 것과 같다.
Subtracting a vector is equivalent to changing the sign of the vector and adding it.\n\n\n\n 이번에는 $\\vec{a}-\\vec{b}$ 의 시작점을 $\\vec{b}$의 끝점으로 옮겨 보자.
\n This time, let's move the start point of $\\vec{a}-\\vec{b}$ to the end point of $\\vec{b}$.\n\n\n\n\n```python\ndraw_2dvec(a[0], a[1], name='a')\ndraw_2dvec(b[0], b[1], name='b')\ndraw_2dvec(a[0], a[1], b[0], b[1], color=(0.75, 0.75, 0.75), name='a')\ndraw_2dvec(b[0], b[1], a[0], a[1], color=(0.5, 0.5, 0.5), name='b')\ndraw_2dvec(a_minus_b[0], a_minus_b[1], b[0], b[1], name='$\\\\vec{a}-\\\\vec{b}$')\n\npy.axis('equal')\npy.xlim((-8, 8))\npy.ylim((-8, 8))\npy.grid(True)\n\n\n```\n\n이는 다음을 뜻한다.
\nThis means the following.\n\n\n\n$$\n\\vec{b}+\\left(\\vec{a}-\\vec{b}\\right)=\\vec{a}\n$$\n\n\n\n또한, $\\vec{a}-\\vec{b}$ 도 $\\vec{a}$와 $\\vec{b}$가 이루는 평행 사변형의 다른 대각선임을 알 수 있다.
\nWe can also see that the vector subtraction is the other diagonal of the parallogram of $\\vec{a}$'s and $\\vec{b}$'s.\n\n\n\n## 연습 문제
Exercise\n\n\n\n* 임의의 두 2차원 벡터를 파이썬 튜플 tuple 로 정의하시오
Define two 2-dimensional vectors as python tuples.\n\n\n\n\n```python\n\n```\n\n* 위에서 보인 예와 같이 두 벡터를 그려 보시오
Plot these two vectors as above\n\n\n\n\n```python\n\n```\n\n* 두 벡터의 합과 두 벡터를 함께 그려 보시오
Plot the sum of two vectors with the two vectors\n\n\n\n\n```python\n\n```\n\n* 두 벡터와 두 벡터의 합, 두 벡터의 차를 함께 그려 보시오
Plot the two vectors, the sum vector and the difference vector\n\n\n\n\n```python\n\n```\n\n## 튜플 `tuple` 과 리스트 `list`
`tuple` and `list`\n\n\n\n리스트 `list` 와 튜플 `tuple` 모두 여러 항목을 저장할 수 있다.
Both `list` and `tuple` can store multiple items.\n\n\n\n또한 각 항목을 순서로 구분한다.
Also, distinguish each item with the order.\n\n\n\n리스트는 항목을 변경 추가 삭제할 수 있으나 (mutable) 튜플은 한번 만들어지면 변경할 수 없다 (immutable).
\nWe may change, add, or remove items in lists (mutable) but we cannot with tuples (immutable).\n\n예를 들어 다음 함수를 생각해 보자.
Let's check following function.\n\n\n\n\n```python\ndef multipy_scalar(a, x_vector):\n y_vector = x_vector\n\n for k in range(len(x_vector)):\n y_vector[k] = a * x_vector[k]\n\n return y_vector\n\n\n```\n\n\n```python\nx_list = [1, 2, 3]\na_sample = 0.1\ny_sample = multipy_scalar(a_sample, x_list)\n\n\n```\n\n\n```python\ny_sample\n\n\n```\n\n\n```python\nx_list\n\n\n```\n\n튜플 tuple 의 경우, 항목을 바꿀 수 없으므로 아래 예에서 예외 Exception 가 발생한다.
\nBecause a tuple does not allow chaning one of its items, following example would raise an Exception.\n\n\n\n\n```python\ntry:\n x_tuple = (4, 5, 6)\n b_sample = 0.01\n y_sample = multipy_scalar(b_sample, x_tuple)\nexcept TypeError as e:\n print(e)\n print('cannot change an item in tuple')\n\n \n```\n\n## `zip`()\n\n\n\n기본 내장 함수인 `zip()` 은 여러 모음에서 한 항목씩 꺼내어 만든 튜플 `tuple` 을 *생성*한다.
\nBuilt-in function `zip()` generates `tuple`s of items from multiple collections.\n\n\n\n\n```python\na_str = 'abc'\nb_list = [0, 1, 2]\nc_dict = {'x':'xylophone', 'y':'yield'}\n\nfor a_b_c in zip(a_str, b_list, c_dict):\n print(a_b_c)\n\n \n```\n\n한 모음이라도 항목이 다 떨어지면 중단한다.
\nThe iteration stops when the smallest collection exhausts.\n\n\n\n### 리스트 컴프리헨션
List comprehension\n\n\n\n다음 결과를 비교하시오.
\nCompare the results of following cells.\n\n\n\n```python\ns_for = []\n\nfor i in range(10):\n s_for.append(2 * i + 1)\n\nprint(s_for)\n\n\n```\n\n\n```python\ns_list_comprehension = [2 * j + 1 for j in range(10)]\n\nprint(s_list_comprehension)\n\n\n```\n\n\n```python\ns_map = list(map(lambda k: 2 * k + 1, range(10)))\n\nprint(s_map)\n\n\n```\n\n`set()` 이나 `dict()`에 대해서도 적용 가능하다.
\nIt is applicable to `set()` or `dict()`.\n\n\n\n\n```python\ninput_str = 'set comprehension'\n\n\n```\n\n\n```python\nset_for = set()\n\nfor c in input_str:\n set_for.add(c*2)\n\nprint(set_for)\n\n\n```\n\n\n```python\nset_comprehension = {2 * j for j in input_str}\n\nprint(set_comprehension)\nprint(set_for == set_comprehension)\n\n\n```\n\n\n```python\ninput_str = 'dictionary comprehension'\n\n\n```\n\n\n```python\ndict_for = {}\n\nfor c in input_str:\n # ASCII code for c = ord(c)\n dict_for[c] = ord(c)\n\nprint(dict_for)\n\n\n```\n\n\n```python\ndict_comprehension = {c:ord(c) for c in input_str}\n\nprint(dict_comprehension)\n\n\n```\n\n## `quiver()`\n\n\n\n이 함수는 다수의 화살표를 동시에 생성한다.
\nThis function would generate a group of arrows at the same time.\n\n\n\n아래 셀의 결과를 비교하시오.
Compare the result of the following cells.\n\n\n\n\n```python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n```\n\n\n```python\nx_deg = np.linspace(0, 360)\ny = np.zeros_like(x_deg)\nu = np.zeros_like(x_deg)\nv = np.cos(np.deg2rad(x_deg))\n\nplt.quiver(x_deg, y, u, v)\nplt.show()\n\n\n```\n\n\n```python\nx_deg = np.linspace(0, 360)\ny = np.zeros_like(x_deg)\nu = np.zeros_like(x_deg)\nv = np.cos(np.deg2rad(x_deg))\n\nplt.plot(x_deg, v)\nplt.quiver(x_deg, y, u, v)\n\nplt.show()\n\n\n```\n\n## 두 벡터의 합을 구하는 다른 방법
Other ways to add two vectors\n\n\n\n리스트 항목 순서
Indices of lists\n\n\n\n\n```python\ndef add_two_vectors_index(a, b):\n\n result = [0.0] * len(a)\n\n for index in range(len(a)):\n print(f\"index : a[{index}]={a[index]}, b[{index}]={b[index]}\")\n result[index] = a[index] + b[index]\n \n return result\n\n\n```\n\n`zip()`\n\n\n\n\n```python\ndef add_two_vectors_zip(a, b):\n\n result = []\n\n for ai, bi in zip(a, b):\n print(f\"zip : ai={ai}, bi={bi}\")\n result.append(ai + bi)\n \n return result\n\n\n```\n\n`map()`\n\n\n\n\n```python\ndef add_two_vectors_map(a, b):\n return list(\n map(\n lambda ai_bi: sum(ai_bi),\n zip(a, b)\n )\n )\n\n\n```\n\n리스트 줄여쓰기
List comprehension\n\n\n\n\n```python\ndef add_two_vectors_list_comprehension(a, b):\n return [(ai + bi) for ai, bi in zip(a, b)]\n\n\n```\n\n결과는 모두 같다.
All three methods give same results.\n\n\n\n\n```python\nx = [1, 2, 3]\ny = [0.1, 0.2, 0.3]\n\nprint('result =', add_two_vectors(x, y))\nprint('result (index) =', add_two_vectors_index(x, y))\nprint('result (zip) =', add_two_vectors_zip(x, y))\nprint('result (map) =', add_two_vectors_map(x, y))\nprint('result (list comprehension) =', add_two_vectors_list_comprehension(x, y))\n\n\n```\n\n## `assert`\n\n\n\n`assert` 명령은 프로그램이 예상했던 대로 작동하는지 확인할 수 있는 방법이다.
\n`assert` is one of ways to check if program is working as expected.\n\n\n\n```\nassert , \n```\n\n위 셀에서 `` 위치의 논리식이 거짓이면 `AssertionError` 예외를 발생시킨다.
\nIn the cell above, when the logical expression of `` is False, it would raise an exception of `AssertionError`.\n\n\n\n### 벡터 합
Vector addition\n\n\n\n벡터 덧셈의 경우, 두 벡터의 크기가 같은지 확인할 필요가 있다.
\nIn case of vector addition, it is necessary to check if the lengths of two vectors are the same.\n\n\n\n\n```python\ndef add_two_vectors(a, b):\n\n assert len(a) == len(b), f\"len(a) = {len(a)}, len(b) = {len(b)}\"\n \n result = []\n\n for ai, bi in zip(a, b):\n result.append(ai + bi)\n \n return result\n\n\n```\n\n두 벡터의 길이가 다르면 `AssertionError` 를 발생 시킬 것이다.
\nIf lengths of two vectors are different, it would raise an `AssertionError`.\n\n\n\n## 시험
Tests\n\n\n\n\n```python\nimport random\n\ntest_alpha_scalar = random.random()*2 - 1\n\ntest_x_vector = [random.random()*2 - 1, random.random()*2 - 1]\n\nexpected = [(test_x_vector[0] * test_alpha_scalar), (test_x_vector[1] * test_alpha_scalar)]\n\nresult = scalar_mul(test_alpha_scalar, test_x_vector)\n\nassert expected == result, (\n f\"\\nscalar = {test_alpha_scalar}\\n\"\n f\"input vector = {test_x_vector}\\n\"\n f\"expected = {expected}\\n\"\n f\"result = {result}\\n\"\n)\n\n\n```\n\n## Final Bell
마지막 종\n\n\n\n\n```python\n# stackoverfow.com/a/24634221\nimport os\nos.system(\"printf '\\a'\");\n\n\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "c8af31084a2cff3b2c4e77f02b6b2ec979e1bcb4", "size": 32508, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "40_linear_algebra_1/10_vector_addition_subtraction.ipynb", "max_stars_repo_name": "kangwonlee/2009eca-nmisp-template", "max_stars_repo_head_hexsha": "46a09c988c5e0c4efd493afa965d4a17d32985e8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "40_linear_algebra_1/10_vector_addition_subtraction.ipynb", "max_issues_repo_name": "kangwonlee/2009eca-nmisp-template", "max_issues_repo_head_hexsha": "46a09c988c5e0c4efd493afa965d4a17d32985e8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "40_linear_algebra_1/10_vector_addition_subtraction.ipynb", "max_forks_repo_name": "kangwonlee/2009eca-nmisp-template", "max_forks_repo_head_hexsha": "46a09c988c5e0c4efd493afa965d4a17d32985e8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8321020819, "max_line_length": 241, "alphanum_fraction": 0.4849267873, "converted": true, "num_tokens": 6097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.30507449306892}} {"text": "\n\n# Tutorial 2: Facial recognition using modern convnets\n**Week 2, Day 2: Modern Convnets**\n\n**By Neuromatch Academy**\n\n__Content creators:__ Laura Pede, Richard Vogg, Marissa Weis, Timo Lüddecke, Alexander Ecker (based on an initial version by Ben Heil)\n\n__Content reviewers:__ Arush Tagade, Polina Turishcheva, Yu-Fang Yang, Bettina Hein, Melvin Selim Atay\n\n__Content editors:__ Roberto Guidotti, Spiros Chavlis\n\n__Production editors:__ Anoop Kulkarni, Roberto Guidotti, Cary Murray, Spiros Chavlis\n\n**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**\n\n

\n\n---\n# Tutorial Objectives\n\nIn this tutorial you will learn about:\n\n1. An application of modern CNNs in facial recognition.\n2. Ethical aspects of facial recognition.\n\n\n```python\n# @title Tutorial slides\n\n# @markdown These are the slides for the videos in this tutorial\nfrom IPython.display import IFrame\nIFrame(src=f\"https://mfr.ca-1.osf.io/render?url=https://osf.io/4r2dp/?direct%26mode=render%26action=download%26mode=render\", width=854, height=480)\n```\n\n---\n# Setup\n\n\n```python\n# @title Install dependencies\n# @markdown Install facenet - a model used to do facial recognition\n!pip install facenet-pytorch --quiet\n!pip install pillow --quiet\n```\n\n\n```python\n# Imports\nimport glob\nimport torch\n\nimport numpy as np\nimport sklearn.decomposition\nimport matplotlib.pyplot as plt\n\nfrom PIL import Image\n\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\nfrom torchvision.datasets import ImageFolder\n\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\n```\n\n\n```python\n# @title Set random seed\n\n# @markdown Executing `set_seed(seed=seed)` you are setting the seed\n\n# for DL its critical to set the random seed so that students can have a\n# baseline to compare their results to expected results.\n# Read more here: https://pytorch.org/docs/stable/notes/randomness.html\n\n# Call `set_seed` function in the exercises to ensure reproducibility.\nimport random\nimport torch\n\ndef set_seed(seed=None, seed_torch=True):\n if seed is None:\n seed = np.random.choice(2 ** 32)\n random.seed(seed)\n np.random.seed(seed)\n if seed_torch:\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(f'Random seed {seed} has been set.')\n\n\n# In case that `DataLoader` is used\ndef seed_worker(worker_id):\n worker_seed = torch.initial_seed() % 2**32\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n```\n\n\n```python\n# @title Set device (GPU or CPU). Execute `set_device()`\n# especially if torch modules used.\n\n# inform the user if the notebook uses GPU or CPU.\n\ndef set_device():\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n if device != \"cuda\":\n print(\"WARNING: For this notebook to perform best, \"\n \"if possible, in the menu under `Runtime` -> \"\n \"`Change runtime type.` select `GPU` \")\n else:\n print(\"GPU is enabled in this notebook.\")\n\n return device\n```\n\n\n```python\nSEED = 2021\nset_seed(seed=SEED)\nDEVICE = set_device()\n```\n\n---\n# Section 1: Face Recognition\n\n## Section 1.1: Download and prepare the data\n\n\n```python\n# @title Download Data\n\n!rm -rf cis_522_data/\n!git clone --quiet https://github.com/ben-heil/cis_522_data.git\n!tar -xzf cis_522_data/archive.tar.gz\n!tar -xzf cis_522_data/faces.tar.gz\n```\n\n\n```python\n# @title Video 1: Face Recognition using CNNs\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV17B4y1K7WV\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"jJqEv8hpRa4\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\nOne application of large CNNs is **facial recognition**. The problem formulation in facial recognition is a little different from the image classification we've seen so far. In facial recognition, we don't want to have a fixed number of individuals that the model can learn. If that were the case then to learn a new person it would be necessary to modify the output portion of the architecture and retrain to account for the new person.\n\nInstead, we train a model to learn an **embedding** where images from the same individual are close to each other in an embedded space, and images corresponding to different people are far apart. When the model is trained, it takes as input an image and outputs an embedding vector corresponding to the image. \n\nTo achieve this, facial recognitions typically use a **triplet loss** that compares two images from the same individual (i.e., \"anchor\" and \"positive\" images) and a negative image from a different individual (i.e., \"negative\" image). The loss requires the distance between the anchor and negative points to be greater than a margin $\\alpha$ + the distance between the anchor and positive points.\n\n## Section 1.2: View and transform the data\n\nA well-trained facial recognition system should be able to map different images of the same individual relatively close together. We will load 15 images of three individuals (maybe you know them - then you can see that your brain is quite well in facial recognition).\n\nAfter viewing the images, we will transform them: MTCNN ([github repo](https://github.com/ipazc/mtcnn)) detects the face and crops the image around the face. Then we stack all the images together in a tensor.\n\n\n```python\n# @title Display Images\n# @markdown Here are the source images of Bruce Lee, Neil Patrick Harris, and Pam Grier\ntrain_transform = transforms.Compose((transforms.Resize((256, 256)),\n transforms.ToTensor()))\n\nface_dataset = ImageFolder('faces', transform=train_transform)\n\nimage_count = len(face_dataset)\n\nface_loader = torch.utils.data.DataLoader(face_dataset,\n batch_size=45,\n shuffle=False)\n\ndataiter = iter(face_loader)\nimages, labels = dataiter.next()\n\n# show images\nplt.figure(figsize=(15, 15))\nplt.imshow(make_grid(images, nrow=15).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n\n```python\n# @title Image Preprocessing Function\ndef process_images(image_dir: str, size=256):\n \"\"\"\n This function returns two tensors for the given image dir: one usable for inputting into the\n facenet model, and one that is [0,1] scaled for visualizing\n\n Parameters:\n image_dir: The glob corresponding to images in a directory\n\n Returns:\n model_tensor: A image_count x channels x height x width tensor scaled to between -1 and 1,\n with the faces detected and cropped to the center using mtcnn\n display_tensor: A transformed version of the model tensor scaled to between 0 and 1\n \"\"\"\n mtcnn = MTCNN(image_size=size, margin=32)\n images = []\n for img_path in glob.glob(image_dir):\n img = Image.open(img_path)\n # Normalize and crop image\n img_cropped = mtcnn(img)\n images.append(img_cropped)\n\n model_tensor = torch.stack(images)\n display_tensor = model_tensor / (model_tensor.max() * 2)\n display_tensor += .5\n\n return model_tensor, display_tensor\n```\n\nNow that we have our images loaded, we need to preprocess them. To make the images easier for the network to learn, we crop them to include just faces.\n\n\n```python\nbruce_tensor, bruce_display = process_images('faces/bruce/*.jpg')\nneil_tensor, neil_display = process_images('faces/neil/*.jpg')\npam_tensor, pam_display = process_images('faces/pam/*.jpg')\n\ntensor_to_display = torch.cat((bruce_display, neil_display, pam_display))\n\nplt.figure(figsize=(15, 15))\nplt.imshow(make_grid(tensor_to_display, nrow=15).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n## Section 1.3: Embedding with a pretrained network \n\nWe load a pretrained facial recognition model called [FaceNet](https://github.com/timesler/facenet-pytorch). It was trained on the [VGGFace2](https://github.com/ox-vgg/vgg_face2) dataset which contains 3.31 million images of 9131 individuals.\n\nWe use the pretrained model to calculate embeddings for all of our input images.\n\n\n```python\nresnet = InceptionResnetV1(pretrained='vggface2').eval().to(DEVICE)\n```\n\n\n```python\n# Calculate embedding\nresnet.classify = False\nbruce_embeddings = resnet(bruce_tensor.to(DEVICE))\nneil_embeddings = resnet(neil_tensor.to(DEVICE))\npam_embeddings = resnet(pam_tensor.to(DEVICE))\n```\n\n### Think! 1.3: Embedding vectors\n\nWe want to understand what happens when the model receives an image and returns the corresponding embedding vector.\n\n- What are the height, width and number of channels of one input image?\n- What are the dimensions of one stack of images (e.g. bruce_tensor)?\n- What are the dimensions of the corresponding embedding (e.g. bruce_embeddings)?\n- What would be the dimensions of the embedding of one input image?\n\n\n**Hints:**\n- You can double click on a variable name and hover over it to see the dimensions of tensors.\n- You do not have to answer the questions in the order they are asked.\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D2_ModernConvnets/solutions/W2D2_Tutorial2_Solution_bbe072ff.py)\n\n\n\nWe cannot show 512-dimensional vectors visually, but using **Principal Component Analysis (PCA)** we can project the 512 dimensions onto a 2-dimensional space while preserving the maximum amount of data variation possible. This is just a visual aid for us to understand the concept. Note that if you would like to do any calculation, like distances between two images, this would be done with the whole 512-dimensional embedding vectors.\n\n\n```python\nembedding_tensor = torch.cat((bruce_embeddings,\n neil_embeddings,\n pam_embeddings)).to(device='cpu')\n\npca = sklearn.decomposition.PCA(n_components=2)\npca_tensor = pca.fit_transform(embedding_tensor.detach().cpu().numpy())\n```\n\n\n```python\nnum = 15\ncategs = 3\ncolors = ['blue', 'orange', 'magenta']\nlabels = ['Bruce Lee', 'Neil Patrick Harris', 'Pam Grier']\nmarkers = ['o', 'x', 's']\nplt.figure(figsize=(8, 8))\nfor i in range(categs):\n plt.scatter(pca_tensor[i*num:(i+1)*num, 0],\n pca_tensor[i*num:(i+1)*num, 1],\n c=colors[i],\n marker=markers[i], label=labels[i])\nplt.legend()\nplt.title('PCA Representation of the Image Embeddings')\nplt.xlabel('PC 1')\nplt.ylabel('PC 2')\nplt.show()\n```\n\nGreat! The images corresponding to each individual are separated from each other in the embedding space!\n\nIf Neil Patrick Harris wants to unlock his phone with facial recognition, the phone takes the image from the camera, calculates the embedding and checks if it is close to the registered embeddings corresponding to Neil Patrick Harris.\n\n---\n# Section 2: Ethics – bias/discrimination due to pre-training datasets\nPopular facial recognition datasets like VGGFace2 and CASIA-WebFace consist primarily of caucasian faces. \nAs a result, even state of the art facial recognition models [substantially underperform](https://openaccess.thecvf.com/content_ICCV_2019/papers/Wang_Racial_Faces_in_the_Wild_Reducing_Racial_Bias_by_Information_ICCV_2019_paper.pdf) when attempting to recognize faces of other races.\n\nGiven the implications that poor model performance can have in fields like security and criminal justice, it's very important to be aware of these limitations if you're going to be building facial recognition systems.\n\nIn this example we will work with a small subset from the [UTKFace](https://susanqq.github.io/UTKFace/) dataset with 49 pictures of black women and 49 picture of white women. We will use the same pretrained model as in Section 8 of Tutorial 1, see and discuss the consequences of the model being trained on an imbalanced dataset.\n\n\n```python\n# @title Video 2: Ethical aspects\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1Jo4y1Q7K3\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"vYilJV3PqUM\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n## Section 2.1: Download the Data\n\n\n```python\n# @title Run this cell to get the data and free ram by deleting old variables\n\n!rm -rf cis_522_data/\n\nif 'embedding_tesnor' in locals():\n del embedding_tensor\nif 'pca_tesnor' in locals():\n del pca_tensor\nif 'tensor_to_display' in locals():\n del tensor_to_display\nif 'bruce_embeddings' in locals():\n del bruce_embeddings\nif 'neil_embeddings' in locals():\n del neil_embeddings\nif 'pam_embeddings' in locals():\n del pam_embeddings\n\n\n# remove directories, if previously run.\n!rm -rf __MACOSX/\n!rm -rf face_sample/\n!rm -rf face_sample2/\n!git clone --quiet https://github.com/richardvogg/face_sample.git\n!unzip -q face_sample/face_sample2.zip\n```\n\n## Section 2.2: Load, view and transform the data\n\n\n```python\nblack_female_tensor, black_female_display = process_images('face_sample2/??_1_1_*.jpg', size=150)\nwhite_female_tensor, white_female_display = process_images('face_sample2/??_1_0_*.jpg', size=150)\n```\n\nWe can check the dimensions of these tensors and see that for each group we have images of size 150x150 and three channels (RGB) of 49 individuals.\n\n**Note:** Originally, the size of images was 200x200, but due to RAM resources, we have reduce it. You can change it back, i.e., `size=200`.\n\n\n```python\nprint(white_female_tensor.shape)\nprint(black_female_tensor.shape)\n```\n\n\n```python\n# @title Visualize some example faces\ntensor_to_display = torch.cat((white_female_display[:15],\n black_female_display[:15]))\n\nplt.figure(figsize=(12, 12))\nplt.imshow(make_grid(tensor_to_display, nrow = 15).permute(1, 2, 0))\nplt.axis('off')\nplt.show()\n```\n\n## Section 2.3: Calculate embeddings\n\nWe use the same pretrained facial recognition network as in section 8 to calculate embeddings. If you have memory issues running this part, go to Edit > Notebook settings and check if GPU is selected as Hardware accelerator. If this does not help you can restart the notebook, go to Runtime -> Restart runtime.\n\n\n```python\nresnet.classify = False\nblack_female_embeddings = resnet(black_female_tensor.to(DEVICE))\nwhite_female_embeddings = resnet(white_female_tensor.to(DEVICE))\n```\n\nWe will use the embeddings to show that the model was trained on an imbalanced dataset. For this, we are going to calculate a distance matrix of all combinations of images, like in this small example with $n=3$ (in our case $n=98$).\n\n\n\nCalculate the distance between each pair of image embeddings in our tensor and visualize all the distances. Remember that two embeddings are vectors and the distance between two vectors is the Euclidean distance.\n\n\n```python\n# @title Function to calculate pairwise distances\n# @markdown `torch.cdist` is used\ndef calculate_pairwise_distances(embedding_tensor):\n \"\"\"\n This function calculates the distance between each pair of image embeddings\n in a tensor using the `torch.cdist`.\n\n Parameters:\n embedding_tensor : torch.Tensor\n A num_images x embedding_dimension tensor\n\n Returns:\n distances : torch.Tensor\n A num_images x num_images tensor containing the pairwise distances between\n each to image embedding\n \"\"\"\n\n distances = torch.cdist(embedding_tensor, embedding_tensor)\n\n return distances\n```\n\n\n```python\n# @title Visualize the distances\n\nembedding_tensor = torch.cat((black_female_embeddings,\n white_female_embeddings)).to(device='cpu')\n\ndistances = calculate_pairwise_distances(embedding_tensor)\n\nplt.figure(figsize=(8, 8))\nplt.imshow(distances.detach().cpu().numpy())\nplt.annotate('Black female', (2, -0.5), fontsize=20, va='bottom')\nplt.annotate('White female', (52, -0.5), fontsize=20, va='bottom')\nplt.annotate('Black female', (-0.5, 45), fontsize=20, rotation=90, ha='right')\nplt.annotate('White female', (-0.5, 90), fontsize=20, rotation=90, ha='right')\ncbar = plt.colorbar()\ncbar.set_label('Distance', fontsize=16)\nplt.axis('off')\nplt.show()\n```\n\n## Exercise 2.1\n\nWhat do you observe? The faces of which group are more similar to each other for the Face Detection algorithm?\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D2_ModernConvnets/solutions/W2D2_Tutorial2_Solution_866d0881.py)\n\n\n\n## Exercise 2.2\n- What does it mean in real life applications that the distance is smaller between the embeddings of one group?\n- Can you come up with example situations/applications where this has a negative impact?\n- What could you do to avoid these problems?\n\n[*Click for solution*](https://github.com/NeuromatchAcademy/course-content-dl/tree/main//tutorials/W2D2_ModernConvnets/solutions/W2D2_Tutorial2_Solution_b92b2f40.py)\n\n\n\nLastly, to show the importance of the dataset which you use to pretrain your model, look at how much space white men and women take in different embeddings. FairFace is a dataset which is specifically created with completely balanced classes. The blue dots in all visualizations are white male and white female.\n\n\n\nAdopted from [Kärkkäinen and Joo, 2019, arXiv](https://arxiv.org/abs/1908.04913)\n\n---\n# Summary\n\nIn this tutorial we have learned how to apply a modern convnet in real application such as facial recognition. However, as the state-of-the-art tools for facial recognition are trained mostly with caucasian faces, they fail or they perform much worst when they have to deal with faces from other races.\n\n\n```python\n# @title Video 3: Summary and Outlook\nfrom ipywidgets import widgets\n\nout2 = widgets.Output()\nwith out2:\n from IPython.display import IFrame\n class BiliVideo(IFrame):\n def __init__(self, id, page=1, width=400, height=300, **kwargs):\n self.id=id\n src = \"https://player.bilibili.com/player.html?bvid={0}&page={1}\".format(id, page)\n super(BiliVideo, self).__init__(src, width, height, **kwargs)\n\n video = BiliVideo(id=f\"BV1So4y1D7Ev\", width=854, height=480, fs=1)\n print(\"Video available at https://www.bilibili.com/video/{0}\".format(video.id))\n display(video)\n\nout1 = widgets.Output()\nwith out1:\n from IPython.display import YouTubeVideo\n video = YouTubeVideo(id=f\"sjj0-7i6XfE\", width=854, height=480, fs=1, rel=0)\n print(\"Video available at https://youtube.com/watch?v=\" + video.id)\n display(video)\n\nout = widgets.Tab([out1, out2])\nout.set_title(0, 'Youtube')\nout.set_title(1, 'Bilibili')\n\ndisplay(out)\n```\n\n---\n# Bonus : Within Sum of Squares\n\nWe can try to put this observation in numbers. For this we work with the embeddings.\nWe want to calculate the centroid of each group, which is the average of the 49 embeddings of the group. As each embedding vector has a dimension of 512, the centroid will also have this dimension.\n\nNow we can calculate how far away the observations $x$ of each group $S_i$ are from the centroid $\\mu_i$. This concept is known as Within Sum of Squares (WSS) from cluster analysis.\n\n\\begin{equation}\n\\text{WSS} = \\sum_{x\\in S_i} ||x - \\mu_i||^2\n\\end{equation}\n\nwhere $|| \\cdot ||$ is the Euclidean norm.\n\nThe Within Sum of Squares (WSS) is a number which measures this variability of a group in the embedding space. If all embeddings of one group were very close to each other, the WSS would be very small. In our case we see that the WSS for the black females is much smaller than for the white females. This means that it is much harder for the model to distinguish two black females than to distinguish two white females. The WSS complements the observation from the distance matrix, where we observed overall smaller pairwise distances between black females.\n\n\n\n```python\n# @title Function to calculate WSS\n\ndef wss(group):\n \"\"\"\n This function returns the sum of squared distances of the N vectors of a\n group tensor (N x K) to its centroid (1 x K).\n\n Args:\n group: A image_count x embedding_size tensor\n\n Returns:\n sum_sq: A 1x1 tensor with the sum of squared distances.\n\n Hints:\n - to calculate the centroid, torch.mean() will be of use.\n - We need the mean of the N=49 observations. If our input tensor is of size\n N x K, we expect the centroid to be of dimensions 1 x K.\n Use the axis argument within torch.mean\n \"\"\"\n\n centroid = torch.mean(group, axis=0)\n distance = torch.linalg.norm(group - centroid.view(1, -1), axis=1)\n sum_sq = torch.sum(distance**2)\n return sum_sq\n```\n\n\n```python\n# @markdown Let's calculate the WSS for the two groups of our example.\n\nprint(f\"Black female embedding WSS: {np.round(wss(black_female_embeddings).item(), 2)}\")\nprint(f\"White female embedding WSS: {np.round(wss(white_female_embeddings).item(), 2)}\")\n```\n", "meta": {"hexsha": "ab7e7ad9162299fc4d58d17ca35c816245ee2396", "size": 33874, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "tutorials/W2D2_ModernConvnets/student/W2D2_Tutorial2.ipynb", "max_stars_repo_name": "amita-kapoor/course-content-dl", "max_stars_repo_head_hexsha": "bba5c8f6fa38a83c4e452be30791f3a6399d5b83", "max_stars_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-24T17:39:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T17:39:20.000Z", "max_issues_repo_path": "tutorials/W2D2_ModernConvnets/student/W2D2_Tutorial2.ipynb", "max_issues_repo_name": "amita-kapoor/course-content-dl", "max_issues_repo_head_hexsha": "bba5c8f6fa38a83c4e452be30791f3a6399d5b83", "max_issues_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2021-08-04T08:04:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T08:04:53.000Z", "max_forks_repo_path": "tutorials/W2D2_ModernConvnets/student/W2D2_Tutorial2.ipynb", "max_forks_repo_name": "amita-kapoor/course-content-dl", "max_forks_repo_head_hexsha": "bba5c8f6fa38a83c4e452be30791f3a6399d5b83", "max_forks_repo_licenses": ["CC-BY-4.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0155945419, "max_line_length": 565, "alphanum_fraction": 0.598305485, "converted": true, "num_tokens": 5522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.30492725832042367}} {"text": "# Molecular Dynamics: Lab 1\n\nIn part based on [Fortran code from Furio Ercolessi](http://www.fisica.uniud.it/~ercolessi/md/f90/).\n\n\n```python\nfrom IPython.core.display import HTML\ncss_file = 'https://raw.githubusercontent.com/ngcm/training-public/master/ipython_notebook_styles/ngcmstyle.css'\nHTML(url=css_file)\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Basics of Molecular Dynamics\n\n\n```python\n%matplotlib inline\nimport numpy\nfrom matplotlib import pyplot\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'serif'\nrcParams['font.size'] = 16\nrcParams['figure.figsize'] = (12,6)\n```\n\nThe basic idea of molecular dynamics is to follow the location of the particles in time using Newton's laws. Each particle has a location $\\vec{X}_i$ which obeys\n\n$$\n\\begin{equation}\n m_i \\frac{d^2}{d t^2} \\vec{X}_i = m_i \\vec{A}_i = -\\nabla V \\left( \\vec{X}_1, \\dots, \\vec{X}_N \\right).\n\\end{equation}\n$$\n\nMost of the time we will work in computational coordinates, rescaled by a reference length $L$, so that the particles obey\n\n$$\n\\begin{equation}\n \\frac{d^2}{d t^2} \\vec{x}_i = \\vec{a}_i = -\\nabla V \\left( \\vec{x}_1, \\dots, \\vec{x}_N \\right).\n\\end{equation}\n$$\n\nThis gives us a computational domain, once translated to the centre-of-mass, of $\\vec{x} \\in [-0.5, 0.5]^3$.\n\nThe simplest possibility is that the interaction potential $V$ is the sum of pairwise interactions, \n\n$$\n\\begin{equation}\n V \\left( \\vec{x}_1, \\dots, \\vec{x}_N \\right) = \\sum_i \\sum_{j>i} \\phi \\left( L \\left| \\vec{x}_i - \\vec{x}_j \\right| \\right).\n\\end{equation}\n$$\n\nThe most commonly used pairwise interaction potential is the *Lennard-Jones* potential\n\n$$\n\\begin{equation}\n \\phi(r) = 4 \\varepsilon \\left[ \\left( \\frac{\\sigma}{r} \\right)^{12} - \\left( \\frac{\\sigma}{r} \\right)^{6} \\right].\n\\end{equation}\n$$\n\nTo stop this potential extending for infinite distance a cutoff is used; $\\phi(r) \\to \\phi(r) - \\phi(R_c)$, where $R_c$ is a constant (here $2.5$ when $\\sigma = 1 = \\varepsilon = M_i$).\n\nAs, in this case,\n\n$$\n\\begin{equation}\n \\frac{d}{dr} \\phi(r) = 24 \\left[ 2 \\left( \\frac{1}{r} \\right)^{14} - \\left( \\frac{1}{r} \\right)^{8} \\right],\n\\end{equation}\n$$\n\nwe have\n\n$$\n\\begin{equation}\n \\vec{a}_i = -\\left. \\nabla V \\right|_{i} = \\sum_{j>i} (\\vec{x}_i - \\vec{x}_j) \\, \\frac{d}{dr} \\phi(r) - \\sum_{j i$, setting *both*\n\n1. $\\vec{a}_i = \\vec{a}_i + (\\vec{x}_i - \\vec{x}_j) \\, \\frac{d}{dr} \\phi(r)$,\n2. $\\vec{a}_j = \\vec{a}_j - (\\vec{x}_i - \\vec{x}_j) \\, \\frac{d}{dr} \\phi(r)$.\n\nImplement an algorithm to calculate the acceleration given the positions.\n\n\n```python\n\n```\n\n### Time evolution\n\nThe problem with time integrating is that most numerical algorithms do not conserve the total energy of the system, which can be be crucial. Certain algorithms, such as the [velocity Verlet](http://en.wikipedia.org/wiki/Verlet_integration#Velocity_Verlet) algorithm, do conserve total energy.\n\n#### Velocity Verlet\n\nGiven initial positions $\\vec{x}$ and velocities $\\vec{v}$ of each particle, the algorithm can be written as\n\n1. $x^{n+1} = \\vec{x}^n + \\Delta t \\, \\vec{v}^n + \\tfrac{1}{2} \\Delta t^2 \\, \\vec{a}^n$\n2. $\\vec{v}^{*} = \\vec{v}^n + \\tfrac{1}{2} \\Delta t \\, \\vec{a}^n$;\n3. Derive $\\vec{a}^{n+1}$ from the interaction potential using $\\vec{x}^{n+1}$;\n4. $\\vec{v}^{n+1} = \\vec{v}^{*} + \\tfrac{1}{2} \\Delta t \\vec{a}^{n+1}$.\n\nImplement this algorithm.\n\n\n```python\n\n```\n\n### Periodic boundaries\n\nIf we just evolved the particles, they could fly off to infinity. Instead it is typical to work inside a box with periodic boundaries, so that there is an \"infinite lattice\" of particles.\n\nImplement a function that resets the position of particles that leave the given domain; the velocities and particles should remain unchanged.\n\n\n```python\n\n```\n\n### What to compute\n\nThe fundamental quantity is the location of the particles. However, the thing to analyze will be average properties of the particles; their mean temperature, pressure and energies.\n\nImplement a function, given the particle locations $\\vec{x}$ to compute the temperature, where\n\n$$\n\\begin{align}\n% E_{\\text{potential},\\ i} &= \\sum_{j /ne i} \\phi \\left( L \\left| \\vec{x}_i - \\vec{x}_j \\right| \\right), \\\\\n E_{\\text{kinetic},\\ i} &= \\tfrac{1}{2} L^2 \\left| \\vec{v}_i \\right|^2, \\\\\n T & = \\frac{2}{3 N} \\sum_{i=1}^N E_{\\text{kinetic},\\ i}.\n\\end{align}\n$$\n\n\n```python\n\n```\n\n### Run in a box\n\nFix the domain to be $\\vec{x} \\in [0, 6.1984]^3$. Fix the timestep to be $0.005$ and take 100 timesteps, given the initial data prescribed in `input.dat` (see `input.dat` on Blackboard).\n\n\n```python\n\n```\n\nThen plot some basic quantities, such as\n\n1. The temperature as a function of time;\n2. The trajectory of two particles from the middle of the domain (eg particles 100 and 101) as a function of time (using `plot3D`);\n3. The trajectories of all the particles.\n\n\n```python\n\n```\n", "meta": {"hexsha": "3e32db9b8924af9b420b773508d5c572f2dd4d5f", "size": 14652, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "FEEG6016 Simulation and Modelling/03-Molecular-Dynamics-Lab-1.ipynb", "max_stars_repo_name": "ngcm/training-public", "max_stars_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-06-23T05:50:49.000Z", "max_stars_repo_stars_event_max_datetime": "2016-06-22T10:29:53.000Z", "max_issues_repo_path": "FEEG6016 Simulation and Modelling/03-Molecular-Dynamics-Lab-1.ipynb", "max_issues_repo_name": "Jhongesell/training-public", "max_issues_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-11-28T08:29:55.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-28T08:29:55.000Z", "max_forks_repo_path": "FEEG6016 Simulation and Modelling/03-Molecular-Dynamics-Lab-1.ipynb", "max_forks_repo_name": "Jhongesell/training-public", "max_forks_repo_head_hexsha": "e5a0d8830df4292315c8879c4b571eef722fdefb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24, "max_forks_repo_forks_event_min_datetime": "2015-04-18T21:44:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T17:35:58.000Z", "avg_line_length": 31.5096774194, "max_line_length": 298, "alphanum_fraction": 0.4988397488, "converted": true, "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.30432497759345306}} {"text": "```python\n# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)\n\n# Toggle cell visibility\n\nfrom IPython.display import HTML\ntag = HTML('''\nToggle cell visibility here.''')\ndisplay(tag)\n\n# Hide the code completely\n\n# from IPython.display import HTML\n# tag = HTML('''''')\n# display(tag)\n```\n\n\n\nToggle cell visibility here.\n\n\n\n```python\n%matplotlib notebook\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\nfrom ipywidgets import widgets\nfrom ipywidgets import interact\nimport numpy as np\nimport sympy as sym\n```\n\n## Controller PID - risposta nel tempo\n\nUn algoritmo di controllo proporzionale-integrale-derivativo (PID) è di gran lunga l'algoritmo di controllo più comune. La sua funzione di trasferimento è\n\n\\begin{equation}\n P(s)=K_p \\cdot \\left( 1 + \\frac{1}{T_i s} + T_d s \\right).\n\\end{equation}\n\nÈ costituito dalla somma dei canali proporzionale, integrale e derivativo. Non tutti devono essere presenti, vengono utilizzati anche algoritmi di controllo P, PI o PD. In questo esempio viene mostrata la risposta di un controller P, PI, PD o PID al gradino unitario, all'impulso unitario, alla rampa unitaria o ad un ingresso sinusoidale.\n\n---\n\n### Come usare questo notebook?\n1. Alterna tra *funzione gradino*, *funzione impulso*, *funzione rampa* e *funzione seno* per selezionare il segnale di ingresso.\n2. Clicca il pulsante *P*, *PI*, *PD* o *PID* per selezionare tra proporzionale, proporzionale-integrale, proporzionale-derivativo o proporzionale-integrale-derivativo.\n3. Sposta gli sliders per modificare i valori dei coefficienti proporzionale ($K_p$), integrale ($T_i$) e derivativo ($T_d$).\n4. Sposta lo slider $t_{max}$ per modificare il valore massimo del tempo sull'asse x.\n\n\n```python\na = 0.1\n\n# make figure\nfig = plt.figure(figsize=(9.8, 5),num='Controllore PID')\n# add axes\nax = fig.add_subplot(111)\nax.grid(which='both', axis='both', color='lightgray')\nax.set_title('Risposta')\n# plot step function and responses (initalisation)\ninput_plot, = ax.plot([],[],'C0', linewidth=1,label='input')\nresponse_plot, = ax.plot([],[], 'C1', linewidth=2,label='output')\nax.axhline(linewidth=.5, color='k')\nax.axvline(linewidth=.5, color='k')\nax.legend()\n\nax.set_xlabel('$t$ [s]')\nax.set_ylabel('input, output')\nplt.show()\n\nP, I, D, s = sym.symbols('P, I, D, s')\n\ninput_type = 'gradino' #input function\nTime_span = 10 # max time on x-axis plot\n\n#initialize global variables\nKP = 1.\nTI = 1.\nTD = 1.\nnum = []\nden = []\n\ndef update_plot():\n global num, den, input_type, Time_span\n num_temp = [float(i.subs(P,KP).subs(I,TI).subs(D,TD)) for i in num]\n den_temp = [float(i.subs(P,KP).subs(I,TI).subs(D,TD)) for i in den]\n \n system = signal.TransferFunction(num_temp, den_temp)\n \n #time, response = signal.step(system) #only for setting time borders (for nicer plot. could also calculate dominant frequency)\n #time = np.linspace(0,time[-1],1000)\n time = np.linspace(0, Time_span, 600)\n \n if input_type == 'gradino':\n u = np.ones_like(time)\n u = np.concatenate((np.array([0]),u))\n time, response = signal.step(system, T=time)\n time = np.concatenate((np.array([0]), time))\n response = np.concatenate((np.array([0]), response))\n elif input_type == 'impulso':\n u = np.zeros_like(time)\n u = np.concatenate((np.array([10]), u))\n time, response = signal.impulse(system, T=time)\n time = np.concatenate((np.array([0]), time))\n response = np.concatenate((np.array([0]), response))\n elif input_type == 'sinusoide':\n u = np.sin(time*2*np.pi)\n time, response, _ = signal.lsim(system, U=u, T=time)\n elif input_type == 'rampa':\n u = time\n time, response, _ = signal.lsim(system, U=u, T=time)\n else:\n raise Exception(\"Errore nel programma. Fai ripartire la simulazione.\")\n \n response_plot.set_data(time, response)\n input_plot.set_data(time, u)\n ax.set_ylim([min([np.min(u), min(response),-.1]),min(100,max([max(response)*1.05, 1, 1.05*np.max(u[1:])]))])\n ax.set_xlim([-0.1,max(time)])\n plt.show()\n \n\ndef transfer_func(controller_type):\n global num, den\n proportional = P\n integral = P/(I*s)\n differential = P*D*s/(a*D*s+1)\n if controller_type =='P':\n controller_func = proportional\n Kp_widget.disabled=False\n Ti_widget.disabled=True\n Td_widget.disabled=True\n elif controller_type =='PI':\n controller_func = proportional+integral\n Kp_widget.disabled=False\n Ti_widget.disabled=False\n Td_widget.disabled=True\n elif controller_type == 'PD':\n controller_func = proportional+differential\n Kp_widget.disabled=False\n Ti_widget.disabled=True\n Td_widget.disabled=False\n else:\n controller_func = proportional+integral+differential\n Kp_widget.disabled=False\n Ti_widget.disabled=False\n Td_widget.disabled=False\n system_func = controller_func\n \n num = [sym.fraction(system_func.factor())[0].expand().coeff(s, i) for i in reversed(range(1+sym.degree(sym.fraction(system_func.factor())[0], gen=s)))]\n den = [sym.fraction(system_func.factor())[1].expand().coeff(s, i) for i in reversed(range(1+sym.degree(sym.fraction(system_func.factor())[1], gen=s)))]\n update_plot()\n \ndef func(Kp, Ti, Td, time_span):\n global KP, TI, TD, Time_span\n KP = Kp\n TI = Ti\n TD = Td\n Time_span = time_span\n update_plot()\n \nstyle = {'description_width': 'initial'}\n\ndef buttons_controller_clicked(event):\n controller = buttons_controller.options[buttons_controller.index]\n transfer_func(controller)\nbuttons_controller = widgets.ToggleButtons(\n options=['P', 'PI', 'PD', 'PID'],\n description='Seleziona il tipo di controller:',\n disabled=False,\n style=style)\nbuttons_controller.observe(buttons_controller_clicked)\n\ndef buttons_input_clicked(event):\n global input_type\n input_type = buttons_input.options[buttons_input.index]\n update_plot()\nbuttons_input = widgets.ToggleButtons(\n options=['gradino','impulso', 'rampa', 'sinusoide'],\n description='Seleziona l\\'input:',\n disabled=False,\n style=style)\nbuttons_input.observe(buttons_input_clicked)\n\n\nKp_widget = widgets.IntSlider(value=20,min=1,max=100,step=1,description=r'\\(K_p \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.1d')\nTi_widget = widgets.FloatSlider(value=.1,min=0.001,max=3.,step=0.001,description=r'\\(T_{i} \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.3f')\nTd_widget = widgets.FloatSlider(value=.1,min=0.001,max=3.,step=0.001,description=r'\\(T_{d} \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.3f')\n\ntime_span_widget = widgets.FloatSlider(value=10.,min=.5,max=50.,step=0.1,description=r'\\(t_{max} \\)',\n disabled=False,continuous_update=True,orientation='horizontal',readout=True,readout_format='.1f')\n\ntransfer_func('P')\n\ndisplay(buttons_input)\ndisplay(buttons_controller)\n\ninteract(func, Kp=Kp_widget, Ti=Ti_widget, Td=Td_widget, time_span=time_span_widget);\n```\n\n\n \n\n\n\n\n\n\n\n ToggleButtons(description=\"Seleziona l'input:\", options=('gradino', 'impulso', 'rampa', 'sinusoide'), style=To…\n\n\n\n ToggleButtons(description='Seleziona il tipo di controller:', options=('P', 'PI', 'PD', 'PID'), style=ToggleBu…\n\n\n\n interactive(children=(IntSlider(value=20, description='\\\\(K_p \\\\)', min=1, readout_format='.1d'), FloatSlider(…\n\n", "meta": {"hexsha": "ae28c1374dedc3a366f8255cf84c5be82ea79d7f", "size": 362134, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "ICCT_it/examples/02/.ipynb_checkpoints/TD-15-PID-controller-Risposta-nel-tempo-checkpoint.ipynb", "max_stars_repo_name": "ICCTerasmus/ICCT", "max_stars_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-05-22T18:42:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T14:10:22.000Z", "max_issues_repo_path": "ICCT_it/examples/02/TD-15-PID-controller-Risposta-nel-tempo.ipynb", "max_issues_repo_name": "ICCTerasmus/ICCT", "max_issues_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICCT_it/examples/02/TD-15-PID-controller-Risposta-nel-tempo.ipynb", "max_forks_repo_name": "ICCTerasmus/ICCT", "max_forks_repo_head_hexsha": "fcd56ab6b5fddc00f72521cc87accfdbec6068f6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-05-24T11:40:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T16:36:18.000Z", "avg_line_length": 319.906360424, "max_line_length": 315027, "alphanum_fraction": 0.905253304, "converted": true, "num_tokens": 2087, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.30315014915245386}} {"text": "\n\n# PyTorch tutorial の内容について(2)\n\n- date: 2020-0722\n- author: 浅川伸一\n\n[https://github.com/pytorch/tutorials/tree/master/beginner_source/nlp](https://github.com/pytorch/tutorials/tree/master/beginner_source/nlp) を見ると\nPyTorch で 自然言語処理を行う場合のチュートリアルは以下とおりである\n\n# Deep Learning for NLP with Pytorch\n\n1. [pytorch_tutorial.py](https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/pytorch_tutorial.py): \n\t[PyTorch 入門 Introduction to PyTorch](https://pytorch.org/tutorials/beginner/nlp/pytorch_tutorial.html)\n\n2. [deep_learning_tutorial.py](https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/deep_learning_tutorial.py): \n\t[PyTorch による深層学習 Deep Learning with PyTorch](https://pytorch.org/tutorials/beginner/nlp/deep_learning_tutorial.html)\n\n3. [word_embeddings_tutorial.py](https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/word_embeddings_tutorial.py): \n\t[単語埋め込み:語彙的意味の符号化 Word Embeddings: Encoding Lexical Semantics](https://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html)\n\n4. [sequence_models_tutorial.py]((https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/sequence_models_tutorial.py): \n\t[系列モデルと LSTM Sequence Models and Long-Short Term Memory Networks](https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html)\n\n5. [advanced_tutorial.py]((https://github.com/pytorch/tutorials/blob/master/beginner_source/nlp/advanced_tutorial.py): \n\t[動的意思決定と双方向 LSTM 条件付き確率場 Advanced: Making Dynamic Decisions and the Bi-LSTM CRF](https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html)\n\n\n以下では,このうちの 2 について解説している。\n\n\n\n```python\n%matplotlib inline\n```\n\n\nPyTorch によるディープラーニング\n********************************\n\n## ディープラーニングのブルディンクブロック: アフィン変換,非線形性,目的関数\n\nディープラーニングは、線形性と非線形性を巧妙な方法で組み合わせることで構成されています。\n非線形性を導入することで、強力なモデルを作ることができます。\nこのセクションでは、これらのコアコンポーネントで遊び、目的関数を構成し、モデルがどのように訓練されるかを見ていきます。\n\n\n\n### アフィン写像 \n\nディープラーニングの中核を成すものの一つがアフィン写像であり、次式の関数 $f(x)$ で表します。\n\n\n\n\\begin{align}\nf(x) = Ax + b\n\\end{align}\n\n行列 $A$ とベクトル $x, b$ を求めます。ここで学習するパラメータは $A$ と $b$ です。\n$b$ はバイアスとして使用されます。\n\nPyTorch や他のほとんどのディープラーニングフレームワークでは 従来の線形代数とは少し違うことをしています。\nそれは、入力の列の代わりに 行を写像します。\nつまり 以下の出力の $i$'番目の行は $A$ の下の入力の $i$'th 行にバイアス項を加えたものです。\n下の例を見てください。\n\n\n\n\n\n\n\n```python\n# Author: Robert Guthrie\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntorch.manual_seed(1)\n```\n\n\n\n\n \n\n\n\n\n```python\nlin = nn.Linear(5, 3) # 5 次のベクトルから 3 次のベクトルへの線形写像 ``nn.Linear`` # maps from R^5 to R^3, parameters A, b\n# データは 2 行 5 列 すなわち 5 次元のベクトルからなるデータが 2 つ # data is 2x5. A maps from 5 to 3... can we map \"data\" under A?\ndata = torch.randn(2, 5)\nprint(lin(data)) # 実際には 行列積 \n```\n\n tensor([[ 0.1755, -0.3268, -0.5069],\n [-0.6602, 0.2260, 0.1089]], grad_fn=)\n\n\n### 非線形性 \n\n次の事実に注意してください。2 つのアフィン写像 $f(x) = Ax + b$ と $g(x) = Cx + d$ があるとします。\n$f(g(x))$ は何でしょうか?\n\n\n\n\\begin{align}f(g(x)) = A(Cx + d) + b = ACx + (Ad + b)\\end{align}\n\n$A$ と $C$ は行列であり,$Ad + b$ はベクトルです。\nアフィン写像の合成はアフィン写像であることがわかります。\n\n\n\n\n\nこのことから,ニューラルネットワークをアフィン写像の幾重にも重ねた,ディープニューラルネットワークモデル\nを作成する場合,\n単一のアフィン写像による成績以上の性能は得られないことを意味します。\n\n\n\n逆に,アフィン写像の間に非線形性を導入するとにより,より強力なモデルを構築することができます。\n\n\nいくつかのコアとなる非線形性があります。\n\b$\\tanh(x)$, $\\sigma(x)$ (シグモイド関数), $\\text{ReLU}(x)$ が一般的です。\n他にも数多非線形変換がありうるのに,なぜこれらが用いられるのか疑問に思うかも知れません。\n理由は勾配計算が容易だからです。勾配の計算はニューラルネットワークの学習には必須です。\n\n\n\n\n例えば\n\n\\begin{align}\\frac{d\\sigma}{dx} = \\sigma(x)(1 - \\sigma(x))\\end{align}\n\n\n\n昔からニューラルネットワークをご存知の方は,シグモイド関数 $\\sigma(x)$ がデフォルトであると思われていることでしょう。ですが,最近ではシグモイド関数は用いられません。理由は勾配消失問題に対処するのが難しいからです。\nこのため,現在では $\\tanh(x)$ や ReLU (整流線型ユニット) が用いられます。\n\n\n\n```python\n# pytorch では ほとんどの非線形活性化関数は torch.functional で定義されています (F としてインポートしています)\n# 非線形型は一般的にアフィン写像のような パラメータを持たちません。\n# すなわち 学習中に更新されるパラメータを持ちません。\ndata = torch.randn(2, 2)\nprint(data)\nprint(F.relu(data))\n```\n\n tensor([[-0.5404, -2.2102],\n [ 2.1130, -0.0040]])\n tensor([[0.0000, 0.0000],\n [2.1130, 0.0000]])\n\n\n### ソフトマックスと確率\n\n\n\n関数 $\\text{Softmax}(x)$ も単なる非線形活性化関数の一つです。\nですが,通常ネットワーク内で最終層で行われる操作であるという点で特殊です。\nソフトマックス関数 は実数のベクトルを引数として取り,\n各ニューロン (ユニット) の確率分布を返すからです。\nソフトマックス関数の定義は次のようになります。\n$x$ を実ベクトルとする (正でも負でも何でもよく,制約はない)。\n$text{Softmax}(x)$ の i 番目の成分は以下になります:\n\n\\begin{align}\\frac{\\exp(x_i)}{\\sum_j \\exp(x_j)}\\end{align}\n\n\n\n出力値が確率分布をなす (各要素は非負で,かつ,全要素の総和が 1 ) ことは,明らかに重要です。\n入力に要素ごとの 指数化演算子を適用してすべてを非負にして,、正規化定数で除算すると考えることもできます。\n\n---\n\n### 訳注: \nPython で頻用される科学計算ライブラリ `scipy.special` には `scipy.special.logsumexp()` という関数が用意されている。\n上記ソフトマックス関数を計算する際に,分母 $\\sum\\exp(x_j)$ は 指数変換した各値を総和する (`sumexp` する) ことを意味し,\n確率密度関数の対数尤度を計算する場合には,この `sumexp` を対数変換するので `logsumexp` と命名された。\n`logsumexp()` 関数を用いてソフトマックス関数を定義すれば以下のようになる:\n\n\\begin{align}\\log\\text{softmax}(x_i) = x_i - \\text{logsumexp(x)}\\end{align}\n\nすなわちソフトマックス関数の対数を計算するときには,各値から `logsumexp(x)` を減じるだけになるので,\n計算が極端にかんたんになる。\n筆者の知る限り,Fortran 時代から logsumexp ルーチンは存在する。もはやその起源や命名者を特定できないように見受けられる。\n実際,以下のコードは同じ値を与える。\n\n```python\nimport numpy as np\nfrom scipy.special import softmax, logsumexp\n\nx1, x2, x3 = 1., 2., 3. \nprint(np.log(softmax([x1, x2, x3]))[0])\nprint( x1 - logsumexp([x1, x2, x3]))\n```\n\n\n\n\n\n```python\n# ソフトマックス関数 Softmax は torch.nn.functional でも定義されている\ndata = torch.randn(5)\nprint(data)\nprint(F.softmax(data, dim=0))\nprint(F.softmax(data, dim=0).sum()) # 確率分布であるから総和は 1 となる\nprint(F.log_softmax(data, dim=0)) # ソフトマックス関数の対数変換\n```\n\n tensor([ 1.3800, -1.3505, 0.3455, 0.5046, 1.8213])\n tensor([0.2948, 0.0192, 0.1048, 0.1228, 0.4584])\n tensor(1.)\n tensor([-1.2214, -3.9519, -2.2560, -2.0969, -0.7801])\n\n\n### 目的関数\n\n目的関数は学習に用いられ,ネットワークがその値を最小化されるよう訓練される関数です\n(*損失関数* または *コスト関数* とも呼ばれます)。\nこれは,最初に 訓練インスタンス を選択し,ニューラルネットワークを実行して 出力関数の損失値を計算することで進行します。\nその後,モデルのパラメータは,損失関数の微分を取ることで更新されます。\n直感的には,モデルがその答えに完全に自信を持っていて,その答えが誤っている場合,損失関数の値は大きくなります。\n反対に,その答えに非常に自信を持っていて,かつ,その答えが正しければ、損失値は小さくなります。\n\n学習事例の損失関数を最小化するという考え方は,ネットワークの一般化に関与します。\n訓練データセット,とテストデータセット,を分割するのは,訓練環境での未見のデータでの損失が小さいことを期待するためです。\n損失関数の例としては、*負の対数尤度損失* があります。\nこれは多クラス分類の非常に一般的な目的関数です。\n教師付き多クラス分類では,正しい出力の負の対数確率を最小にするようにネットワークを訓練することを意味します (正しい出力に対する対数確率を最大にする)。\n\n(訳注: 目的関数 ojbective function は,損失関数 loss function は,ほぼ同義で使われます。\nGoodfellow の教科書では objective, loss, goal, error function などは同義としてで扱う書かれています。)\n\n\n\n\n\n## 最適化と訓練\n\n\n\nSo what we can compute a loss function for an instance? \nWhat do we do with that? We saw earlier that Tensors know how to compute gradients with respect to the things that were used to compute it. \nWell, since our loss is an Tensor, we can compute gradients with respect to all of the parameters used to compute it! \nThen we can perform standard gradient updates. \nLet $\\theta$ be our parameters, $L(\\theta)$ the loss function, and $\\eta$ a positive learning rate. Then:\n\nある事例 (データ) の損失関数を実際どう計算するのでしょうか?\n先ほど,PyTorch のテンソルは計算に使われたすべてについての勾配計算に関する情報を知っていると説明しました。\n損失関数は PyTorch テンソル なので,計算に使われたすべてのパラメータに関する勾配を計算することができます。\n標準的な勾配降下法によりパラメータ更新が可能です。\n$\\theta$ をパラメータとし,損失関数を $L(\\theta)$,正の学習率を $\\eta$ とすれば次式を得ます:\n\n\n\n\\begin{align}\\theta^{(t+1)} = \\theta^{(t)} - \\eta \\nabla_\\theta L(\\theta)\\end{align}\n\n\n\nこのバニラ勾配降下法 による更新だけでなく,それ以上のことをしようとする試みには,膨大なアルゴリズムの研究が集積されていてり,活発な研究が行われています。\n(訳注: 何の飾り付けのない素のアルゴリズムという意味でしばしば `バニラ` vanilla という形容詞を用います。\n何のフレーバーもつかない素のアイスクリームをバニラアイスクリームと呼ぶように,\n例えば,教科書に記載されているような素の誤差逆伝播法のことを `バニラバックプロパゲーション` などと呼ぶ習慣があります)\nバニラではない,多くの発展的なアルゴリズムでは,訓練時に起こっていることに基づいて学習率を変化させます。\n本当に興味がない限り,これらのアルゴリズムが具体的に何をしているのかを気にする必要はありません。\nTorch では `torch.optim` パッケージで多くのアルゴリズムを提供しています。\nそれらアルゴリズムはすべて完全に透過的です。すなわち,\n最も単純な勾配更新法を使うこととは,より複雑なアルゴリズムと同じく扱うことができます。\nネットワークのパフォーマンスを最適化するには,さまざまな更新アルゴリズムや更新アルゴリズムのパラメータ (初期学習率の違いなど) を試すことが重要です。\n多くの場合, `バニラ SGD` を `Adam` や `RMSProp` のような最適化手法に置き換えるだけで,パフォーマンスが顕著に向上します。\n\n(訳注: バニラ SGD ではハイパーパラメータ $\\eta$ が固定です。\n一方 `RMSprop` 以降のアルゴリズムでは,各パラメータごとに異なる $\\eta$ を採用します。\nまた,2 次微分 **ヘッセ行列** を用いるニュートン法の近似として,ヘッセ行列を近似式で置き換えた\n準ニュートン法のニューラルネットワーク的実装が `Adam` です。ニュートン法からの類推で明らかなように\nAdam では学習係数 $\\eta$ をヘシアンに応じて調整します。\n)\n\n\n# PyTorch によるネットワークコンポネントの作成\n\n\n\nNLP の話に移る前に,アフィン写像と非線形性だけを使って PyTorch でネットワークを構築してみましょう。\n加えて,PyTorch の負の対数尤度を使って損失関数を計算し,誤差逆伝播法 (バックプロパゲーション) でパラメータを更新する方法も見てみましょう。\n\nすべてのネットワークコンポーネントは `nn.Module` を継承し,`forward()` メソッドをオーバーライドする必要があります。\nボイラープレート (訳注: いわゆるテンプレート版あるいはプロトタイプ,オブジェクト指向でのクラス定義的な意味合いです) に関する限りでは、これくらいです。\n`nn.Module` を継承することで コンポーネントに関数 (機能) を提供します。\n例えば 訓練可能なパラメータを管理したり ``.to(device)`` メソッドを使って CPU と GPU を入れ替えたりすることができます。\n\n疎な bag-of-words 表現を受け取り,2 つのラベルの確率分布を出力するネットワークの注釈付きの例を書いてみましょう。\n「英語」と「スペイン語」の 2 つのラベルの確率を出力するネットワークの例を書いてみましょう。\nこのモデルは単なるロジスティック回帰です。\n\n\n\n### 例: Bog-of-Words によるロジスティック回帰分類器\n\n\n\n\n\nモデルは 疎な BoW 表現をラベルの対数確率にマッピングするものです。\n語彙内の各単語にインデックスを割り当てます。例えば,全語彙が \"hello\" と \"world\" の 2 つの単語で成り立っているとします。\nそれぞれ 0 と 1 のインデックスを持つとします。\n文 \"hello hello hello hello hello hello \" の BoW ベクトルは次のようになります。\n\n\\begin{align}\\left[ 4, 0 \\right]\\end{align}\n\n同様に,\"hello, workd world hello\" の BoW ベクトルは次のようになります:\n\n\n\\begin{align}\\left[ 2, 2 \\right]\\end{align}\n\n一般には,次のような表記となります:\n\n\n\\begin{align}\\left[ \\text{Count}(\\text{hello}), \\text{Count}(\\text{world}) \\right]\\end{align}\n\nこの BOW ベクトルを $x$ と表記します。ネットワークの出力は以下のとおり:\n\n\n\n\\begin{align}\\log \\text{Softmax}(Ax + b)\\end{align}\n\nすなわち入力信号を アフィン写像に通して,その値に対して log softmax を行います。\n\n\n\n\n\n```python\ndata = [(\"me gusta comer en la cafeteria\".split(), \"SPANISH\"),\n (\"Give it to me\".split(), \"ENGLISH\"),\n (\"No creo que sea una buena idea\".split(), \"SPANISH\"),\n (\"No it is not a good idea to get lost at sea\".split(), \"ENGLISH\")]\n\ntest_data = [(\"Yo creo que si\".split(), \"SPANISH\"),\n (\"it is lost on me\".split(), \"ENGLISH\")]\n\n# word_to_ix は語彙中の各単語をとユニークな整数に変換します。\nword_to_ix = {}\nfor sent, _ in data + test_data:\n for word in sent:\n if word not in word_to_ix:\n word_to_ix[word] = len(word_to_ix)\nprint(word_to_ix)\n\nVOCAB_SIZE = len(word_to_ix)\nNUM_LABELS = 2\n\n\nclass BoWClassifier(nn.Module): # inheriting from nn.Module!\n\n def __init__(self, num_labels, vocab_size):\n # nn.Module の init 関数を呼び出します。文法で混乱しないように。\n # nn.Module での初期化が行われます\n super(BoWClassifier, self).__init__()\n\n # 必要なパラメータの定義。アフィン写像のパラメータ A と b \n # Torch には nn.Linear() が定義されており,これがアフィン写像を提供します\n # 入力次元が vocab_size であり,出力が num_labels である理由を理解してください。\n self.linear = nn.Linear(vocab_size, num_labels)\n\n # 非線形関数 log softmax にはパラメータがないことに注意\n\n def forward(self, bow_vec):\n # 入力を線形層に通し,さらに log_softmax に通します。\n # 多くの非線形関数ややその他の関数は torch.nn.functional にあります\n return F.log_softmax(self.linear(bow_vec), dim=1)\n\n\ndef make_bow_vector(sentence, word_to_ix):\n vec = torch.zeros(len(word_to_ix))\n for word in sentence:\n vec[word_to_ix[word]] += 1\n return vec.view(1, -1)\n\n\ndef make_target(label, label_to_ix):\n return torch.LongTensor([label_to_ix[label]])\n\n\nmodel = BoWClassifier(NUM_LABELS, VOCAB_SIZE)\n\n# モデルはパラメータを知っています。 以下の最初の出力は A,2番目の出力は bです。\n# モジュールの __init__ 関数でクラス変数にコンポーネントを代入するときはいつも\n# self.linear = nn.Linear(...) 行で行われていました。\n# PyTorch 開発者による Python 魔法により,このモジュール (BoWClassifier) は\n# nn.Linear のパラメータの知識を保持しています\nfor param in model.parameters():\n print(param)\n\n# このモデルを走らせるためには,BoW ベクトルを通します\n# ここでは訓練する必要がないので,以下では torch.no_grad() で warp します\nwith torch.no_grad():\n sample = data[0]\n bow_vector = make_bow_vector(sample[0], word_to_ix)\n log_probs = model(bow_vector)\n print(log_probs)\n```\n\n {'me': 0, 'gusta': 1, 'comer': 2, 'en': 3, 'la': 4, 'cafeteria': 5, 'Give': 6, 'it': 7, 'to': 8, 'No': 9, 'creo': 10, 'que': 11, 'sea': 12, 'una': 13, 'buena': 14, 'idea': 15, 'is': 16, 'not': 17, 'a': 18, 'good': 19, 'get': 20, 'lost': 21, 'at': 22, 'Yo': 23, 'si': 24, 'on': 25}\n Parameter containing:\n tensor([[ 0.1194, 0.0609, -0.1268, 0.1274, 0.1191, 0.1739, -0.1099, -0.0323,\n -0.0038, 0.0286, -0.1488, -0.1392, 0.1067, -0.0460, 0.0958, 0.0112,\n 0.0644, 0.0431, 0.0713, 0.0972, -0.1816, 0.0987, -0.1379, -0.1480,\n 0.0119, -0.0334],\n [ 0.1152, -0.1136, -0.1743, 0.1427, -0.0291, 0.1103, 0.0630, -0.1471,\n 0.0394, 0.0471, -0.1313, -0.0931, 0.0669, 0.0351, -0.0834, -0.0594,\n 0.1796, -0.0363, 0.1106, 0.0849, -0.1268, -0.1668, 0.1882, 0.0102,\n 0.1344, 0.0406]], requires_grad=True)\n Parameter containing:\n tensor([0.0631, 0.1465], requires_grad=True)\n tensor([[-0.5378, -0.8771]])\n\n\n\n\n上の値のうち、どれが ENGLISH の対数確率に対応し,どれが SPANISH の対数確率に対応するのでしょうか?\nこれまで定義したことはありませんでしたが,もし学習したいのであれば定義する必要があります。\n\n\n\n\n\n\n```python\nlabel_to_ix = {\"SPANISH\": 0, \"ENGLISH\": 1}\n```\n\n\n\n以下は訓練です。\n\n訓練には,インスタンスを通過させて対数確率を取得し,損失関数を計算し,損失関数の勾配を計算し,勾配ステップでパラメータを更新します。\n損失関数は Torch の nn パッケージ内で提供されています。\n`nn.NLLLoss()` は求める負の対数尤度損失です。 \n (訳注: NLL とは Negative Log Loss 関数,負の対数尤度を意味します)\nまた 最適化関数も torch.optim で定義されています。ここでは SGD を使用します。\n\nNLL 損失への *input* は対数確率のベクトルとターゲットラベルであることに注意してください。\nこの関数は 対数確率を計算してくれません。\nこれが,このネットワークの最後の層が log softmax である理由です。\n損失関数 nn.CrossEntropyLoss() は NLLLoss() と同じですが、log softmax を計算してくれます。\n\n\n\n```python\n# 訓練前にテストデータを評価します。訓練前後での変化を見るためです\nwith torch.no_grad():\n for instance, label in test_data:\n bow_vec = make_bow_vector(instance, word_to_ix)\n log_probs = model(bow_vec)\n print(log_probs)\n\n# \"creo\" に対応する行列の列を印字\nprint(next(model.parameters())[:, word_to_ix[\"creo\"]])\n\nloss_function = nn.NLLLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.1)\n\n# 学習データを何度か通したいと思うでしょう.\n# 100 は実際のデータセットよりもはるかに大きいです。\n# ですが 実際のデータセットは 2 つ以上のインスタンスを持っています。\n# 通常 5 から 30 エポックの間のどこかが妥当です。\nfor epoch in range(100):\n for instance, label in data:\n # ステップ 1. PyTorch には勾配が蓄積されていることを覚えておいてください\n # 各インスタンスの前にその勾配を ゼロ消去する必要があります\n model.zero_grad()\n\n # Step 2. Make our BOW vector and also we must wrap the target in a\n # Tensor as an integer. For example, if the target is SPANISH, then\n # we wrap the integer 0. The loss function then knows that the 0th\n # element of the log probabilities is the log probability\n # corresponding to SPANISH\n \n bow_vec = make_bow_vector(instance, word_to_ix)\n target = make_target(label, label_to_ix)\n\n # Step 3. Run our forward pass.\n log_probs = model(bow_vec)\n\n # Step 4. Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n loss = loss_function(log_probs, target)\n loss.backward()\n optimizer.step()\n\nwith torch.no_grad():\n for instance, label in test_data:\n bow_vec = make_bow_vector(instance, word_to_ix)\n log_probs = model(bow_vec)\n print(log_probs)\n\n# Index corresponding to Spanish goes up, English goes down!\nprint(next(model.parameters())[:, word_to_ix[\"creo\"]])\n```\n\n tensor([[-0.9297, -0.5020]])\n tensor([[-0.6388, -0.7506]])\n tensor([-0.1488, -0.1313], grad_fn=)\n tensor([[-0.2093, -1.6669]])\n tensor([[-2.5330, -0.0828]])\n tensor([ 0.2803, -0.5605], grad_fn=)\n\n\n\n\n正解が出ました! \n最初の例では,スペイン語の対数確率がはるかに高いことがわかります。\n英語では,テストデータの 2 番目の方が当然のように英語の方が高いです。\n\nこれで PyTorch コンポーネントを作って,そこにいくつかのデータを渡して,勾配更新を行う方法がわかりました。\nこれで ディープ NLP が提供するものをさらに深く掘り下げる準備が整いました。\n\n\n\n", "meta": {"hexsha": "cec6108225110c6314bb850ba941d8828cc5e33e", "size": 35883, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/02deep_learning_tutorial.ipynb", "max_stars_repo_name": "JPA-BERT/jpa-bert.github.io", "max_stars_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/02deep_learning_tutorial.ipynb", "max_issues_repo_name": "JPA-BERT/jpa-bert.github.io", "max_issues_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/02deep_learning_tutorial.ipynb", "max_forks_repo_name": "JPA-BERT/jpa-bert.github.io", "max_forks_repo_head_hexsha": "d0acda35703d876582b90b80298cfe0fa8590512", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0251798561, "max_line_length": 350, "alphanum_fraction": 0.5522949586, "converted": true, "num_tokens": 10252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.30271106987308805}} {"text": "# Chapter 2\n\n## Notes\n\n### Use of \"frequentist\"\n\nIn this chapter, \"frequentist\" is often equated with hypothesis testing based on P-values.\nHowever, that's a bit misleading.\nFundamentally, there are 2 branches statistics (frequentist and Bayesian), because we have two things we can condition on, the model or the data.\nFor a nice explanation of this grounded in decision theory, check out the first 20 minutes of this lecture by Michael Jordan (no, not \"air\" Jordan, more like \"err\" Jordan):\n\nhttp://videolectures.net/mlss09uk_jordan_bfway/\n\nIf your browser has trouble with this site, here's a YouTube version with no slides:\n\nhttps://www.youtube.com/watch?v=HUAE26lNDuE\n\nYou can approach hypothesis testing from a frequentist or Bayesian approach.\nWe tend to teach the frequentist approach (P-values and confidence intervals) to hypothesis testing, but they are not equivalent.\n\n### Comparing Bayes factors to AIC\n\nAt the end of the third paragraph of Section 2.4c, when comparing model choice using AIC and Bayes factors, it reads \"If all parameters can be estimated with precision, results from both approaches should be similar.\"\n\nThis is not always true. If the data are very informative, we can expect that our posterior probability densities of the parameters will be precise and robust to prior assumptions within each model. However, when comparing posterior probabilities across models, it is the average (marginal) likelihood of each model that updates prior probabilities. These average likelihoods are weighted by the prior. So, even if we have very informative data and precise parameter estimates within each model, the model posterior probabilities can still be very sensitive to the prior distributions on the parameters of each model.\n\nLong story short, if we put enough prior weight on unreasonable parameter values, we can \"sink\" the marginal likelihood of any model. This is responsible for what is known as [Lindley's Paradox](https://en.wikipedia.org/wiki/Lindley%27s_paradox).\n\nThis doesn't mean that Bayesian model comparison is bad. It simply means that the priors we place on each parameter within each model serve as a \"penalty\" for that parameter, so we have to choose those priors carefully.\n\n\n## Errata\n\n### Equation 2.7\n\n\\begin{equation}\n \\Delta = -2 \\ln \\frac{\\textrm{ML}_1}{\\textrm{ML}_2} = -2 (\\ln \\textrm{ML}_1 - \\ln \\textrm{ML}_2)\n\\end{equation}\n\n\n### Equation 2.21\n\n\"H\" should be \"D\" in the last equation. Also $p_h$ should be $p_H$:\n\n\\begin{equation}\n Pr(H|D) = \\frac{P(D | p_H, N) f(p_H)}{\\int_{0}^{1} P(D | p_H, N) f(p_H) dp_H}\n\\end{equation}\n\n### MCMC 3b\n\nThe proposal density is inverted. It should be:\n\n\\begin{equation}\n R_{\\textrm{proposal}} = \\frac{Q(p | p^{\\prime})}{Q(p^{\\prime} | p)}\n\\end{equation}\n\nThe way I remember this: If the proposing the new state is super likely, I need to penalize the acceptance ratio for it, so it needs to go in the denominator.\n\n### Last paragraph of Section 2.4c\n\n\"arrogance sampling\" should be \"importance sampling.\" Though, I must say, I am now partial to arrogance sampling.\n\n\n# Chapter 3\n\n## Notes\n\nParagraph 2 of Section 3.3a reads (in reference to Brownian motion):\n\n\"This model assumes that the number of alleles is so large that there is effectively no chance of mutations happening to the same allele more than once...\"\n\nThis is a bit confusing. At any given time, the model does not assume there must be a huge number of alleles. It only assumes that every mutation creates a new allele (it can't create an allele that has already been seen). So, as time approaches infinity, the total number of alleles observed (including the ones lost to drift, which is most of them) will approach infinity.\n\n## Errata\n\n### Equation 3.17\nThis distribution should not be for the expectation of $\\bar{z}(t)$. It should be:\n\n\\begin{equation}\n \\bar{z}(t) \\sim N(\\bar{z}(0), \\sigma_{B}^{2} t_1)\n\\end{equation}\n\n\n# Chapter 4\n\n## Errata\n\n### In the last paragraph of Section 4.2\n\n$e^{2.68} = 2.3$ should be $e^{0.85} = 2.3$\n\n### Second sentence after Equation 4.9\n\n\"Equation 4.8\" should be \"Equation 4.9,\" so that it reads:\n\n\"Equation 4.9 is exactly identical to the estimated rate fo evolution calculated using the average squared independent contract...\"\n", "meta": {"hexsha": "2dc93e171c9b56c6765dc74c8f9dbda5c48170da", "size": 5699, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "comments-and-errata.ipynb", "max_stars_repo_name": "phyletica/bayesian-lizard-flipping", "max_stars_repo_head_hexsha": "4150bd1222bba2837196c9c7e665ec3ab157f084", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "comments-and-errata.ipynb", "max_issues_repo_name": "phyletica/bayesian-lizard-flipping", "max_issues_repo_head_hexsha": "4150bd1222bba2837196c9c7e665ec3ab157f084", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "comments-and-errata.ipynb", "max_forks_repo_name": "phyletica/bayesian-lizard-flipping", "max_forks_repo_head_hexsha": "4150bd1222bba2837196c9c7e665ec3ab157f084", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1782945736, "max_line_length": 626, "alphanum_fraction": 0.6250219337, "converted": true, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.3024386177109419}} {"text": "# 7장 앙상블 학습과 랜덤 포레스트\n\n## 핵심 주제\n\n예측기의 모음을 **앙상블**(ensemble),\n앙상블을 이용한 예측기 학습을 **앙상블 학습**(ensemble learning),\n앙상블 학습 알고리즘을 **앙상블 기법**(ensemble method) 등으로 부른다. \n\n앙상블 기법을 적용하는 다양한 모델, 기법, 알고리즘 등을 살펴본다.\n\n1. 다수결 분류기\n1. 배깅/페이스팅\n 1. 랜덤 패치와 랜덤 서브스페이스\n1. 랜덤 포레스트 \n1. 부스팅\n 1. 에이다부스트\n 1. 그레이디언트 부스팅\n1. 스태킹\n\n## 파이썬 기본 설정\n\n* 파이선 버전 3.5 이상\n* 사이킷런 버전 0.20 이상\n* 모듈 불러오기\n * numpy\n * matplotlib\n * matplotlib.pyplot\n* 그림 저장 위치 지정\n\n\n```python\n# 파이썬 ≥3.5 필수\nimport sys\nassert sys.version_info >= (3, 5)\n\n# 사이킷런 ≥0.20 필수\nimport sklearn\nassert sklearn.__version__ >= \"0.20\"\n\n# 공통 모듈 임포트\nimport numpy as np\nimport os\n\n# 노트북 실행 결과를 동일하게 유지하기 위해\nnp.random.seed(42)\n\n# 깔끔한 그래프 출력을 위해\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\n# 그림을 저장할 위치\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"ensembles\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n print(\"그림 저장:\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format=fig_extension, dpi=resolution)\n```\n\n## 핵심 1: 다수결 분류기\n\n**다수결 분류기**(voting classifier)의 기본 개념은 \n동일한 훈련 세트에 대해 여러 종류의 분류기를 학습시킨 후 각 분류기의 예측을 모아\n다수결 방식으로 예측값을 결정하는 것이다. \n이와 같이 작동하는 분류기를 **직접 투표**(hard voting) 분류기라 부른다. \n\n반면에 사용되는 분류기가 모두 클래스에 포함될 확률을 계산하는 `predict_proba()` 메서드를\n지원한다면 사용된 분류기의 확률 예측을 평균 내어 가장 높은 확률의 클래스를 선택할 수 있다.\n이렇게 작동하는 분류기를 **간접 투표**(soft voting) 분류기라 부른다. \n확류리 높은 투표에 비중을 더 두기 때문에 직접 투표 방식보다 좀 더 좋은 성능을 발휘한다.\n\n아래 그림은 다수결 분류기의 기본적인 작동과정을 보여준다.\n\n\n\n<그림출처> [mlxtend: EnsembleVoteClassifier](http://rasbt.github.io/mlxtend/user_guide/classifier/EnsembleVoteClassifier/)\n\n다수결 분류기를 사용하면 하나의 성능이 좋은 분류기를 사용하는 것보다 일반적으로\n정확한 예측을 한다.\n단, 다수결 분류기에 포함된 분류기들 사이의 독립성이 전제되어야 한다. \n독립성이 제대로 보장되지 못하면 다수결 분류기의 성능이 성능이 낮아질 수도 있다.\n독립성이 어느 정도 이상 보장된 분류기를 이용하여 앙상블 학습을 하면 보다 좋은 \n성능의 분류기가 만들어지는 이유를 확률적으로 설명할 수 있다.\n\n앞면이 나올 확률이 51%로 약간 편향된 동전을 이용하여 동전 던지기 실험을 해보자.\n\n* 동전을 1,000번 던지면 동전의 앞면이 나오는 비율이 50% 이상일 확률은 74.7% 이다.\n* 동전을 10,000번 던지면 동전의 앞면이 나오는 비율이 50% 이상일 확률은 97.8% 이다.\n\n**참고**: 위 확률은 이항분포의 누적분포함수를 이용하여 계산할 수 있다. \n\n```\nfrom scipy.stats import binom\n1-binom.cdf(499, 1000, 0.51) # 0.747\n1-binom.cdf(4999, 10000, 0.51) # 0.978\n```\n\n아래 코드는 동전 10,000번 던지기를 10번 시행하는 것을\n모의실험으로 보여준다. \n앞서 언급한 확률대로라면 10,000번 던지기를 100번 하면 98번 정도는\n앞면이 나올 확률이 50% 이상이다. \n따라서 10,000번 던지기를 10번 하면 앞면이 50% 이하로 나오는 일은 사실상 없어야 하는데\n아래 모의실험이 이를 뒷받침한다.\n\n\n```python\nnp.random.seed(42)\n\nheads_proba = 0.51\ncoin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\ncumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n\nplt.figure(figsize=(8,3.5))\nplt.plot(cumulative_heads_ratio)\nplt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\nplt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\nplt.xlabel(\"Number of coin tosses\")\nplt.ylabel(\"Heads ratio\")\nplt.legend(loc=\"lower right\")\nplt.axis([0, 10000, 0.42, 0.58])\nsave_fig(\"law_of_large_numbers_plot\")\nplt.show()\n```\n\n위 결과의 의미는 다음과 같다. \n\n> 앞면이 나올 확률을 분류기의 정확도라고 하면, \n> 그런 분류기의 성능은 무작위로 찍는 것보다 아주 조금 좋은 정도이다. \n> 그런데 그런 분류기를 1,000 개 사용하여 클래스를 예측하고,\n> 가장 많이 예측된 클래스를 최종 선택하면 그 결과가 맞을 확률이 74.7%이고,\n> 그런 분류기를 10,000 개 사용하면 정확도가 97.8%까지 올라간다.\n\n물론, 이것은 사용되는 분류기가 완벽하게 서로 독립적이어서 서로의 결과에 어떤 영향도 주지 않아야 한다. \n하지만 동전 던지기와는 달리 동일한 훈련 세트를 사용해야 하는 모델 학습에서는\n절대로 그런 상호 독립성을 보장할 수 없다. \n분류기들이 동종의 오차를 만들 가능성이 기본적으로 높기 때문이며, 따라서 앙상블 모델의 정확도는\n이론보다 많이 낮아진다.\n\n### 사이킷런의 다수결 분류기\n\n사이킷런의 `VotingClassifier`가 다수결 분류기 모델을 제공한다. \n훈련 데이터셋으로 5장에서 사용한 moons 데이터셋이다. \n\n\n```python\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import make_moons\n\nX, y = make_moons(n_samples=500, noise=0.30, random_state=42)\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n```\n\n다음은 로지스틱 회귀, 랜덤 포레스트, 서포트 벡터머신 세 분류기를 \n이용하여 다수결 분류기를 생성한 후 학습한다.\n\n* `voting='hard'`: 직접 투표 방식 선택\n * 간접 투표 방식을 선택하려면 `'hard'` 대신에 `'soft'` 지정해야 함.\n\n**참고**: 사이킷런의 향후 버전과의 호환성을 위해 다음 옵션 인자를 사용함. \n* `solver=\"lbfgs\"`\n* `n_estimators=100`\n* `gamma=\"scale\"`.\n\n사용된 네 개의 분류기의 성능을 정확도를 이용하여 확인할 수 있다.\n다수결 분류기의 정확도가 91.2%로 개별 분류기보다 조금 더 성능이 좋다.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\n\n# 선형 회귀 \nlog_clf = LogisticRegression(solver=\"lbfgs\", random_state=42)\n# 랜덤 포레스트\nrnd_clf = RandomForestClassifier(n_estimators=100, random_state=42)\n# 서포트 벡터 머신\nsvm_clf = SVC(gamma=\"scale\", random_state=42)\n\n# 다수결 분류기: 직접 투표 방식\nvoting_clf = VotingClassifier(\n estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], voting='hard')\n\n# 다수결 분류기 학습\nvoting_clf.fit(X_train, y_train)\n\nfrom sklearn.metrics import accuracy_score\n\n# 분류기 별 정확도 측정\nfor clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(clf.__class__.__name__+':\\t', accuracy_score(y_test, y_pred))\n```\n\n LogisticRegression:\t 0.864\n RandomForestClassifier:\t 0.896\n SVC:\t 0.896\n VotingClassifier:\t 0.912\n\n\n간접 투표 방식을 사용하면 정확도가 92%로 조금 더 올라간다.\n\n* `voting='soft'` 사용.\n* SVC 모델의 경우 `predict_proba()` 메서드를 사용하기 위해 \n `probability=True` 옵션 인자를 지정해야 한다. \n\n\n```python\nlog_clf = LogisticRegression(solver=\"lbfgs\", random_state=42)\nrnd_clf = RandomForestClassifier(n_estimators=100, random_state=42)\nsvm_clf = SVC(gamma=\"scale\", probability=True, random_state=42)\n\n# 간접 투표 방식\nvoting_clf = VotingClassifier(\n estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], voting='soft')\n\nvoting_clf.fit(X_train, y_train)\n\nfrom sklearn.metrics import accuracy_score\n\nfor clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(clf.__class__.__name__+':\\t', accuracy_score(y_test, y_pred))\n```\n\n LogisticRegression:\t 0.864\n RandomForestClassifier:\t 0.896\n SVC:\t 0.896\n VotingClassifier:\t 0.92\n\n\n## 핵심 2: 배깅/페이스팅\n\n훈련 세트의 부분집합을 임의로 구성한 후 동일한 분류기를\n생성된 부분 집합을 이용하여 학습시키는 방식으로 앙상블 학습을 진행할 수 있다.\n즉, 사용되는 분류기 모델은 하나이지만,\n훈련 세트를 임의로 다르게 하여 여러 번 학습시킨다. \n\n훈련 세트의 부분집합을 임의로 선택할 때 중복 허용 여부에 따라 \n앙상블 학습 방식이 달라진다. \n\n* **배깅**(bootstrap aggregating): 중복 허용 샘플링\n* **페이스팅**(pasting): 중복 미허용 샘플링\n\n**참고**: 통계학에서 중복을 허용하는 표본 추출 방식을 **부트스트래핑**(bootstrapping)이라 부른다.\n\n아래 그림은 배깅 방식을 묘사한다.\n\n\n\n<그림출처> [WikimediaCommons: Bagging](https://commons.wikimedia.org/wiki/File:Bagging.png)\n\n### 앙상블 학습 예측 방식\n\n앙상블 학습 예측기는 최종적으로 **종합 함수**(aggregation function)가\n각 개별기의 결과를 종합해서 최종 예측값을 지정한다.\n\n* 분류 모델의 경우: 직접 투표 방식 사용. 즉, 수집된 예측값들 중에서 최빈값(mode) 선택.\n* 회귀 모델의 경우: 수집된 예측값들의 평균값 선택.\n\n### 편향과 분산\n\n앙상블 학습을 이용한 예측기의 경우 개별 예측기의 경우에 비해\n일반적으로 편향은 비슷하지만 분산은 줄어든다.\n즉, 과대적합의 위험성이 줄어든다.\n\n반면에 개별 학습기의 경우, 배깅/페이스팅 방식으로 학습하면\n전체 훈련 세트를 대상으로 학습한 경우에 비해 \n편향이 커지는데, 이는 훈련 세트가 작아지면 학습이 제대로 이루지지 않기 때문에\n당연한 결과이다. 즉, 과소적합 위험성이 커질 수밖에 없다.\n\n### 사이킷런의 배깅/페이스팅\n\n사이킷런에서 제공하는 배깅/페이스팅 모델은 다음과 같다.\n\n* 분류 모델: `BaggingClassifier`\n* 회귀 모델: `BaggingRegressor`\n\n아래 코드는 의사결정나무를 이용하여 배깅 앙상블 학습을 진행한다.\n사용된 모델 옵션은 다음과 같다. \n\n* `n_estimators=500`: 500개의 의사결정나무 학습기 훈련\n* `max_samples=100`: 각각의 의사결정나무 분류기에 사용될 훈련 샘플 수가 100개. 기본값은 1.0\n * 정수일 경우 지정된 수 만큼의 샘플 사용\n * 부동소수점 ($\\in [0, 1]$): 지정된 비율만큼의 샘플 사용. 즉, 기본값은 전체 샘플 수만큼 사용.\n* `bootstrap=True`: 중복 허용 표본 추출. 기본값은 `True`, 즉, 기본적으로 배깅 지원.\n* `n_jobs=-1`: 사용할 코어 수. -1은 가능한 모드 코어 사용.\n\n또한 의사결정나무의 경우처럼 `predict_proba()` 메서드가 지원되는 경우 \n자동으로 간접 투표(soft voting) 방식이 사용된다.\n\n\n```python\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\nbag_clf = BaggingClassifier(\n DecisionTreeClassifier(random_state=42), \n n_estimators=500,\n max_samples=100, \n # bootstrap=True 가 기본값임.\n# bootstrap=True,\n n_jobs=-1,\n random_state=42)\n\nbag_clf.fit(X_train, y_train)\ny_pred = bag_clf.predict(X_test)\n```\n\n앙상블 학습 결과의 정확도는 90.4%이다.\n\n\n```python\nfrom sklearn.metrics import accuracy_score\n\nprint(accuracy_score(y_test, y_pred))\n```\n\n 0.904\n\n\n반면에 하나의 의사결정나무의 정확도는 85.6%이다. \n\n\n```python\ntree_clf = DecisionTreeClassifier(random_state=42)\ntree_clf.fit(X_train, y_train)\ny_pred_tree = tree_clf.predict(X_test)\n\nprint(accuracy_score(y_test, y_pred_tree))\n```\n\n 0.856\n\n\n#### 분류 그래프 그리기 함수\n\n아래 코드에서 정의된 함수 `plot_decision_boundary` 함수는\n지정된 분류기가 지정된 훈련 세트를 대상으로 학습한 결과와 결정경계(decision boundary)를\n그래프로 보여준다.\n\n\n```python\nfrom matplotlib.colors import ListedColormap\n\ndef plot_decision_boundary(clf, X, y, axes=[-1.5, 2.45, -1, 1.5], alpha=0.5, contour=True):\n x1s = np.linspace(axes[0], axes[1], 100)\n x2s = np.linspace(axes[2], axes[3], 100)\n x1, x2 = np.meshgrid(x1s, x2s)\n X_new = np.c_[x1.ravel(), x2.ravel()]\n y_pred = clf.predict(X_new).reshape(x1.shape)\n custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n if contour:\n custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n plt.axis(axes)\n plt.xlabel(r\"$x_1$\", fontsize=18)\n plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n```\n\n아래 코드는 의사결정나무 하나를 이용한 분류기와 앞서 학습한 배깅 방식 앙상블 학습 결과를 보여준다.\n\n* 왼편 그래프: 의사결정나무 하나로 학습한 분류 결과\n* 오른편 그래프: 의사결정나무와 배깅 방식으로 학습한 분류 결과\n\n앙상블 학습의 일반화가 보다 좋으며, 편향은 비슷한 반면에 분산이 더 작다. \n\n* 편향: 잘못된 예측 정도는 두 방식이 거의 비슷함.\n* 분산: 과대적합 정도는 왼편이 보다 강함.\n\n\n```python\nfix, axes = plt.subplots(ncols=2, figsize=(10,4), sharey=True)\n\n# 왼편 그래프\nplt.sca(axes[0])\nplot_decision_boundary(tree_clf, X, y)\nplt.title(\"Decision Tree\", fontsize=14)\n\n# 오른편 그래프\nplt.sca(axes[1])\nplot_decision_boundary(bag_clf, X, y)\n\nplt.title(\"Decision Trees with Bagging\", fontsize=14)\nplt.ylabel(\"\")\nsave_fig(\"decision_tree_without_and_with_bagging_plot\")\nplt.show()\n```\n\n#### 배깅 대 페이스팅\n\n중복선택을 허용하는 배깅 방식이 사용되는 샘플 부분집합의 다양성을 좀 더 키우며,\n다음 효과를 가져온다.\n\n* 일반적으로 배깅 방식이 좀 더 편향은 키우고, 분산은 줄임.\n * 표본 샘플링의 무작위성을 커지면서 예측기들 사이의 상관관계 정도가 약화되기 때문임.\n* 전반적으로 배깅 방식이 좀 더 나은 모델 생성.\n* 교차검증을 통해 항상 확인 필요.\n\n### oob 평가\n\n배깅을 사용하면 한 번도 선택되지 못하는 샘플이 존재할 수 있다.\n뽑히지 않을 확률을 계산할 수 있으며 이론적으로 37% 정도 된다. \n\n실제로 $m$ 개의 샘플에서 임의로 선택되지 않을 확률은 $(1 - 1/m)$ 이며,\n따라서 중복을 허용하면서 $m$ 번 뽑았을 때 뽑히지 않을 확률은 $(1 - 1/m)^m$ 이다.\n이 값은 $m$이 증가함에 따라 0.368에 수렴한다.\n\n$$\n\\lim_{m\\to \\infty} (1-1/m)^m = e^{-1} = 0.368\n$$\n\n선택되지 않은 훈련 샘플을 **oob(out-of-bag)** 샘플이라고 부른다. \noob 샘플은 예측기마다 다르며, 예측기가 학습 중에 oob 샘플을 사용하지 않으므로\n이 샘플들을 검증 세트로 사용할 수 있다. \n앙상블 모델 자체는 예측기별 oob 평가의 평균값을 이용하여 평가할 수 있다. \n\n`BaggingClassifier` 의 `oob_score=True` 로 설정하면 oob 평가를 자동으로 실행한다.\n평가 점수는 `oob_score_`에 저장된다.\n\n* `max_samples` 옵션이 언급되지 았았기에 `max_samples=1.0` 기본 옵션이 사용된다. \n 즉, 중복을 허용하면서 전체 샘플 수 만큼 표본 추출. \n 따라서 전체 데이터의 37% 정도가 oob 샘플이 됨.\n\n\n```python\nbag_clf = BaggingClassifier(\n DecisionTreeClassifier(random_state=42), \n n_estimators=500,\n bootstrap=True, \n # max_samples=1.0이 기본값\n# max_samples=1.0\n oob_score=True, \n random_state=40)\nbag_clf.fit(X_train, y_train)\n\nbag_clf.oob_score_\n```\n\n\n\n\n 0.9013333333333333\n\n\n\noob 평가와 테스트 셋트에 대한 정확도가 비슷하게 나온다.\n\n\n```python\nfrom sklearn.metrics import accuracy_score\ny_pred = bag_clf.predict(X_test)\naccuracy_score(y_test, y_pred)\n```\n\n\n\n\n 0.912\n\n\n\noob 샘플에 대한 예측값은 클래스에 속할 확률을 이용하여 결정된다.\n모든 테스트 샘플에 대한 클래스 예측 확률은 `oob_decision_function_` 속성에 저장된다.\n\n`moons` 데이터 셋은 두 개의 클래스로 구성되었기 때문에\n각 샘플 별로 길이가 2인 리스트가 된다.\n처음 10개 샘플에 대한 클래스 예측 확률은 다음과 같다.\n예를 들어, 첫째 샘플의 경우 0번(음성) 클래스에 속할 확률은 31.75% 이고\n1번(양성) 클래스에 속할 확률은 68.25%이다. \n(클래스별 예측 확률의 합은 1임)\n\n\n```python\nbag_clf.oob_decision_function_[:10]\n```\n\n\n\n\n array([[0.31746032, 0.68253968],\n [0.34117647, 0.65882353],\n [1. , 0. ],\n [0. , 1. ],\n [0. , 1. ],\n [0.08379888, 0.91620112],\n [0.31693989, 0.68306011],\n [0.02923977, 0.97076023],\n [0.97687861, 0.02312139],\n [0.97765363, 0.02234637]])\n\n\n\n### 랜덤 패치/랜덤 서브스페이스\n\n`BaggingClassifier`는 특성을 대상으로 하는 두 개의 하이퍼파라미터를 제공한다. \n\n* `max_features`: \n * 학습에 사용할 특성 수를 지정. \n * 특성 선택은 무작위. \n * 정수인 경우: 지정된 수만큼 특성 선택\n * 부동소수점($\\in [0, 1]$)인 경우: 지정된 비율만큼 특성 선택\n * `max_samples`와 유사 기능 수행.\n* `bootstrap_features`: \n * 학습에 사용할 특성을 선택할 때 중복 허용 여부 지정. \n * 기본값은 `False`.\n * `botostrap`과 유사 기능 수행.\n \n이미지 등과 같이 매우 높은 차원의 데이터셋을 다룰 때 유용하게 사용될 수 있다. \n특성 샘플링은 더 다양한 예측기를 만들며, 일반적으로 편향이 커지지만 분산은 낮아진다. \n이유는 보다 적은 수의 특성을 사용하면 아무래도 예측이 부정확해질 수밖에 없는 반면에,\n데이터 샘플에 대해 보다 덜 민감하게 반응하게 된다.\n\n훈련 세트와 특성에 대한 샘플링 방식에 따라 아래 두 가지 기법으로 나뉘어진다.\n\n#### 랜덤 패치 기법\n\n훈련 샘플과 훈련 특성 모두를 대상으로 중복을 허용하며 임의의 샘플 수와 임의의 특성 수만큼을 샘플링 해서\n학습하는 기법이 **랜덤 패치 기법**이다. \n즉, 다음 두 조건이 참이어야 한다.\n\n* `bootstrap=True` 또는 `max_samples` < 1.0\n* `bootstrap_features=True` 또는 `max_features` < 1.0\n\n#### 랜덤 서브스페이스 기법\n\n전체 훈련 세트를 학습 대상으로 삼지만 훈련 특성은 임의의 특성 수만큼 샘플링 해서 \n학습하는 기법이 **랜덤 서브스페이스 기법**이다. \n즉, 다음 두 조건이 참이어야 한다.\n\n* `bootstrap=False` 그리고 `max_samples=1.0`\n* `bootstrap_features=True` 또는 `max_features` < 1.0\n\n## 핵심 3: 랜덤 포레스트\n\n배깅/페이스팅 방법을 적용한 의사결정나무의 앙상블을 최적화한 모델이 **랜덤 포레스트**(random forest)이다. \n\n아래 코드는 사이킷런에서 `RandomFrestClassifier`를 이용하여 랜덤 포레스트를 구현한다.\n\n* `n_estimators=500`: 500개의 의사결정나무 학습\n* `max_leaf_nodes=16`: 사용되는 의사결정나무의 잎의 수를 16개로 제한\n* `n_jobs=-1`: 가용 가능한 모든 CPU 사용\n\n**참조**: 회귀용 예측기는 `RandomForestRegressor`가 지원한다.\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\n\nrnd_clf = RandomForestClassifier(\n n_estimators=500, \n max_leaf_nodes=16, \n n_jobs=-1,\n random_state=42)\n\nrnd_clf.fit(X_train, y_train)\ny_pred_rf = rnd_clf.predict(X_test)\n```\n\n### 램덤 포레스트와 앙상블 학습: 번역서 버전\n\n아래 코드는 위 코드를\n`DecisionTreeClassifier`를 `BaggingClassifier`와\n함께 사용한 앙상블 모델이다. \n\n사용된 `DecisionTreeClassifier`의 특성은 다음과 같다.\n\n* `max_leaf_nodes=16`: 잎의 수를 16개로 제한함.\n* `max_samples=1.0`\n* `max_features=\"auto\"`: 학습에 사용되는 특성의 수를 전체 특성 수의 제곱근 값으로 제한한다. \n 즉, `max_features=sqrt(n_features)` 와 동일하게 작동한다.\n \n이 모델은 `splitter=best` 기본 옵션을 사용한다. \n따라서 마디에 사용되는 특성과 임곗값을 선택하기 위해 모든 가능성을 확인하기 때문에\n특성 수가 매우 크면 제곱근으로 특성 수를 줄인다 하더라도 \n시간이 오래 걸릴 수 있다.\n\n\n```python\nbag_clf_auto = BaggingClassifier(\n DecisionTreeClassifier(max_features=\"auto\", max_leaf_nodes=16, random_state=42),\n n_estimators=500,\n # max_samples=1.0 이 기본값임.\n max_samples=1.0, \n # bootstrap=True 가 기본값임.\n bootstrap=True,\n n_jobs=-1,\n random_state=42)\n\nbag_clf_auto.fit(X_train, y_train)\ny_pred_auto = bag_clf_auto.predict(X_test)\n```\n\n그러면 랜덤 포레스트의 결과와 완벽히 일치한다. \n아래 코드는 랜덤 포레스트 모델과 배깅 모델이 동일한 예측을 한다는 것을 보여준다. \n\n* `y_pred_auto == y_pred_rf`: 두 넘파이의 항목별 비교. 항목의 값이 같으면 1, 다르면 0.\n* `np.sum(y_pred_auto == y_pred_rf)`: 동일한 항목의 수\n\n\n```python\nnp.sum(y_pred_auto == y_pred_rf) / len(y_pred)\n```\n\n\n\n\n 1.0\n\n\n\n### 램덤 포레스트와 앙상블 학습: 영어 원서 버전\n\n영어 원서에는 아래와 같이 약가 다르게 설정된 배깅 방식으로 작성되었다. \n사용된 `DecisionTreeClassifier`의 특성은 다음과 같다.\n\n* `splitter=\"random\"`: 사용되는 특성 중에 무작위로 선택된 특성과 임곗값을 대상으로 최고의 특성과 임곗값 선택\n* `max_leaf_nodes=16`: 잎의 수를 16개로 제한함.\n* `max_samples=1.0`\n\n이 모델은 `max_features=None`인 기본값을 사용하기에 특성 전체를 대상으로 무작위 특성 선택을 진행한다.\n속도는 번역서 버전보다 빠르지만 조금 더 편향이 커진다. \n결과도 랜덤 포레스트와 100% 일치하지는 않는다.\n\n\n```python\nbag_clf_rand = BaggingClassifier(\n DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n n_estimators=500,\n # max_samples=1.0 이 기본값임.\n max_samples=1.0, \n # bootstrap=True 가 기본값임.\n bootstrap=True,\n n_jobs=-1,\n random_state=42)\n\nbag_clf_rand.fit(X_train, y_train)\ny_pred_rand = bag_clf_rand.predict(X_test)\n```\n\n두 모델에 의한 예측이 97.6% 동일하다.\n\n\n```python\nnp.sum(y_pred_rand == y_pred_rf) / len(y_pred)\n```\n\n\n\n\n 0.976\n\n\n\n### 엑스트라 트리\n\n앞서 설명하였듯이 랜덤 포레스트는 의사결정나무의 마디를 결정할 때 사용할 특성을 무작위로 선택된\n특성과 임곗값 전체를 대상으로 해서 그 중에 최적의 조합을 선택한다. \n즉, 의사결정나무의 아래 옵션을 사용하는 것과 동일하다.\n\n* `splitter=\"best\"`: 의사결정나무의 마디 속성을 정할 때 사용 대상 특성 전체를 대상으로해서 최적의 특성과 임곗값 선택.\n* `max_features=\"auto\"`: 학습에 사용되는 특성의 수를 전체 특성 수의 제곱근 값으로 제한.\n\n여기에 더해 최적의 임곗값을 찾는 대신 선택된 특성 중에서 일부만을 무작위로 대상으로 삼아 \n임계값을 무작위로 선택해서 샘플을 분할한 다음 그 중에 최선의 분할을 선택하는 방식을 사용할 수도 있다.\n즉, 아래 옵션을 함께 사용한다. \n\n* `splitter=\"random\"`: 의사결정나무의 마디 지정에 사용될 특성과 임곗값을 무작위로 지정해서 분할한 다음\n 그 중에 최선의 분할 선택.\n* `max_features=\"auto\"`: 학습에 사용되는 특성의 수를 전체 특성 수의 제곱근 값으로 제한.\n\n이렇게 하면 특성 수가 매우 클 때 일반적인 랜덤 포레스트보다 속도가 훨씨 빠르다. \n이런 방식을 사용하는 랜덤 포레스트를 **엑스트라 트리**(extra-trees) 또는\n**익스트림 랜덤 트리**(extremely randomized trees)라고 부른다. \n이 방식을 사용하면 역시 편향은 늘고, 분산은 줄어든다. \n\n아래 코드는 `BaggingClassifier`와 의사결정나무를 이용하여 엑스트라 트리가\n작동하는 방식을 구현한 것이다. \n앞서 사용한 랜덤 포레스트와의 차이가 좀 더 벌어졌음을 확인할 수 있다.\n\n\n```python\nbag_clf_randAuto = BaggingClassifier(\n DecisionTreeClassifier(splitter=\"random\", \n max_features=\"auto\", \n max_leaf_nodes=16, \n random_state=42),\n n_estimators=500,\n # max_samples=1.0 이 기본값임.\n max_samples=1.0, \n # bootstrap=True 가 기본값임.\n bootstrap=True,\n n_jobs=-1,\n random_state=42)\n\nbag_clf_randAuto.fit(X_train, y_train)\ny_pred_randAuto = bag_clf_randAuto.predict(X_test)\n```\n\n이때 두 모델에 의한 예측이 96.8%로 일치한다. \n\n\n```python\nnp.sum(y_pred_randAuto == y_pred_rf) / len(y_pred)\n```\n\n\n\n\n 0.968\n\n\n\n사이킷런의 `ExtraTreesClassifier`가 앞서 설명한 엑스트라 트리를 구현한다. \n\n\n```python\nfrom sklearn.ensemble import ExtraTreesClassifier\n\nextra_clf = ExtraTreesClassifier(\n n_estimators=500, \n max_leaf_nodes=16, \n n_jobs=-1,\n random_state=42)\n\nextra_clf.fit(X_train, y_train)\ny_pred_extra = extra_clf.predict(X_test)\n```\n\n앞서 구현한 `bag_clf_randAuto`와 완벽하게 동일한 예측을 한다. \n\n\n```python\nnp.sum(y_pred_randAuto == y_pred_extra) / len(y_pred)\n```\n\n\n\n\n 1.0\n\n\n\n앙상블 모델의 하이퍼파라미터에 따라 약간의 차이가 있지만 별 의미를 둘 필요는 없다. \n아주 큰 데이터셋, 보다 큰 특성 수를 다뤄야 하는 경우에는\n훈련 데이터터와 특성을 무작위적으로 선택하는 게 보다 효율적인데\n어쩔 수 없이 약간의 오차는 발생하게 된다.\n그리고 이렇게 하면 편향은 약간 높아지지만 분산은 낮아져서 전체적으로 보다 \n나은 모델을 얻게 된다.\n\n결론적으로 `RandomForestClassifier`와 `ExtraTreesClassifier` 중에\n누가 더 좋을지는 미리 알 수 없으며 교차 검증으로 확인하는 수 밖에 없다. \n또한 그리드 탐색을 이용하여 하이퍼파라미터를 튜닝할 수도 있다.\n\n### 특성 중요도\n\n랜덤 포레스트는 학습에 사용된 특성의 상대적 중요도도 함께 측정한다. \n특성 중요도는 해당 특성을 사용한 마디가 평균적으로 불순도를 얼마나 감소시키는지를 측정한다. \n즉, 불순도를 많이 줄이면 그만큼 중요도가 커진다. \n\n사이킷런의 `RandomForestClassifier`는 훈련이 끝난 뒤 특성별 중요도의\n전체 합이 1이 되도록 하는 방식으로 특성별 상대적 중요도를 측정한 후\n`feature_importances_` 속성에 저장한다. \n\n#### 예제: 붓꽃 데이터셋\n\n아래 코드는 붓꽃 데이터셋에 대해 랜덤 포레스트를 적용한 후 \n특성별 중요도를 평가한 자료를 확인해준다. \n\n* 꽃잎 길이(petal length): 44.1%\n* 곷잎 너비(petal width): 42.3%\n* 꽃받침 길이(sepal length): 11.3%\n* 곷받침 너비(sepal width): 2.3%\n\n\n```python\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\nrnd_clf = RandomForestClassifier(n_estimators=500, random_state=42)\nrnd_clf.fit(iris[\"data\"], iris[\"target\"])\n\nfor name, score in zip(iris[\"feature_names\"], rnd_clf.feature_importances_):\n print(name, score)\n```\n\n sepal length (cm) 0.11249225099876375\n sepal width (cm) 0.02311928828251033\n petal length (cm) 0.4410304643639577\n petal width (cm) 0.4233579963547682\n\n\n#### 예제: MNIST 손글씨 데이터셋\n\n3장에서 다룬 MNIST 데이터셋에서 다룬 숫자 이미지는 `28x28=784` 개의 픽셀을 \n샘플 특성으로 사용하였다.\nMNIST 데이터셋에 랜덤 포레스트 분류기를 훈련시키고 각 픽셀의 중요도를 확인할 수 있다.\n\n\n```python\nfrom sklearn.datasets import fetch_openml\n\nmnist = fetch_openml('mnist_784', version=1)\nmnist.target = mnist.target.astype(np.uint8)\n\nrnd_clf = RandomForestClassifier(n_estimators=100, random_state=42)\nrnd_clf.fit(mnist[\"data\"], mnist[\"target\"])\n```\n\n\n\n\n RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False)\n\n\n\n이전에 설명한 대로 손글씨 숫자는 이미지 중앙에 그려지고 테두리는 흰색으로 채워져 있어서\n테두리로 갈수록 중요도가 떨어진다.\n아래 코드가 이것을 그림으로 확인해준다.\n\n`plot_digit()` 함수는 중요도를 `cmap=mpl.cm.hot` 속성을 이용하여 표현한다.\n어두운 색은 낮은 중요도를, 밝은 색은 높은 중요도를 보여준다.\n\n\n```python\ndef plot_digit(data):\n # 28x28 사이즈로 형태 변환\n image = data.reshape(28, 28)\n # 그림 그리기\n plt.imshow(image, cmap = mpl.cm.hot, interpolation=\"nearest\")\n # 축은 사용하지 않음.\n plt.axis(\"off\")\n\n# 이미지 속성 중요도 색으로 표현\nplot_digit(rnd_clf.feature_importances_)\n\n# 색상의 중요도를 보여주는 참조용 막대그래프. 오른편에 위치.\ncbar = plt.colorbar(ticks=[rnd_clf.feature_importances_.min(), rnd_clf.feature_importances_.max()])\ncbar.ax.set_yticklabels(['Not important', 'Very important'])\n\nsave_fig(\"mnist_feature_importance_plot\")\nplt.show()\n```\n\n## 핵심 4: 부스팅\n\n**부스팅**(boosting)은 성능이 약한 학습기의 여러 개를 선형으로 연결하여 강한 성능의 학습기를 만드는\n앙상블 기법을 의미한다. \n즉, 여러 개의 학습기가 동시에 학습하는 것이 아니라 **순차적으로 이전 학습기의 결과를 바탕으로\n성능을 조금씩 높혀가는 방식**으로 학습을 이어간다.\n이런 이유로 배깅/페이스팅에 비해 확장성이 떨어진다는 단점을 갖는다.\n\n이와같이 성능이 약한 예측기의 단점을 보완하여 보다 좋은 성능의 예측기를 훈련해 나가는 것이 \n**부스팅**의 기본 아이디어이다.\n여기서는 가장 인기 높은 **에이다부스트**(AdaBoost)와 **그레이디언트부스팅**(Gradient Boosing)을 소개한다.\n\n**참조**:\n* 부스트(boost)의 사전적 의미는 늘리다, 활성화하다 등이다.\n* 에이다부스트(AdaBoost)는 Adaptive Boosting의 줄임말이다. \n\n### 에이다부스트(AdaBoost)\n\n이전 모델이 제대로 학습하지 못한 샘플들에 대한 가중치를 조절하여 새로운 모델을 만들어 가는 방식을\n**에이다부스트**라 부른다. \n이 방식을 사용하면 새로운 예측기는 학습하기 어려운 샘플에 조금씩 더 잘 적응하는 모델이 연속적으로 만들어져 간다.\n\n\n\n<그림출처> [Medium: Understanding AdaBoost for Decision Tree](https://miro.medium.com/max/1400/0*KYszvMnr3nCtjaGy.png)\n\n#### 에이다부스트 알고리즘\n\n에이다부스트 알고리즘을 설명하기 전에 먼저 아래 사항을 전제한다. \n\n* $m$: 훈련 세트 크기\n* $N$: 사용되는 예측기 수\n* $\\eta$: 학습률\n\n에이다부스트 알고리즘 작동방식은 다음과 같다.\n\n1. 먼저 각 **샘플에 대한 가중치** $w^{(i)}$ 를 $1/m$로 설정.\n

\n1. $j = 1, 2, ..., N$을 대상으로 아래 과정을 순차적으로 반복한다.\n

\n 1. $j$ 번 째 예측기 학습\n

\n 1. 가중치 적용 에러율 $r_j$ 계산.\n
\n $$\n r_j = \\Big( \\sum_{i=1,\\,\\, \\hat y_j^{(i)} \\neq y^{(i)}}^{m} w^{(i)} \\Big) \\Big/\n \\Big( \\sum_{i=1}^{m} w^{(i)} \\Big)\n $$\n
\n 1. **예측기 가중치** $\\alpha_j$ 계산\n
\n $$\n \\alpha_j = \\eta \\, \\log\\Big( \\frac{1-r_j}{r_j} \\Big)\n $$\n
\n 1. 각 샘플에 대한 가중치 업데이트\n
\n $$\n w(i) \\gets \\begin{cases} w^{(i)} & \\text{if }\\,\\, \\hat y_j^{(i)} = y^{(i)} \\\\ w^{(i)}\\,\\exp(\\alpha_j) & \\text{if }\\,\\, \\hat y_j^{(i)} \\neq y^{(i)}\\end{cases}\n $$\n
\n1. $j=N$이 되거나 완벽한 예측기가 학습되면 위 과정을 멈춘다.\n\n#### 알고리즘의 수학적 의미\n\n사용된 수식의 의미는 다음과 같다.\n\n* 가중치 적용 에러율 $r_j$\n * 예측값이 실제와 다른 샘플에 사용된 가중치가 차지하는 비중 계산\n * 즉, $j$번 째 예측기의 정확도를 낮추는 샘플에 사용되는 가중치의 비중 측정\n

\n* 예측기 가중치 $\\alpha_j$와 샘플 가중치 업데이트\n

\n * $r_j \\le 0.5$ 인 경우\n * 예측기의 적중율에 미치는 가중치 적용 에러율이 높지 않음을 의미.\n * 즉, 예측값이 틀린 샘플에 사용된 가중치의 역할이 크지 않았음을 반증함.\n * 따라서 예측값이 틀린 샘플에 사용된 가중치를 좀 더 높게 설정할 필요 있음.\n * 수학적으로 아래와 같이 설명됨.\n * $\\frac{1-r_j}{r_j} \\ge 1$, 따라서 $\\alpha_j \\ge 0$.\n * $\\exp(\\alpha_j) \\ge 1$이 되어 $w^{(i)}$ 값 증가시킴(단, $\\hat y_j^{(i)} \\neq y^{(i)}$).\n

\n * $r_j > 0.5$ 인 경우\n * 예측기의 적중율에 미치는 가중치 적용 에러율이 높음을 의미.\n * 즉, 예측값이 틀린 샘플에 사용된 가중치의 역할이 컸음을 반증함.\n * 따라서 예측값이 틀린 샘플에 사용된 가중치를 좀 더 낮게 설정할 필요 있음.\n * 수학적으로 아래와 같이 설명됨.\n * $\\frac{1-r_j}{r_j} < 1$, 따라서 $\\alpha_j < 0$.\n * $\\exp(\\alpha_j) < 1$이 되어 $w^{(i)}$ 값 감소시킴(단, $\\hat y_j^{(i)} \\neq y^{(i)}$).\n \n\n#### 최종 예측값\n\n모든 예측기의 예측을 계산하고 가장 높은 비중의 가중치가 사용된 예측값을 선택한다. \n\n\\begin{equation}\n\\hat y(\\mathbf x) = \\mathrm{argmax}_k\\sum^{N}_{j=1, \\,\\, \\hat y_j(\\mathbf x) = k} \\alpha_j\n\\end{equation}\n\n즉, 가중치를 키웠을 때의 예측값이 가장 많이 선택되었다면 최종적으로 그 값을 선택한다는 의미이다. \n\n#### 사이키런의 에이다부스트\n\n사이킷런은 `AdaBoostClassifier` 분류 모델과 `AdaBoostRegressor` 회귀 모델을 지원한다.\n두 모델이 사용하는 알고리즘은 앞서 설명한 알고리즘을 다중 클래스 버전으로 일반화한\n**SAMME** 라는 알고리즘을 사용한다. \n\n사용되는 예측기가 `predict_proba()` 메서드를 지원하면\n클래스에 속할 확률을 이용하는 \n**SAMME.R** 이라는 약간 변형된 알고리즘을 사용하며, 일반적으로 보다 성능이 좋다. \n\n아래 코드는 최대 깊이가 1인 의사결정나무 200개를 이용하는 에이다부스트 분류기를 구현하며,\n이것이 에이다부스트의 기본 설정이다.\n\n* `max_depth=1`: 잎이 아닌 마디가 단 하나뿐임. 즉, 뿌리 마디와 여러 개의 잎만 존재하는 의사결정나무.\n\n\n\n\n```python\nfrom sklearn.ensemble import AdaBoostClassifier\n\nada_clf = AdaBoostClassifier(\n DecisionTreeClassifier(max_depth=1), \n n_estimators=200,\n algorithm=\"SAMME.R\", \n learning_rate=0.5, \n random_state=42)\n\nada_clf.fit(X_train, y_train)\n```\n\n\n\n\n AdaBoostClassifier(algorithm='SAMME.R',\n base_estimator=DecisionTreeClassifier(class_weight=None,\n criterion='gini',\n max_depth=1,\n max_features=None,\n max_leaf_nodes=None,\n min_impurity_decrease=0.0,\n min_impurity_split=None,\n min_samples_leaf=1,\n min_samples_split=2,\n min_weight_fraction_leaf=0.0,\n presort=False,\n random_state=None,\n splitter='best'),\n learning_rate=0.5, n_estimators=200, random_state=42)\n\n\n\n학습 결과는 다음과 같다.\n학습 결과가 과대적합된 것으로 판단되면 추정기 수를 줄이거나 보다 강한 규제를 사용할 수 있다.\n\n\n```python\nplot_decision_boundary(ada_clf, X, y)\n```\n\n#### 에이다부스트 직접 구현하기\n\n아래 코드는 서포트벡터머신을 이용하여 에이다부스트 알고리즘과\n비슷하게 작동하는 코드이다. \n\n* `rbf` 커널을 사용하는 `SVC` 모델\n* 예측값이 틀린 샘플의 가중치를 5번 업데이트할 때의 학습과정을 그래프로 보여줌.\n* 왼편 그림: 학습률 1.0\n * 학습이 널뛰는 것을 확인 가능\n* 오른편 그림: 학습률 0.5\n * 학습을 잘함.\n* 훈련 세트는 moons 데이터셋 그대로 사용.\n\n\n```python\nm = len(X_train)\n\nfix, axes = plt.subplots(ncols=2, figsize=(10,4), sharey=True)\n\n# (그림위치, 학습률) = (0, 1): 왼편 그림, 학습률 1\n# (그림위치, 학습률) = (1, 0.5): 오른편 그림, 학습률 0.5\nfor subplot, learning_rate in ((0, 1), (1, 0.5)):\n # sample_weights 높을 수록 해당 샘플을 더 중요시 여김.\n # 처음엔 m으로 동일하게 시작\n sample_weights = np.ones(m)\n \n plt.sca(axes[subplot])\n # 5번 학습\n # 반복 학습때마다 예측값이 틀린 샘플에 대한 가중치 높힘.\n for _ in range(5):\n # SVC 모델 학습\n svm_clf = SVC(kernel=\"rbf\", C=0.05, gamma=\"scale\", random_state=42)\n svm_clf.fit(X_train, y_train, sample_weight=sample_weights)\n # 학습 모델 예측\n y_pred = svm_clf.predict(X_train)\n # 예측값 틀린 샘플에 대한 가중치 키우기\n sample_weights[y_pred != y_train] *= (1 + learning_rate)\n \n # 그래프 그리기\n plot_decision_boundary(svm_clf, X, y, alpha=0.2)\n plt.title(\"learning_rate = {}\".format(learning_rate), fontsize=16)\n\n # 왼편 그래프에 번호 추가. 1번 ~ 5번\n if subplot == 0:\n plt.text(-0.7, -0.65, \"1\", fontsize=14)\n plt.text(-0.6, -0.10, \"2\", fontsize=14)\n plt.text(-0.5, 0.10, \"3\", fontsize=14)\n plt.text(-0.4, 0.55, \"4\", fontsize=14)\n plt.text(-0.3, 0.90, \"5\", fontsize=14)\n else:\n plt.ylabel(\"\")\n\nsave_fig(\"boosting_plot\")\nplt.show()\n```\n\n**주의**: 서포트벡터 머신은 에이다부스트에 잘 사용되지 않는다. \n위에서도 보았듯이 학습률에 따른 불안정성이 큰 편이기 때문이다. \n여기서를 예시를 위해 사용되었다.\n\n### 그레이디언트 부스팅\n\n이전 학습기에 의한 오차를 보정하도록 새로운 예측기를 순차적으로 추가하는 아이디어는 \n에이다부스트와 동일하다. \n하지만 샘플의 가중치를 수정하는 대신 이전 예측기가 만든 **나머지 오차**(residual error)에\n대해 새로운 예측기를 학습시킨다. \n\n**주의**: 나머지 오차를 책에서는 **잔여 오차**로 번역하였음. \n하지만 수학의 나머지 개념이 보다 적절해 보임.\n\n#### 그레이디언트 부스팅 기법으로 회귀 모델 학습하기\n\n아래 코드는 회귀 모델을 그레이디언트 부스팅 기법으로 학습해 가는 과정을 보여준다.\n훈련 세트는 2차방정식으로 생성한 데이터셋을 사용한다. \n가우시안 잡음도 추가되었다. \n\n\n```python\nnp.random.seed(42)\nX = np.random.rand(100, 1) - 0.5\ny = 3*X[:, 0]**2 + 0.05 * np.random.randn(100)\n```\n\n* 1 단계: 의사결정나무 회귀모델을 이용하여 학습한다.\n * `max_depth=2`\n\n\n```python\nfrom sklearn.tree import DecisionTreeRegressor\n\ntree_reg1 = DecisionTreeRegressor(max_depth=2, random_state=42)\ntree_reg1.fit(X, y)\n```\n\n\n\n\n DecisionTreeRegressor(criterion='mse', max_depth=2, max_features=None,\n max_leaf_nodes=None, min_impurity_decrease=0.0,\n min_impurity_split=None, min_samples_leaf=1,\n min_samples_split=2, min_weight_fraction_leaf=0.0,\n presort=False, random_state=42, splitter='best')\n\n\n\n* 2 단계: 1단계 예측기의 예측 결과와의 오차에 대한 레이블을 대상으로 의사결정나무 회귀모델 학습\n * `max_depth=2`\n\n\n```python\ny2 = y - tree_reg1.predict(X)\ntree_reg2 = DecisionTreeRegressor(max_depth=2, random_state=42)\ntree_reg2.fit(X, y2)\n```\n\n\n\n\n DecisionTreeRegressor(criterion='mse', max_depth=2, max_features=None,\n max_leaf_nodes=None, min_impurity_decrease=0.0,\n min_impurity_split=None, min_samples_leaf=1,\n min_samples_split=2, min_weight_fraction_leaf=0.0,\n presort=False, random_state=42, splitter='best')\n\n\n\n* 3 단계: 2단계 예측기의 예측 결과와의 오차에 대한 레이블을 대상으로 의사결정나무 회귀모델 학습\n * `max_depth=2`\n\n\n```python\ny3 = y2 - tree_reg2.predict(X)\ntree_reg3 = DecisionTreeRegressor(max_depth=2, random_state=42)\ntree_reg3.fit(X, y3)\n```\n\n\n\n\n DecisionTreeRegressor(criterion='mse', max_depth=2, max_features=None,\n max_leaf_nodes=None, min_impurity_decrease=0.0,\n min_impurity_split=None, min_samples_leaf=1,\n min_samples_split=2, min_weight_fraction_leaf=0.0,\n presort=False, random_state=42, splitter='best')\n\n\n\n새로운 샘플에 대한 예측값은 사용된 모든 예측기의 예측값을 더한다.\n\n\n```python\n# 새로운 샘플\nX_new = np.array([[0.8]])\n# 모든 예측값 더하기\ny_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3))\n\nprint(y_pred)\n```\n\n [0.75026781]\n\n\n아래 그림은 학습된 세 개의 회귀 모델를 그래프로 보여준다.\n\n* 왼쪽 열: 세 단계별로 학습된 모델의 예측값을 보여준다.\n* 오른쪽 열: 단계별 학습 모델의 누적 예측값을 보여준다.\n\n행별로 설명하면 다음과 같다.\n\n* 1행: 왼쪽과 오른쪽이 동일하다. \n* 2행: 오른쪽 그래프는 왼쪽의 1단계 ~ 2단계 예측값의 합을 보여준다.\n* 3행: 오른쪽 그래프는 왼쪽의 1단계 ~ 3단계 예측값의 합을 보여준다.\n\n\n```python\n# 예측값 그래프 그리기\ndef plot_predictions(regressors, X, y, axes, label=None, style=\"r-\", data_style=\"b.\", data_label=None):\n x1 = np.linspace(axes[0], axes[1], 500)\n # 회귀 모델 리스트를 대상으로 예측값의 합 계산\n y_pred = sum(regressor.predict(x1.reshape(-1, 1)) for regressor in regressors)\n \n # 기존 데이터셋과 레이블\n plt.plot(X[:, 0], y, data_style, label=data_label)\n # 새로운 데이터셋과 예측값\n plt.plot(x1, y_pred, style, linewidth=2, label=label)\n\n if label or data_label:\n plt.legend(loc=\"upper center\", fontsize=16)\n plt.axis(axes)\n\nplt.figure(figsize=(11,11))\n\n# 왼편 1행\nplt.subplot(321)\nplot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h_1(x_1)$\", style=\"g-\", data_label=\"Training set\")\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\nplt.title(\"Residuals and tree predictions\", fontsize=16)\n\n# 오른편 1행\nplt.subplot(322)\nplot_predictions([tree_reg1], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h(x_1) = h_1(x_1)$\", data_label=\"Training set\")\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\nplt.title(\"Ensemble predictions\", fontsize=16)\n\n# 왼편 2행\nplt.subplot(323)\nplot_predictions([tree_reg2], X, y2, axes=[-0.5, 0.5, -0.5, 0.5], label=\"$h_2(x_1)$\", style=\"g-\", data_style=\"k+\", data_label=\"Residuals\")\nplt.ylabel(\"$y - h_1(x_1)$\", fontsize=16)\n\n# 오른편 2행\nplt.subplot(324)\nplot_predictions([tree_reg1, tree_reg2], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h(x_1) = h_1(x_1) + h_2(x_1)$\")\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\n\n# 왼편 3행\nplt.subplot(325)\nplot_predictions([tree_reg3], X, y3, axes=[-0.5, 0.5, -0.5, 0.5], label=\"$h_3(x_1)$\", style=\"g-\", data_style=\"k+\")\nplt.ylabel(\"$y - h_1(x_1) - h_2(x_1)$\", fontsize=16)\nplt.xlabel(\"$x_1$\", fontsize=16)\n\n# 오른편 3행\nplt.subplot(326)\nplot_predictions([tree_reg1, tree_reg2, tree_reg3], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"$h(x_1) = h_1(x_1) + h_2(x_1) + h_3(x_1)$\")\nplt.xlabel(\"$x_1$\", fontsize=16)\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\n\nsave_fig(\"gradient_boosting_plot\")\nplt.show()\n```\n\n#### 그레이디언트 부스티드 회귀 나무\n\n앞서 설명한 대로 의사결정나무를 그레이디언트 부스팅 알고리즘으로 작동시키는 회귀 모델을 \n**그레이디언트 트리 부스팅**(gradient tree boosting)\n또는 \n**그레이디언트 부스티드 회귀 나무**(gradient boosted regression tree, GBRT)라 부른다. \n\n#### 사이킷런 그레이디언트 부스팅 모델\n\n앞서 직접 구현한 GBRT 알고리즘과 동일하게 작동하는 모델을\n사이킷런의 `GradientBoostingRegressor` 클래스가 제공하며,\n`RandomForestRegressor`와 비슷한 하이퍼파라미터를 제공한다. \n\n* `max_depth=2`: 의사결정나무 깊이 2\n* `n_estimators=3`: 3개의 의사결정나무 연속으로 훈련\n\n##### `learning_rate` (학습률)\n\n`learnign_rate`는 기존에 설명한 학습률과 다른 의미의 학습률이다.\n\n* 기존 학습률: 하나의 모델이 학습되는 과정에서 샘플 특성의 가중치를 업데이트할 때 사용되는\n 손실함수의 그레이디언트 비율 지정\n* 이전 의사결정나무에서 학습된 값을 전달할 때 사용되는 비율.\n * 1.0이면 그대로 전달. \n * 1.0보다 작으면 해당 비율 만큼 조금만 전달.\n \n하지만 그레이디언트 부스팅 알고리즘은 모델 내부의 가중치가 아닌 \n모델 자체를 새로운 모델로 업데이트 하면서\n최적의 모델을 찾아가는 과정이다.\n\n이때, 나머지 오차는 특정 손실함수의 그레이디언트와 연관되어 있다.\n따라서 나머지 오차를 얼마의 비율로 사용하여 새로운 모델로 업데이트할까를\n정하는 문제는 기존에 설명된 학습률과 사실상 동일한 개념이다.\n이에 대한 자세한 설명은 하지 않으며, 대신에 \n[위키백과: Gradient boosting](https://en.wikipedia.org/wiki/Gradient_boosting#cite_note-MasonBaxterBartlettFrean1999a-4)을 \n읽어보기를 추천한다.\n\n#### 축소 규제\n\n학습률(`learning_rate`)을 이용하여 학습 과정을 조절하는 방식을 **축소**(shrinkage) 규제라 부른다. \n학습률을 낮추면 보다 많은 의사결정나무가 필요하지만 일반적으로 예측 성능을 좋아진다.\n\n아래 코드는 학습률을 1로 지정한 경우와 0.1롷 지정한 경우를 보여준다.\n\n* 왼편 그래프: 앞서 수동으로 실험해본 그레이디언트 부스팅 알고리즘과 동일한 결과를 내준다.\n 사용되는 의사결정나무의 수를 3으로 좀 적게 지정하였음. 결과는 과소적합\n * `learning_rate=1.0`\n * `n_estimators=3`\n * 과소적합 되었음.\n* 오른편 그래프: 학습률을 0.1로 훨씬 작게 만들었음. 따라서 사용되는 의사결정나무의 수를 200으로 늘렸음. \n 결과는 과대적합.\n * `learning_rate=0.1`\n * `n_estimators=200`\n * 과소적합 되었음.\n \n\n\n```python\nfrom sklearn.ensemble import GradientBoostingRegressor\n\n# 왼편 그래프 모델\ngbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0, random_state=42)\ngbrt.fit(X, y)\n\n# 오른편 그래프 모델\ngbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42)\ngbrt_slow.fit(X, y)\n\n# 그래프 그리기\nfix, axes = plt.subplots(ncols=2, figsize=(10,4), sharey=True)\n\n# 왼편 그래프\nplt.sca(axes[0])\nplot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"Ensemble predictions\")\nplt.title(\"learning_rate={}, n_estimators={}\".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14)\nplt.xlabel(\"$x_1$\", fontsize=16)\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\n\n# 오른편 그래프\nplt.sca(axes[1])\nplot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8])\nplt.title(\"learning_rate={}, n_estimators={}\".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14)\nplt.xlabel(\"$x_1$\", fontsize=16)\n\nsave_fig(\"gbrt_learning_rate_plot\")\nplt.show()\n```\n\n아래 그림은 왼편 모델에 사용되는 의사결정나무를 20으로 늘렸을 때, 오른편과 비슷한 결과를 \n보여주는 것을 확인해준다.\n즉, 학습률(`learning_rate`)와 예측기 수(`n_estimators`) 사이에 반비례 관계가 \n어느 정도 성립한다는 것을 볼 수 있다.\n\n\n```python\nfrom sklearn.ensemble import GradientBoostingRegressor\n\n# 왼편 그래프 모델\ngbrt = GradientBoostingRegressor(max_depth=2, n_estimators=20, learning_rate=1.0, random_state=42)\ngbrt.fit(X, y)\n\n# 오른편 그래프 모델\ngbrt_slow = GradientBoostingRegressor(max_depth=2, n_estimators=200, learning_rate=0.1, random_state=42)\ngbrt_slow.fit(X, y)\n\n# 그래프 그리기\nfix, axes = plt.subplots(ncols=2, figsize=(10,4), sharey=True)\n\n# 왼편 그래프\nplt.sca(axes[0])\nplot_predictions([gbrt], X, y, axes=[-0.5, 0.5, -0.1, 0.8], label=\"Ensemble predictions\")\nplt.title(\"learning_rate={}, n_estimators={}\".format(gbrt.learning_rate, gbrt.n_estimators), fontsize=14)\nplt.xlabel(\"$x_1$\", fontsize=16)\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\n\n# 오른편 그래프\nplt.sca(axes[1])\nplot_predictions([gbrt_slow], X, y, axes=[-0.5, 0.5, -0.1, 0.8])\nplt.title(\"learning_rate={}, n_estimators={}\".format(gbrt_slow.learning_rate, gbrt_slow.n_estimators), fontsize=14)\nplt.xlabel(\"$x_1$\", fontsize=16)\n\nsave_fig(\"gbrt_learning_rate_plot\")\nplt.show()\n```\n\n### 그레이디언트 부스팅 조기 종료\n\n최적의 트리 수를 찾기 위해 조기 종료 기법을 사용할 수 있으며, 여기서는 두 가지 방식을 소개한다.\n\n#### `staged_predict()` 메서드 활용\n\n`staged_predict()` 메서드는 훈련되는 예측기 전체를 대상으로 하는 반복자(이터레이터)를 \n리턴값으로 내준다. \n따라서 GBRT 학습이 종료된 후 해당 반복자를 이용하여 최적의 의사결정나무 수를 찾는다.\n이때 사용되는 최적의 기준은 평균제곱오차(MSE)를 사용한다.\n\n아래 코드는 120개의 의사결정나무를 사용한 GBRT 모델을 훈련한 후 \nMSE를 최소화하는 의사결정나무의 수를 찾는다.\n\n\n```python\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\n# 이전 학습 내용을 지우고 새로 훈련하기 위해 훈련 세트 섞기. \n# random_state를 다른 값으로 지정.\nX_train, X_val, y_train, y_val = train_test_split(X, y, random_state=49)\n\n# GBRT 모델 설정 및 훈련\ngbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120, random_state=42)\ngbrt.fit(X_train, y_train)\n\n# staged_predict()에 의해 생성된 반복자를 활용하여\n# 각 단계별 MSE 수집 후 최소값을 갖는 인덱스 확인\nerrors = [mean_squared_error(y_val, y_pred)\n for y_pred in gbrt.staged_predict(X_val)]\nbst_n_estimators = np.argmin(errors) + 1\n\n# 최적의 의사결정나무 수를 이용하여 새로 학습\ngbrt_best = GradientBoostingRegressor(max_depth=2, n_estimators=bst_n_estimators, random_state=42)\ngbrt_best.fit(X_train, y_train)\n```\n\n\n\n\n GradientBoostingRegressor(alpha=0.9, criterion='friedman_mse', init=None,\n learning_rate=0.1, loss='ls', max_depth=2,\n max_features=None, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=56,\n n_iter_no_change=None, presort='auto',\n random_state=42, subsample=1.0, tol=0.0001,\n validation_fraction=0.1, verbose=0, warm_start=False)\n\n\n\n위 결과에 의하면 `n_estimators=56`일 때 MSE가 최소값을 갖는다.\n즉, 56개의 의사결정나무를 사용하면 충분하다는 의미히다.\n이것을 그래프로도 확인할 수 있다.\n\n* 왼편 그래프: MSE 변화 선그래프\n* 오른편 그래프: 최적 모델 그래프\n\n\n```python\n# MSE 최소값 확인\nmin_error = np.min(errors)\n\n# 그래프 그리기 준비\nplt.figure(figsize=(10, 4))\n\n# 왼편 그래프\nplt.subplot(121)\nplt.plot(errors, \"b.-\")\nplt.plot([bst_n_estimators, bst_n_estimators], [0, min_error], \"k--\")\nplt.plot([0, 120], [min_error, min_error], \"k--\")\nplt.plot(bst_n_estimators, min_error, \"ko\")\nplt.text(bst_n_estimators, min_error*1.2, \"Minimum\", ha=\"center\", fontsize=14)\nplt.axis([0, 120, 0, 0.01])\nplt.xlabel(\"Number of trees\")\nplt.ylabel(\"Error\", fontsize=16)\nplt.title(\"Validation error\", fontsize=14)\n\n# 오른편 그래프\nplt.subplot(122)\nplot_predictions([gbrt_best], X, y, axes=[-0.5, 0.5, -0.1, 0.8])\nplt.title(\"Best model (%d trees)\" % bst_n_estimators, fontsize=14)\nplt.ylabel(\"$y$\", fontsize=16, rotation=0)\nplt.xlabel(\"$x_1$\", fontsize=16)\n\nsave_fig(\"early_stopping_gbrt_plot\")\nplt.show()\n```\n\n\n#### `warm_start=True` 하이퍼파라미터 활용\n\n`staged_predict()` 메서드를 이용하면 최적의 모델을 찾은 후 새롭게 학습하는 과정을 거쳐야 한다.\n반면에 `warm_start=True` 옵션을 사용하면 `fit()` 메서드가 호출될 때 \n이전 의사결정나무에서 학습된 결과를 이어 받아 학습을 계속하게 만든다. \n즉, 점진적 학습이 가능해진다. \n\n아래 코드는 `n_estimators` 수를 점진적으로 늘려가면서 MSE가 변하는 추이를 관찰한다.\n그러면서 MSE가 5번 이상 별 변화가 없거나 좋아지지 않으면 실행을 멈춘다. \n\n\n```python\n# n_estimators 파라미터를 지정하지 않은 채로 모델 설정\ngbrt = GradientBoostingRegressor(max_depth=2, warm_start=True, random_state=42)\n\n# MSE 최솟값 보관용\nmin_val_error = float(\"inf\")\n\n# MSE의 변화가 없거나 나빠지는 횟수 측정. 5회까지 기다리기.\nerror_going_up = 0\n\n# n_estimators를 1부터 120까지 실험\nfor n_estimators in range(1, 120):\n # GBRT의 n_estimators 설정 후 학습\n gbrt.n_estimators = n_estimators\n gbrt.fit(X_train, y_train)\n \n # MSE 측정\n y_pred = gbrt.predict(X_val)\n val_error = mean_squared_error(y_val, y_pred)\n \n # MSE가 낮아졌을 경우 최솟값 업데이트.\n # 아니면 5번 정도 기다렸다가 조기 종료할 것.\n if val_error < min_val_error:\n min_val_error = val_error\n error_going_up = 0\n else:\n error_going_up += 1\n if error_going_up == 5:\n break\n```\n\n61개의 의사결정나무에서 멈춘다. \n즉, `n_estimators=56` 일 때부터 MSE가 별로 좋아지지 않았음을 의미하며,\n`staged_predict()` 메서드를 사용한 경우와 거의 동일한 결과이다.\n\n\n```python\nprint(gbrt.n_estimators)\n```\n\n 61\n\n\n### 그레이디언트 부스팅 기타 옵션\n\n#### 확률적 그레이디언트 부스팅\n\nGBRT 모델을 설정할 때 예를 들어 `subsample=0.25` 라고 `subsample` 파라미터를 지정하면\n무작위로 선택된 25%의 훈련 샘플만 이용하여 학습이 이루어진다.\n이런 방식을 **확률적 그레이디언트 부스팅**(stochastic gradient boosting)이라 부른다.\n이 방식을 사용하면 일반적으로 편향은 높아지고, 분산은 낮아진다. \n\n#### `loss` 매개변수 활용\n\nGBRT 모델이 사용하는 손실함수는 $\\ell_2$ 노름과 아이디어가 같은 [least squares](https://ko.wikipedia.org/wiki/최소제곱법)을 사용하며 `loss=ls`로 지정된다.\n만약에 $\\ell_1$ 노름 방식을 사용하려면 `loss=lad`로 지정해야 하며,\n그러면 [least absolute deviation](https://en.wikipedia.org/wiki/Least_absolute_deviations)을\n사용한다.\n기타 방식에 대해서는 [sklearn: GradientBoostingRegressor 문서](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html)를\n참조한다.\n\n### XGBoost 사용법 소개\n\n**XGBoost**는 익스트림 그레이디언트 부스팅(extreme gradient boosting)의 약자이며,\n그레이디언트 부스팅 기법을 최적화한 기법이다. \n매우 빠르며, 확장성과 이식성이 좋아서 머신러닝 경연대회 참가자들에게 애용된다. \n\nXGBost의 API는 사이킷런의 API와 유사하게 작동한다.\n기본 설정 파라미터는\n[핵심 XGBoost 문서](https://xgboost.readthedocs.io/en/latest/python/python_api.html)에서 \n확인할 수 있다.\n하지만 사이킷런과 별개로 추가 설치되어야 한다.\n설치방법은\n[XGBoost 설치 안내](https://xgboost.readthedocs.io/en/latest/build.html)를 \n참조한다.\n\n아래 코드는 `xgboost` 모듈의 설치여부를 파악한다.\n\n\n```python\ntry:\n import xgboost\nexcept ImportError as ex:\n print(\"Error: the xgboost library is not installed.\")\n xgboost = None\n```\n\n`XGBoostRegressor` 모델 학습은 다음과 같이 설정한다.\n\n\n```python\nif xgboost is not None:\n xgb_reg = xgboost.XGBRegressor(random_state=42)\n xgb_reg.fit(X_train, y_train)\n y_pred = xgb_reg.predict(X_val)\n \n # 평균 제곱근 오차(RMSE) 계산\n val_error = mean_squared_error(y_val, y_pred)\n print(\"\\nValidation MSE:\", val_error) \n```\n\n [15:22:34] WARNING: /home/conda/feedstock_root/build_artifacts/xgboost_1572314959925/work/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n \n Validation MSE: 0.0028512559726563943\n\n\n조기 종료 옵션을 활용할 수 있다.\n\n* `early_stopping_rounds=2`: 2번의 학습 단계에서 평균제곱근오차(RMSE)가\n 향상되지 않으면 학습을 멈춘다는 의미임.\n 이 옵션을 사용하면 `best_score`, `best_iteration`, `best_ntree_limit` \n 등의 추가 속성을 이용할 수 있다. \n \n아래 코드를 실행하면 34번째 학습에서 멈추며 `best_iteration`이 32라고 알려준다.\n\n\n```python\nif xgboost is not None:\n xgb_reg.fit(X_train, y_train,\n eval_set=[(X_val, y_val)], early_stopping_rounds=2)\n y_pred = xgb_reg.predict(X_val)\n val_error = mean_squared_error(y_val, y_pred)\n\n print(\"\\nValidation MSE:\", val_error) \n```\n\n [15:22:35] WARNING: /home/conda/feedstock_root/build_artifacts/xgboost_1572314959925/work/src/objective/regression_obj.cu:152: reg:linear is now deprecated in favor of reg:squarederror.\n [0]\tvalidation_0-rmse:0.286719\n Will train until validation_0-rmse hasn't improved in 2 rounds.\n [1]\tvalidation_0-rmse:0.258221\n [2]\tvalidation_0-rmse:0.232634\n [3]\tvalidation_0-rmse:0.210526\n [4]\tvalidation_0-rmse:0.190232\n [5]\tvalidation_0-rmse:0.172196\n [6]\tvalidation_0-rmse:0.156394\n [7]\tvalidation_0-rmse:0.142241\n [8]\tvalidation_0-rmse:0.129789\n [9]\tvalidation_0-rmse:0.118752\n [10]\tvalidation_0-rmse:0.108388\n [11]\tvalidation_0-rmse:0.100155\n [12]\tvalidation_0-rmse:0.09208\n [13]\tvalidation_0-rmse:0.084791\n [14]\tvalidation_0-rmse:0.078699\n [15]\tvalidation_0-rmse:0.073248\n [16]\tvalidation_0-rmse:0.069391\n [17]\tvalidation_0-rmse:0.066277\n [18]\tvalidation_0-rmse:0.063458\n [19]\tvalidation_0-rmse:0.060326\n [20]\tvalidation_0-rmse:0.0578\n [21]\tvalidation_0-rmse:0.055643\n [22]\tvalidation_0-rmse:0.053943\n [23]\tvalidation_0-rmse:0.053138\n [24]\tvalidation_0-rmse:0.052415\n [25]\tvalidation_0-rmse:0.051821\n [26]\tvalidation_0-rmse:0.051226\n [27]\tvalidation_0-rmse:0.051135\n [28]\tvalidation_0-rmse:0.05091\n [29]\tvalidation_0-rmse:0.050893\n [30]\tvalidation_0-rmse:0.050725\n [31]\tvalidation_0-rmse:0.050471\n [32]\tvalidation_0-rmse:0.050285\n [33]\tvalidation_0-rmse:0.050492\n [34]\tvalidation_0-rmse:0.050348\n Stopping. Best iteration:\n [32]\tvalidation_0-rmse:0.050285\n \n \n Validation MSE: 0.002528626115371327\n\n\n다음 두 코드는 XGBoost와 GBRT와의 속도 차이를 보여준다.\n결과적으로 XGBoost 모델이 세 배 이상 빠르다.\n\n* `XGBRegressor`에 사용된 `silent=True` 파라미터는\n 학습과정을 굳이 보여주지 않도록 하기위해 사용된다.\n\n\n```python\n%timeit xgboost.XGBRegressor(silent=True).fit(X_train, y_train) if xgboost is not None else None\n```\n\n 3.18 ms ± 22.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\n\n```python\n%timeit GradientBoostingRegressor().fit(X_train, y_train)\n```\n\n 12.4 ms ± 106 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\n\n## 핵심 5: 스태킹\n\n차후 설명 추가!\n\n# Exercise solutions\n\n## 1. to 7.\n\nSee Appendix A.\n\n## 8. Voting Classifier\n\nExercise: _Load the MNIST data and split it into a training set, a validation set, and a test set (e.g., use 50,000 instances for training, 10,000 for validation, and 10,000 for testing)._\n\nThe MNIST dataset was loaded earlier.\n\n\n```python\nfrom sklearn.model_selection import train_test_split\n```\n\n\n```python\nX_train_val, X_test, y_train_val, y_test = train_test_split(\n mnist.data, mnist.target, test_size=10000, random_state=42)\nX_train, X_val, y_train, y_val = train_test_split(\n X_train_val, y_train_val, test_size=10000, random_state=42)\n```\n\nExercise: _Then train various classifiers, such as a Random Forest classifier, an Extra-Trees classifier, and an SVM._\n\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.neural_network import MLPClassifier\n```\n\n\n```python\nrandom_forest_clf = RandomForestClassifier(n_estimators=100, random_state=42)\nextra_trees_clf = ExtraTreesClassifier(n_estimators=100, random_state=42)\nsvm_clf = LinearSVC(random_state=42)\nmlp_clf = MLPClassifier(random_state=42)\n```\n\n\n```python\nestimators = [random_forest_clf, extra_trees_clf, svm_clf, mlp_clf]\nfor estimator in estimators:\n print(\"Training the\", estimator)\n estimator.fit(X_train, y_train)\n```\n\n Training the RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False)\n Training the ExtraTreesClassifier(bootstrap=False, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False)\n Training the LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,\n intercept_scaling=1, loss='squared_hinge', max_iter=1000,\n multi_class='ovr', penalty='l2', random_state=42, tol=0.0001,\n verbose=0)\n\n\n /opt/conda/envs/tf2/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n\n\n Training the MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,\n beta_2=0.999, early_stopping=False, epsilon=1e-08,\n hidden_layer_sizes=(100,), learning_rate='constant',\n learning_rate_init=0.001, max_iter=200, momentum=0.9,\n n_iter_no_change=10, nesterovs_momentum=True, power_t=0.5,\n random_state=42, shuffle=True, solver='adam', tol=0.0001,\n validation_fraction=0.1, verbose=False, warm_start=False)\n\n\n\n```python\n[estimator.score(X_val, y_val) for estimator in estimators]\n```\n\n\n\n\n [0.9692, 0.9715, 0.8397, 0.9602]\n\n\n\nThe linear SVM is far outperformed by the other classifiers. However, let's keep it for now since it may improve the voting classifier's performance.\n\nExercise: _Next, try to combine them into an ensemble that outperforms them all on the validation set, using a soft or hard voting classifier._\n\n\n```python\nfrom sklearn.ensemble import VotingClassifier\n```\n\n\n```python\nnamed_estimators = [\n (\"random_forest_clf\", random_forest_clf),\n (\"extra_trees_clf\", extra_trees_clf),\n (\"svm_clf\", svm_clf),\n (\"mlp_clf\", mlp_clf),\n]\n```\n\n\n```python\nvoting_clf = VotingClassifier(named_estimators)\n```\n\n\n```python\nvoting_clf.fit(X_train, y_train)\n```\n\n /opt/conda/envs/tf2/lib/python3.7/site-packages/sklearn/svm/base.py:929: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.\n \"the number of iterations.\", ConvergenceWarning)\n\n\n\n\n\n VotingClassifier(estimators=[('random_forest_clf',\n RandomForestClassifier(bootstrap=True,\n class_weight=None,\n criterion='gini',\n max_depth=None,\n max_features='auto',\n max_leaf_nodes=None,\n min_impurity_decrease=0.0,\n min_impurity_split=None,\n min_samples_leaf=1,\n min_samples_split=2,\n min_weight_fraction_leaf=0.0,\n n_estimators=100,\n n_jobs=None,\n oob_score=False,\n random_st...\n beta_2=0.999, early_stopping=False,\n epsilon=1e-08,\n hidden_layer_sizes=(100,),\n learning_rate='constant',\n learning_rate_init=0.001,\n max_iter=200, momentum=0.9,\n n_iter_no_change=10,\n nesterovs_momentum=True,\n power_t=0.5, random_state=42,\n shuffle=True, solver='adam',\n tol=0.0001, validation_fraction=0.1,\n verbose=False, warm_start=False))],\n flatten_transform=True, n_jobs=None, voting='hard',\n weights=None)\n\n\n\n\n```python\nvoting_clf.score(X_val, y_val)\n```\n\n\n\n\n 0.9709\n\n\n\n\n```python\n[estimator.score(X_val, y_val) for estimator in voting_clf.estimators_]\n```\n\n\n\n\n [0.9692, 0.9715, 0.8397, 0.9602]\n\n\n\nLet's remove the SVM to see if performance improves. It is possible to remove an estimator by setting it to `None` using `set_params()` like this:\n\n\n```python\nvoting_clf.set_params(svm_clf=None)\n```\n\n\n\n\n VotingClassifier(estimators=[('random_forest_clf',\n RandomForestClassifier(bootstrap=True,\n class_weight=None,\n criterion='gini',\n max_depth=None,\n max_features='auto',\n max_leaf_nodes=None,\n min_impurity_decrease=0.0,\n min_impurity_split=None,\n min_samples_leaf=1,\n min_samples_split=2,\n min_weight_fraction_leaf=0.0,\n n_estimators=100,\n n_jobs=None,\n oob_score=False,\n random_st...\n beta_2=0.999, early_stopping=False,\n epsilon=1e-08,\n hidden_layer_sizes=(100,),\n learning_rate='constant',\n learning_rate_init=0.001,\n max_iter=200, momentum=0.9,\n n_iter_no_change=10,\n nesterovs_momentum=True,\n power_t=0.5, random_state=42,\n shuffle=True, solver='adam',\n tol=0.0001, validation_fraction=0.1,\n verbose=False, warm_start=False))],\n flatten_transform=True, n_jobs=None, voting='hard',\n weights=None)\n\n\n\nThis updated the list of estimators:\n\n\n```python\nvoting_clf.estimators\n```\n\n\n\n\n [('random_forest_clf',\n RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False)),\n ('extra_trees_clf',\n ExtraTreesClassifier(bootstrap=False, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False)),\n ('svm_clf', None),\n ('mlp_clf',\n MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,\n beta_2=0.999, early_stopping=False, epsilon=1e-08,\n hidden_layer_sizes=(100,), learning_rate='constant',\n learning_rate_init=0.001, max_iter=200, momentum=0.9,\n n_iter_no_change=10, nesterovs_momentum=True, power_t=0.5,\n random_state=42, shuffle=True, solver='adam', tol=0.0001,\n validation_fraction=0.1, verbose=False, warm_start=False))]\n\n\n\nHowever, it did not update the list of _trained_ estimators:\n\n\n```python\nvoting_clf.estimators_\n```\n\n\n\n\n [RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False),\n ExtraTreesClassifier(bootstrap=False, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=100,\n n_jobs=None, oob_score=False, random_state=42, verbose=0,\n warm_start=False),\n LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,\n intercept_scaling=1, loss='squared_hinge', max_iter=1000,\n multi_class='ovr', penalty='l2', random_state=42, tol=0.0001,\n verbose=0),\n MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,\n beta_2=0.999, early_stopping=False, epsilon=1e-08,\n hidden_layer_sizes=(100,), learning_rate='constant',\n learning_rate_init=0.001, max_iter=200, momentum=0.9,\n n_iter_no_change=10, nesterovs_momentum=True, power_t=0.5,\n random_state=42, shuffle=True, solver='adam', tol=0.0001,\n validation_fraction=0.1, verbose=False, warm_start=False)]\n\n\n\nSo we can either fit the `VotingClassifier` again, or just remove the SVM from the list of trained estimators:\n\n\n```python\ndel voting_clf.estimators_[2]\n```\n\nNow let's evaluate the `VotingClassifier` again:\n\n\n```python\nvoting_clf.score(X_val, y_val)\n```\n\n\n\n\n 0.9728\n\n\n\nA bit better! The SVM was hurting performance. Now let's try using a soft voting classifier. We do not actually need to retrain the classifier, we can just set `voting` to `\"soft\"`:\n\n\n```python\nvoting_clf.voting = \"soft\"\n```\n\n\n```python\nvoting_clf.score(X_val, y_val)\n```\n\n\n\n\n 0.9677\n\n\n\nNope, hard voting wins in this case.\n\n_Once you have found one, try it on the test set. How much better does it perform compared to the individual classifiers?_\n\n\n```python\nvoting_clf.voting = \"hard\"\nvoting_clf.score(X_test, y_test)\n```\n\n\n\n\n 0.9708\n\n\n\n\n```python\n[estimator.score(X_test, y_test) for estimator in voting_clf.estimators_]\n```\n\n\n\n\n [0.9645, 0.9691, 0.9589]\n\n\n\nThe voting classifier only very slightly reduced the error rate of the best model in this case.\n\n## 9. Stacking Ensemble\n\nExercise: _Run the individual classifiers from the previous exercise to make predictions on the validation set, and create a new training set with the resulting predictions: each training instance is a vector containing the set of predictions from all your classifiers for an image, and the target is the image's class. Train a classifier on this new training set._\n\n\n```python\nX_val_predictions = np.empty((len(X_val), len(estimators)), dtype=np.float32)\n\nfor index, estimator in enumerate(estimators):\n X_val_predictions[:, index] = estimator.predict(X_val)\n```\n\n\n```python\nX_val_predictions\n```\n\n\n\n\n array([[5., 5., 8., 5.],\n [8., 8., 8., 8.],\n [2., 2., 2., 2.],\n ...,\n [7., 7., 7., 7.],\n [6., 6., 6., 6.],\n [7., 7., 7., 7.]], dtype=float32)\n\n\n\n\n```python\nrnd_forest_blender = RandomForestClassifier(n_estimators=200, oob_score=True, random_state=42)\nrnd_forest_blender.fit(X_val_predictions, y_val)\n```\n\n\n\n\n RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n max_depth=None, max_features='auto', max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=2,\n min_weight_fraction_leaf=0.0, n_estimators=200,\n n_jobs=None, oob_score=True, random_state=42, verbose=0,\n warm_start=False)\n\n\n\n\n```python\nrnd_forest_blender.oob_score_\n```\n\n\n\n\n 0.9695\n\n\n\nYou could fine-tune this blender or try other types of blenders (e.g., an `MLPClassifier`), then select the best one using cross-validation, as always.\n\nExercise: _Congratulations, you have just trained a blender, and together with the classifiers they form a stacking ensemble! Now let's evaluate the ensemble on the test set. For each image in the test set, make predictions with all your classifiers, then feed the predictions to the blender to get the ensemble's predictions. How does it compare to the voting classifier you trained earlier?_\n\n\n```python\nX_test_predictions = np.empty((len(X_test), len(estimators)), dtype=np.float32)\n\nfor index, estimator in enumerate(estimators):\n X_test_predictions[:, index] = estimator.predict(X_test)\n```\n\n\n```python\ny_pred = rnd_forest_blender.predict(X_test_predictions)\n```\n\n\n```python\nfrom sklearn.metrics import accuracy_score\n```\n\n\n```python\naccuracy_score(y_test, y_pred)\n```\n\n\n\n\n 0.9654\n\n\n\nThis stacking ensemble does not perform as well as the voting classifier we trained earlier, it's not quite as good as the best individual classifier.\n\n\n```python\n\n```\n", "meta": {"hexsha": "fff79e5da707e42572eac267b990d6d9a7dbc230", "size": 549949, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/07_ensemble_learning_and_random_forests.ipynb", "max_stars_repo_name": "Park-taenam/handson-ml2", "max_stars_repo_head_hexsha": "b55f07290b5a1a368fad120453d03cdacb2c0de9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-07-08T09:27:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T09:27:12.000Z", "max_issues_repo_path": "notebooks/07_ensemble_learning_and_random_forests.ipynb", "max_issues_repo_name": "Park-taenam/handson-ml2", "max_issues_repo_head_hexsha": "b55f07290b5a1a368fad120453d03cdacb2c0de9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/07_ensemble_learning_and_random_forests.ipynb", "max_forks_repo_name": "Park-taenam/handson-ml2", "max_forks_repo_head_hexsha": "b55f07290b5a1a368fad120453d03cdacb2c0de9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2021-09-25T05:37:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T17:20:17.000Z", "avg_line_length": 154.9152112676, "max_line_length": 107068, "alphanum_fraction": 0.882574566, "converted": true, "num_tokens": 25836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.301999350106371}} {"text": "### Part 3: City district object\n\nThe city district object of pycity is an inheritance of the uesgraph object of uesgraphs package, which itself is an inheritance of networkx.Graph.\n\nIf you are not familiar with networkx.Graph or uesgraph, please go through the uesgraphs tutorial first. \nYou can access it within the uesgraphs package, which is available under:\n[UESGraphs](https://github.com/RWTH-EBC/uesgraphs)\n\nYou can install it locally via pip. Open a console and type:\n'pip install -e your_path_to_uesgraphs' (with your local path to uesgraphs package)\n\nIf you have not installed it, please do so now, because you are going to need it to execute the following lines.\n\n\n```python\nimport pycity_base.classes.timer as Timer\nimport pycity_base.classes.weather as Weather\nimport pycity_base.classes.prices as Prices\nimport pycity_base.classes.environment as Env\n\n# Setting up environment\n# Timestep in seconds\ntimestep = 3600\n\n# Total number of timesteps\ntimesteps_total = int(365 * 24 * 3600 / timestep)\n\n# Generate timer object for environment\ntimer = Timer.Timer(time_discretization=timestep, timesteps_total=timesteps_total, \n timesteps_used_horizon=timesteps_total, timesteps_horizon=timesteps_total)\n# Timer object holds timestep, number of timesteps as well as\n# forecast horizon\n\n# Generate weather object\nweather = Weather.Weather(timer)\n# Weather object holds weather data, such as outdoor temperatures,\n# direct and diffuse radiation\n# Default TRY value is TRY2010_05_Jahr.dat\n# (Test reference year 2010 for region 5 in Germany)\n\n# Generate price object\nprice = Prices.Prices()\n# Holding energy prices and subsidies\n\n# Generate environment object\nenvironment = Env.Environment(timer=timer, weather=weather, prices=price)\n\nprint(environment)\n\n```\n\n \n\n\n\n```python\nimport pycity_base.classes.city_district as CityDistrict\n\n# Generate city district object\ncity_district = CityDistrict.CityDistrict(environment)\n# You can generate a CityDistrict object without handing over the environment. This is done to enable some \n# networkx functions for the citydistrict object. However, you should add the environment either way,\n# because you will not be able to work with your district later on, if the environment pointer is missing!\n# Thus, we recommmend to add the environment pointer directly!\n\nprint(city_district)\n```\n\n \n\n\nNow we will generate 3 single family buildings with loads and add them to the city district object\n\n\n```python\nimport random\nimport sympy.geometry.point as point\n\nimport pycity_base.classes.demand.domestic_hot_water as DomesticHotWater\nimport pycity_base.classes.demand.electrical_demand as ElectricalDemand\nimport pycity_base.classes.demand.space_heating as SpaceHeating\n\nimport pycity_base.classes.demand.apartment as Apartment\nimport pycity_base.classes.building as Building\n\n\n# Loop to generate building objects\nfor i in range(3):\n \n # Generate space heating object\n heat_demand = SpaceHeating.SpaceHeating(environment,\n method=1, # Standard load profile\n living_area=150,\n specific_demand=100)\n\n # Generate electrical demand object\n el_demand = ElectricalDemand.ElectricalDemand(environment,\n method=1, # Standard load profile\n annual_demand=3000)\n\n # Generate domestic hot water demand object\n dhw_annex42 = DomesticHotWater.DomesticHotWater(environment,\n t_flow=60,\n thermal=True,\n method=1, # Annex 42\n daily_consumption=70,\n supply_temperature=25)\n \n # Generate apartment and add load objects\n apartment = Apartment.Apartment(environment)\n apartment.addEntity(heat_demand)\n apartment.addMultipleEntities([el_demand, dhw_annex42])\n \n # Generate building and add apartment\n building = Building.Building(environment)\n building.addEntity(entity=apartment)\n \n # Generate sympy point positions (with random coordinates)\n position = point.Point(random.randint(0, 100), random.randint(0, 100))\n \n # Add buildings to city district\n city_district.addEntity(entity=building, position=position)\n\nprint('Number of building entities:')\nprint(city_district.get_nb_of_building_entities())\n```\n\n Number of building entities:\n 3\n\n\nYou can also add pv- or wind farms to the city district:\n\n\n```python\nimport pycity_base.classes.supply.photovoltaic as PV\n\n# Generate PV field within city district\npv = PV.PV(environment=environment, method=0, area=20, eta_noct=0.15)\n\n# Generate sympy point positions\nposition_1 = point.Point(0, 0)\n\n# Add PV fields to city district\ncity_district.addEntity(entity=pv, position=position_1)\n\nprint('Number of PV farms:')\nprint(city_district.get_nb_of_entities(entity_name='pv'))\n```\n\n Number of PV farms:\n 1\n\n\nCAUTION: If you add pv- or windfarms to the city district, the number of buildings is not the same as tne length of nodelist_building. The reason is, that pv- and windfarms are also handled as building nodes within uesgraph. If you deal with building nodes, you should also check the _kind of entity within the node!\n\n\n```python\nassert len(city_district.nodelist_building) == city_district.get_nb_of_building_entities()+1,\\\n 'Be aware that PV units and wind energy converters are also handled as building nodes in uesgraph!'\n```\n\n\n```python\n# Get complete node information of city district (possible, because city district is a graph)\n\nprint('Node information:')\nprint(city_district.nodes(data=True))\nprint()\n\nprint('Node numbers only:')\nprint(city_district.nodes())\n```\n\n Node information:\n [(1001, {'name': 1001, 'node_type': 'building', 'position': Point2D(87, 32), 'is_supply_heating': False, 'is_supply_cooling': False, 'is_supply_electricity': False, 'is_supply_gas': False, 'is_supply_other': False, 'entity': }), (1002, {'name': 1002, 'node_type': 'building', 'position': Point2D(71, 78), 'is_supply_heating': False, 'is_supply_cooling': False, 'is_supply_electricity': False, 'is_supply_gas': False, 'is_supply_other': False, 'entity': }), (1003, {'name': 1003, 'node_type': 'building', 'position': Point2D(38, 62), 'is_supply_heating': False, 'is_supply_cooling': False, 'is_supply_electricity': False, 'is_supply_gas': False, 'is_supply_other': False, 'entity': }), (1004, {'name': 1004, 'node_type': 'building', 'position': Point2D(0, 0), 'is_supply_heating': False, 'is_supply_cooling': False, 'is_supply_electricity': True, 'is_supply_gas': False, 'is_supply_other': False, 'entity': })]\n \n Node numbers only:\n [1001, 1002, 1003, 1004]\n\n\nCityDistrict holds further methods. Some are shown below:\n\n\n```python\nprint('Get number of building objects:')\nprint(city_district.get_nb_of_building_entities())\nprint()\n\nprint('Get list of nodes with building objects:')\nprint(city_district.get_list_build_entity_node_ids())\n```\n\n Get number of building objects:\n 3\n \n Get list of nodes with building objects:\n [1001, 1002, 1003]\n\n\nIt is also possible to extract aggregated load curves of all building objects\n\n\n```python\naggr_load_curve = city_district.get_aggr_space_heating_power_curve()\n\nprint(aggr_load_curve)\n```\n\n [5682.09607927 5830.32467264 5978.55326602 ... 7451.04147065 5086.44155188\n 3708.50922512]\n\n\n\n```python\n\n```\n", "meta": {"hexsha": "e6148cab646765f72bb127249b467240f514e493", "size": 11955, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "pycity_base/examples/tutorials/tutorial_pycity_base_2.ipynb", "max_stars_repo_name": "RWTH-EBC/pyCity", "max_stars_repo_head_hexsha": "88c832aa647ceb8889abd8f851b7349c3366e30a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11, "max_stars_repo_stars_event_min_datetime": "2019-08-13T15:18:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T08:03:02.000Z", "max_issues_repo_path": "pycity_base/examples/tutorials/tutorial_pycity_base_2.ipynb", "max_issues_repo_name": "RWTH-EBC/pyCity", "max_issues_repo_head_hexsha": "88c832aa647ceb8889abd8f851b7349c3366e30a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29, "max_issues_repo_issues_event_min_datetime": "2019-06-15T20:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-27T16:04:30.000Z", "max_forks_repo_path": "pycity_base/examples/tutorials/tutorial_pycity_base_2.ipynb", "max_forks_repo_name": "RWTH-EBC/pyCity", "max_forks_repo_head_hexsha": "88c832aa647ceb8889abd8f851b7349c3366e30a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0598290598, "max_line_length": 1263, "alphanum_fraction": 0.5950648264, "converted": true, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3016898078197093}} {"text": "\n\n\n# Start-to-Finish Example: `GiRaFFE_NRPy` 3D tests\n\n### Author: Patrick Nelson\n\n### Adapted from [Start-to-Finish Example: Head-On Black Hole Collision](../Tutorial-Start_to_Finish-BSSNCurvilinear-Two_BHs_Collide.ipynb)\n\n## This module implements a basic GRFFE code to evolve one-dimensional GRFFE waves.\n\n### NRPy+ Source Code for this module: \n* [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Exact_Wald.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Exact_Wald.py) [\\[**tutorial**\\]](Tutorial-GiRaFFEfood_NRPy_Exact_Wald.ipynb) Generates Exact Wald initial data\n* [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_Aligned_Rotator.py) [\\[**tutorial**\\]](Tutorial-GiRaFFEfood_NRPy_Aligned_Rotator.ipynb) Generates Aligned Rotator initial data\n* [GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_1D_tests.py](../../edit/in_progress/GiRaFFEfood_NRPy/GiRaFFEfood_NRPy_1D_tests.py) [\\[**tutorial**\\]](Tutorial-GiRaFFEfood_NRPy_1D_tests.ipynb) Generates Alfvén Wave initial data.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Afield_flux.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Afield_flux.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy_staggered-Afield_flux.ipynb) Generates the expressions to find the flux term of the induction equation.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_A2B.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_A2B.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy_staggered-A2B.ipynb) Generates the driver to compute the magnetic field from the vector potential/\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_BCs.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-BCs.ipynb) Generates the code to apply boundary conditions to the vector potential, scalar potential, and three-velocity.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_C2P_P2C.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_C2P_P2C.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-C2P_P2C.ipynb) Generates the conservative-to-primitive and primitive-to-conservative solvers.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_Metric_Face_Values.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_Metric_Face_Values.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-Metric_Face_Values.ipynb) Generates code to interpolate metric gridfunctions to cell faces.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_PPM.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_PPM.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-PPM.ipynb) Genearates code to reconstruct primitive variables on cell faces.\n* [GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Source_Terms.py](../../edit/in_progress/GiRaFFE_NRPy/GiRaFFE_NRPy_staggered_Source_Terms.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy_staggered-Source_Terms.ipynb) Generates the expressions to find the flux term of the Poynting flux evolution equation.\n* [GiRaFFE_NRPy/Stilde_flux.py](../../edit/in_progress/GiRaFFE_NRPy/Stilde_flux.py) [\\[**tutorial**\\]](Tutorial-GiRaFFE_NRPy-Stilde_flux.ipynb) Generates the expressions to find the flux term of the Poynting flux evolution equation.\n* [../GRFFE/equations.py](../../edit/GRFFE/equations.py) [\\[**tutorial**\\]](../Tutorial-GRFFE_Equations-Cartesian.ipynb) Generates code necessary to compute the source terms.\n* [../GRHD/equations.py](../../edit/GRHD/equations.py) [\\[**tutorial**\\]](../Tutorial-GRHD_Equations-Cartesian.ipynb) Generates code necessary to compute the source terms.\n\nHere we use NRPy+ to generate the C source code necessary to set up initial data for an Exact Wald (see [the original GiRaFFE paper](https://arxiv.org/pdf/1704.00599.pdf)). Then we use it to generate the RHS expressions for [Method of Lines](https://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html) time integration based on the [explicit Runge-Kutta fourth-order scheme](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods) (RK4).\n\n\n\n# Table of Contents\n$$\\label{toc}$$\n\nThis notebook is organized as follows\n\n1. [Step 1](#initializenrpy): Set core NRPy+ parameters for numerical grids\n1. [Step 2](#grffe): Output C code for GRFFE evolution\n 1. [Step 2.a](#mol): Output macros for Method of Lines timestepping\n1. [Step 3](#gf_id): Import `GiRaFFEfood_NRPy` initial data modules\n1. [Step 4](#cparams): Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h`\n1. [Step 5](#mainc): `GiRaFFE_NRPy_standalone.c`: The Main C Code\n\n\n\n# Step 1: Set up core functions and parameters for solving GRFFE equations \\[Back to [top](#toc)\\]\n$$\\label{setup}$$\n\n\n\n```python\nimport shutil, os, sys # Standard Python modules for multiplatform OS-level functions\n# First, we'll add the parent directory to the list of directories Python will check for modules.\nnrpy_dir_path = os.path.join(\"..\")\nif nrpy_dir_path not in sys.path:\n sys.path.append(nrpy_dir_path)\n\n# Step P1: Import needed NRPy+ core modules:\nfrom outputC import outCfunction, lhrh # NRPy+: Core C code output module\nimport sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends\nimport finite_difference as fin # NRPy+: Finite difference C code generation module\nimport NRPy_param_funcs as par # NRPy+: Parameter interface\nimport grid as gri # NRPy+: Functions having to do with numerical grids\nimport indexedexp as ixp # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support\nimport cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\n\n# Step P2: Create C code output directory:\nCcodesdir = os.path.join(\"GiRaFFE_staggered_standalone_Ccodes/\")\n# First remove C code output directory if it exists\n# Courtesy https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty\n# !rm -r ScalarWaveCurvilinear_Playground_Ccodes\nshutil.rmtree(Ccodesdir, ignore_errors=True)\n# Then create a fresh directory\ncmd.mkdir(Ccodesdir)\n\n# Step P3: Create executable output directory:\noutdir = os.path.join(Ccodesdir,\"output/\")\ncmd.mkdir(outdir)\n\n# Step P5: Set timestepping algorithm (we adopt the Method of Lines)\nREAL = \"double\" # Best to use double here.\ndefault_CFL_FACTOR= 0.5 # (GETS OVERWRITTEN WHEN EXECUTED.) In pure axisymmetry (symmetry_axes = 2 below) 1.0 works fine. Otherwise 0.5 or lower.\n\n# Step P6: Set the finite differencing order to 2.\npar.set_parval_from_str(\"finite_difference::FD_CENTDERIVS_ORDER\",2)\n\nthismodule = \"Start_to_Finish-GiRaFFE_NRPy-1D_tests\"\nTINYDOUBLE = par.Cparameters(\"REAL\", thismodule, \"TINYDOUBLE\", 1e-100)\n\nimport GiRaFFE_NRPy.GiRaFFE_NRPy_Main_Driver_staggered as md\n# par.set_paramsvals_value(\"GiRaFFE_NRPy.GiRaFFE_NRPy_C2P_P2C::enforce_speed_limit_StildeD = False\")\npar.set_paramsvals_value(\"GiRaFFE_NRPy.GiRaFFE_NRPy_C2P_P2C::enforce_current_sheet_prescription = False\")\n```\n\n\n\n# Step 2: Output C code for GRFFE evolution \\[Back to [top](#toc)\\]\n$$\\label{grffe}$$\n\nWe will first write the C codes needed for GRFFE evolution. We have already written a module to generate all these codes and call the functions in the appropriate order, so we will import that here. We will take the slightly unusual step of doing this before we generate the initial data functions because the main driver module will register all the gridfunctions we need. It will also generate functions that, in addition to their normal spot in the MoL timestepping, will need to be called during the initial data step to make sure all the variables are appropriately filled in. \n\nAll of this is handled with a single call to `GiRaFFE_NRPy_Main_Driver_generate_all()`, which will register gridfunctions, write all the C code kernels, and write the C code functions to call those.\n\n\n```python\nmd.GiRaFFE_NRPy_Main_Driver_generate_all(Ccodesdir)\n```\n\n Output C function calculate_StildeD0_source_term() to file GiRaFFE_staggered_standalone_Ccodes/RHSs/calculate_StildeD0_source_term.h\n Output C function calculate_StildeD1_source_term() to file GiRaFFE_staggered_standalone_Ccodes/RHSs/calculate_StildeD1_source_term.h\n Output C function calculate_StildeD2_source_term() to file GiRaFFE_staggered_standalone_Ccodes/RHSs/calculate_StildeD2_source_term.h\n Output C function calculate_Stilde_rhsD() to file GiRaFFE_staggered_standalone_Ccodes/RHSs/calculate_Stilde_rhsD.h\n Output C function GiRaFFE_NRPy_cons_to_prims() to file GiRaFFE_staggered_standalone_Ccodes/C2P/GiRaFFE_NRPy_cons_to_prims.h\n Output C function GiRaFFE_NRPy_prims_to_cons() to file GiRaFFE_staggered_standalone_Ccodes/C2P/GiRaFFE_NRPy_prims_to_cons.h\n Output C function Workaround_ADM_to_BSSN() to file GiRaFFE_staggered_standalone_Ccodes/Workaround_ADM_to_BSSN.h\n Output C function Workaround_BSSN_to_ADM() to file GiRaFFE_staggered_standalone_Ccodes/Workaround_BSSN_to_ADM.h\n\n\n\n\n## Step 2.a: Output macros for Method of Lines timestepping \\[Back to [top](#toc)\\]\n$$\\label{mol}$$\n\nNow, we generate the code to implement the method of lines using the fourth-order Runge-Kutta algorithm.\n\n\n```python\nRK_method = \"RK4\"\n\n# Step 3: Generate Runge-Kutta-based (RK-based) timestepping code.\n# As described above the Table of Contents, this is a 3-step process:\n# 3.A: Evaluate RHSs (RHS_string)\n# 3.B: Apply boundary conditions (post_RHS_string, pt 1)\nimport MoLtimestepping.C_Code_Generation as MoL\nfrom MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict\nRK_order = Butcher_dict[RK_method][1]\ncmd.mkdir(os.path.join(Ccodesdir,\"MoLtimestepping/\"))\nMoL.MoL_C_Code_Generation(RK_method,\n RHS_string = \"\"\"\nGiRaFFE_NRPy_RHSs(¶ms,auxevol_gfs,RK_INPUT_GFS,RK_OUTPUT_GFS);\"\"\",\n post_RHS_string = \"\"\"\nGiRaFFE_NRPy_post_step(¶ms,xx,auxevol_gfs,RK_OUTPUT_GFS,n+1);\\n\"\"\",\n outdir = os.path.join(Ccodesdir,\"MoLtimestepping/\"))\n```\n\n\n\n# Step 3: Import `GiRaFFEfood_NRPy` initial data modules \\[Back to [top](#toc)\\]\n$$\\label{gf_id}$$\n\nWith the preliminaries out of the way, we will write the C functions to set up initial data. There are two categories of initial data that must be set: the spacetime metric variables, and the GRFFE plasma variables. We will set up the spacetime first.\n\n\n```python\n# There are several initial data routines we need to test. We'll control which one we use with a string option\ninitial_data = \"ExactWald\" # Valid options: \"ExactWald\", \"AlignedRotator\"\nspacetime = \"ShiftedKerrSchild\" # Valid options: \"ShiftedKerrSchild\", \"flat\"\n\nif spacetime == \"ShiftedKerrSchild\":\n # Exact Wald is more complicated. We'll need the Shifted Kerr Schild metric in Cartesian coordinates.\n import BSSN.ShiftedKerrSchild as sks\n sks.ShiftedKerrSchild(True)\n import reference_metric as rfm\n par.set_parval_from_str(\"reference_metric::CoordSystem\",\"Cartesian\")\n rfm.reference_metric()\n # Use the Jacobian matrix to transform the vectors to Cartesian coordinates.\n drrefmetric__dx_0UDmatrix = sp.Matrix([[sp.diff(rfm.xxSph[0],rfm.xx[0]), sp.diff(rfm.xxSph[0],rfm.xx[1]), sp.diff(rfm.xxSph[0],rfm.xx[2])],\n [sp.diff(rfm.xxSph[1],rfm.xx[0]), sp.diff(rfm.xxSph[1],rfm.xx[1]), sp.diff(rfm.xxSph[1],rfm.xx[2])],\n [sp.diff(rfm.xxSph[2],rfm.xx[0]), sp.diff(rfm.xxSph[2],rfm.xx[1]), sp.diff(rfm.xxSph[2],rfm.xx[2])]])\n dx__drrefmetric_0UDmatrix = drrefmetric__dx_0UDmatrix.inv()\n gammaDD = ixp.zerorank2()\n for i in range(3):\n for j in range(3):\n for k in range(3):\n for l in range(3):\n gammaDD[i][j] += drrefmetric__dx_0UDmatrix[(k,i)]*drrefmetric__dx_0UDmatrix[(l,j)]*sks.gammaSphDD[k][l].subs(sks.r,rfm.xxSph[0]).subs(sks.th,rfm.xxSph[1])\n\n betaU = ixp.zerorank1()\n for i in range(3):\n for j in range(3):\n betaU[i] += dx__drrefmetric_0UDmatrix[(i,j)]*sks.betaSphU[j].subs(sks.r,rfm.xxSph[0]).subs(sks.th,rfm.xxSph[1])\n alpha = sks.alphaSph.subs(sks.r,rfm.xxSph[0]).subs(sks.th,rfm.xxSph[1])\n\n # Description and options for this initial data\n desc = \"Generate a spinning black hole with Shifted Kerr Schild metric.\"\n loopopts_id =\"AllPoints,Read_xxs\"\n\nelif spacetime == \"flat\":\n gammaDD = ixp.zerorank2(DIM=3)\n for i in range(3):\n for j in range(3):\n if i==j:\n gammaDD[i][j] = sp.sympify(1) # else: leave as zero\n betaU = ixp.zerorank1() # All should be 0\n alpha = sp.sympify(1)\n\n # Description and options for this initial data\n desc = \"Generate a flat spacetime metric.\"\n loopopts_id =\"AllPoints\" # we don't need to read coordinates for flat spacetime.\n\n\n# For testing: Also set inverse metric:\ngammaUU, unused_gammaDET = ixp.symm_matrix_inverter3x3(gammaDD)\n\nname = \"set_initial_spacetime_metric_data\"\nvalues_to_print = [\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD00\"),rhs=gammaDD[0][0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD01\"),rhs=gammaDD[0][1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD02\"),rhs=gammaDD[0][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD11\"),rhs=gammaDD[1][1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD12\"),rhs=gammaDD[1][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaDD22\"),rhs=gammaDD[2][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"betaU0\"),rhs=betaU[0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"betaU1\"),rhs=betaU[1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"betaU2\"),rhs=betaU[2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"alpha\"),rhs=alpha),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaUU00\"),rhs=gammaUU[0][0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaUU01\"),rhs=gammaUU[0][1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaUU02\"),rhs=gammaUU[0][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaUU11\"),rhs=gammaUU[1][1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaUU12\"),rhs=gammaUU[1][2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"gammaUU22\"),rhs=gammaUU[2][2])\n ]\n\noutCfunction(\n outfile = os.path.join(Ccodesdir,name+\".h\"), desc=desc, name=name,\n params =\"const paramstruct *params,REAL *xx[3],REAL *auxevol_gfs\",\n body = fin.FD_outputC(\"returnstring\",values_to_print,params=\"outCverbose=False\").replace(\"IDX4\",\"IDX4S\"),\n loopopts = loopopts_id)\n\n```\n\n Output C function set_initial_spacetime_metric_data() to file GiRaFFE_staggered_standalone_Ccodes/set_initial_spacetime_metric_data.h\n\n\nNow, we will write out the initial data function for the GRFFE variables.\n\n\n```python\nif initial_data==\"AlignedRotator\":\n import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_Aligned_Rotator as gid\n gid.GiRaFFEfood_NRPy_Aligned_Rotator()\n desc = \"Generate aligned rotator initial test data for GiRaFFEfood_NRPy.\"\nelif initial_data==\"ExactWald\":\n import GiRaFFEfood_NRPy.GiRaFFEfood_NRPy_Exact_Wald as gid\n gid.GiRaFFEfood_NRPy_Exact_Wald(gammaDD,sks.M,sks.r0,stagger=True)\n desc = \"Generate exact Wald initial test data for GiRaFFEfood_NRPy.\"\nelse:\n print(\"Unsupported Initial Data string \"+initial_data+\"! Supported ID: AlfvenWave, FastWave, AlignedRotator, or ExactWald\")\n\nname = \"initial_data\"\n\nvalues_to_print = [\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"AD0\"),rhs=gid.AD[0]),\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"AD1\"),rhs=gid.AD[1]),\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"AD2\"),rhs=gid.AD[2]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"ValenciavU0\"),rhs=gid.ValenciavU[0]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"ValenciavU1\"),rhs=gid.ValenciavU[1]),\n lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"ValenciavU2\"),rhs=gid.ValenciavU[2]),\n# lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"BU0\"),rhs=gid.BU[0]),\n# lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"BU1\"),rhs=gid.BU[1]),\n# lhrh(lhs=gri.gfaccess(\"auxevol_gfs\",\"BU2\"),rhs=gid.BU[2]),\n lhrh(lhs=gri.gfaccess(\"out_gfs\",\"psi6Phi\"),rhs=sp.sympify(0))\n ]\n\noutCfunction(\n outfile = os.path.join(Ccodesdir,name+\".h\"), desc=desc, name=name,\n params =\"const paramstruct *params,REAL *xx[3],REAL *auxevol_gfs,REAL *out_gfs\",\n body = fin.FD_outputC(\"returnstring\",values_to_print,params=\"outCverbose=False\").replace(\"IDX4\",\"IDX4S\"),\n loopopts =\"AllPoints,Read_xxs\")\n```\n\n Output C function initial_data() to file GiRaFFE_staggered_standalone_Ccodes/initial_data.h\n\n\n\n\n# Step 4: Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h` \\[Back to [top](#toc)\\]\n$$\\label{cparams}$$\n\nBased on declared NRPy+ Cparameters, first we generate `declare_Cparameters_struct.h`, `set_Cparameters_default.h`, and `set_Cparameters[-SIMD].h`.\n\nThen we output `free_parameters.h`, which sets initial data parameters, as well as grid domain & reference metric parameters, applying `domain_size` and `sinh_width`/`SymTP_bScale` (if applicable) as set above\n\n\n```python\n# Step 3.e: Output C codes needed for declaring and setting Cparameters; also set free_parameters.h\n# Step 3.e.i: Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h\npar.generate_Cparameters_Ccodes(os.path.join(Ccodesdir))\n\n# Step 3.e.ii: Set free_parameters.h\nwith open(os.path.join(Ccodesdir,\"free_parameters.h\"),\"w\") as file:\n file.write(\"\"\"// Override parameter defaults with values based on command line arguments and NGHOSTS.\nparams.Nxx0 = atoi(argv[1]);\nparams.Nxx1 = atoi(argv[2]);\nparams.Nxx2 = atoi(argv[3]);\nparams.Nxx_plus_2NGHOSTS0 = params.Nxx0 + 2*NGHOSTS;\nparams.Nxx_plus_2NGHOSTS1 = params.Nxx1 + 2*NGHOSTS;\nparams.Nxx_plus_2NGHOSTS2 = params.Nxx2 + 2*NGHOSTS;\n// Step 0d: Set up space and time coordinates\n// Step 0d.i: Declare \\Delta x^i=dxx{0,1,2} and invdxx{0,1,2}, as well as xxmin[3] and xxmax[3]:\nconst REAL xxmin[3] = {-1.5,-1.5,-1.5};\nconst REAL xxmax[3] = { 1.5, 1.5, 1.5};\n\nparams.dxx0 = (xxmax[0] - xxmin[0]) / ((REAL)params.Nxx0+1);\nparams.dxx1 = (xxmax[1] - xxmin[1]) / ((REAL)params.Nxx1+1);\nparams.dxx2 = (xxmax[2] - xxmin[2]) / ((REAL)params.Nxx2+1);\nprintf(\"dxx0,dxx1,dxx2 = %.15e,%.15e,%.15e\\\\n\",params.dxx0,params.dxx1,params.dxx2);\nparams.invdx0 = 1.0 / params.dxx0;\nparams.invdx1 = 1.0 / params.dxx1;\nparams.invdx2 = 1.0 / params.dxx2;\n\nconst int poison_grids = 1;\n// Standard GRFFE parameters:\nparams.GAMMA_SPEED_LIMIT = 2000.0;\nparams.diss_strength = 4.0;\n\"\"\")\nif initial_data==\"ExactWald\":\n with open(os.path.join(Ccodesdir,\"free_parameters.h\"),\"a\") as file:\n file.write(\"\"\"params.r0 = 0.4;\nparams.a = 0.0;\n\"\"\")\n\n```\n\n\n\n# Step 4: Set up boundary condition functions for chosen singular, curvilinear coordinate system \\[Back to [top](#toc)\\]\n$$\\label{bc_functs}$$\n\nNext apply singular, curvilinear coordinate boundary conditions [as documented in the corresponding NRPy+ tutorial notebook](Tutorial-Start_to_Finish-Curvilinear_BCs.ipynb)\n\n...But, for the moment, we're actually just using this because it writes the file `gridfunction_defines.h`.\n\n\n```python\nimport CurviBoundaryConditions.CurviBoundaryConditions as cbcs\ncbcs.Set_up_CurviBoundaryConditions(os.path.join(Ccodesdir,\"boundary_conditions/\"),Cparamspath=os.path.join(\"../\"),enable_copy_of_static_Ccodes=False)\n```\n\n Wrote to file \"GiRaFFE_staggered_standalone_Ccodes/boundary_conditions/parity_conditions_symbolic_dot_products.h\"\n Evolved parity: ( AD0:1, AD1:2, AD2:3, StildeD0:1, StildeD1:2, StildeD2:3,\n psi6Phi:0 )\n \n AuxEvol parity: ( BU0:1, BU1:2, BU2:3, B_lU0:1, B_lU1:2, B_lU2:3, B_rU0:1,\n B_rU1:2, B_rU2:3, BstaggerU0:1, BstaggerU1:2, BstaggerU2:3,\n Bstagger_lU0:1, Bstagger_lU1:2, Bstagger_lU2:3, Bstagger_rU0:1,\n Bstagger_rU1:2, Bstagger_rU2:3, Stilde_flux_HLLED0:1,\n Stilde_flux_HLLED1:2, Stilde_flux_HLLED2:3, ValenciavU0:1,\n ValenciavU1:2, ValenciavU2:3, Valenciav_lU0:1, Valenciav_lU1:2,\n Valenciav_lU2:3, Valenciav_llU0:1, Valenciav_llU1:2, Valenciav_llU2:3,\n Valenciav_lrU0:1, Valenciav_lrU1:2, Valenciav_lrU2:3, Valenciav_rU0:1,\n Valenciav_rU1:2, Valenciav_rU2:3, Valenciav_rlU0:1, Valenciav_rlU1:2,\n Valenciav_rlU2:3, Valenciav_rrU0:1, Valenciav_rrU1:2, Valenciav_rrU2:3,\n alpha:0, alpha_face:0, betaU0:1, betaU1:2, betaU2:3, beta_faceU0:1,\n beta_faceU1:2, beta_faceU2:3, cmax_x:0, cmax_y:0, cmax_z:0, cmin_x:0,\n cmin_y:0, cmin_z:0, gammaDD00:4, gammaDD01:5, gammaDD02:6, gammaDD11:7,\n gammaDD12:8, gammaDD22:9, gammaUU00:4, gammaUU01:5, gammaUU02:6,\n gammaUU11:7, gammaUU12:8, gammaUU22:9, gamma_faceDD00:4,\n gamma_faceDD01:5, gamma_faceDD02:6, gamma_faceDD11:7, gamma_faceDD12:8,\n gamma_faceDD22:9, gamma_faceUU00:4, gamma_faceUU01:5, gamma_faceUU02:6,\n gamma_faceUU11:7, gamma_faceUU12:8, gamma_faceUU22:9, phi:0,\n phi_face:0, psi6_temp:0, psi6center:0 )\n Wrote to file \"GiRaFFE_staggered_standalone_Ccodes/boundary_conditions/EigenCoord_Cart_to_xx.h\"\n\n\n\n\n# Step 5: `GiRaFFE_NRPy_standalone.c`: The Main C Code \\[Back to [top](#toc)\\]\n$$\\label{mainc}$$\n\n\n```python\n# Part P0: Define REAL, set the number of ghost cells NGHOSTS (from NRPy+'s FD_CENTDERIVS_ORDER),\n# and set the CFL_FACTOR (which can be overwritten at the command line)\n\nwith open(os.path.join(Ccodesdir,\"GiRaFFE_NRPy_REAL__NGHOSTS__CFL_FACTOR.h\"), \"w\") as file:\n file.write(\"\"\"\n// Part P0.a: Set the number of ghost cells, from NRPy+'s FD_CENTDERIVS_ORDER\n#define NGHOSTS \"\"\"+str(3)+\"\"\"\n#define NGHOSTS_A2B \"\"\"+str(2)+\"\"\"\n// Part P0.b: Set the numerical precision (REAL) to double, ensuring all floating point\n// numbers are stored to at least ~16 significant digits\n#define REAL \"\"\"+REAL+\"\"\"\n// Part P0.c: Set the CFL Factor. Can be overwritten at command line.\nREAL CFL_FACTOR = \"\"\"+str(default_CFL_FACTOR)+\";\")\n```\n\n\n```python\n%%writefile $Ccodesdir/GiRaFFE_NRPy_standalone.c\n// Step P0: Define REAL and NGHOSTS; and declare CFL_FACTOR. This header is generated in NRPy+.\n#include \"GiRaFFE_NRPy_REAL__NGHOSTS__CFL_FACTOR.h\"\n\n#include \"declare_Cparameters_struct.h\"\n\n// Output parameters: output_every, min and max radii for L2 norm\nconst int NSKIP_OUTPUT = 1;\nconst REAL outer_integration_radius = 1.5; const REAL inner_integration_radius = 0.6;\n\n// Step P1: Import needed header files\n#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"math.h\"\n#include \"time.h\"\n#include \"stdint.h\" // Needed for Windows GCC 6.x compatibility\n#ifndef M_PI\n#define M_PI 3.141592653589793238462643383279502884L\n#endif /*M_PI*/\n#ifndef M_SQRT1_2\n#define M_SQRT1_2 0.707106781186547524400844362104849039L\n#endif /*M_SQRT1_2*/\n\n// Step P2: Declare the IDX4S(gf,i,j,k) macro, which enables us to store 4-dimensions of\n// data in a 1D array. In this case, consecutive values of \"i\"\n// (all other indices held to a fixed value) are consecutive in memory, where\n// consecutive values of \"j\" (fixing all other indices) are separated by\n// Nxx_plus_2NGHOSTS0 elements in memory. Similarly, consecutive values of\n// \"k\" are separated by Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1 in memory, etc.\n#define IDX4S(g,i,j,k) \\\n( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) + Nxx_plus_2NGHOSTS2 * (g) ) ) )\n#define IDX4ptS(g,idx) ( (idx) + (Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1*Nxx_plus_2NGHOSTS2) * (g) )\n#define IDX3S(i,j,k) ( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) ) ) )\n#define LOOP_REGION(i0min,i0max, i1min,i1max, i2min,i2max) \\\n for(int i2=i2min;i2 SQR(inner_integration_radius)) {\n const int idx = IDX3S(i0,i1,i2);\n // Compute the sum of the squares of the difference between numerical and exact:\n integrated_quantities[0] += SQR(auxevol_gfs[IDX4ptS(BU0GF,idx)] - auxevol_gfs_exact[IDX4ptS(BU0GF,idx)]);\n integrated_quantities[1] += SQR(auxevol_gfs[IDX4ptS(BU1GF,idx)] - auxevol_gfs_exact[IDX4ptS(BU1GF,idx)]);\n integrated_quantities[2] += SQR(auxevol_gfs[IDX4ptS(BU2GF,idx)] - auxevol_gfs_exact[IDX4ptS(BU2GF,idx)]);\n integrated_quantities[3] += SQR(y_n_gfs[IDX4ptS(AD0GF,idx)] - evol_gfs_exact[IDX4ptS(AD0GF,idx)]);\n integrated_quantities[4] += SQR(y_n_gfs[IDX4ptS(AD1GF,idx)] - evol_gfs_exact[IDX4ptS(AD1GF,idx)]);\n integrated_quantities[5] += SQR(y_n_gfs[IDX4ptS(AD2GF,idx)] - evol_gfs_exact[IDX4ptS(AD2GF,idx)]);\n integrated_quantities[6] += SQR(y_n_gfs[IDX4ptS(STILDED0GF,idx)] - evol_gfs_exact[IDX4ptS(STILDED0GF,idx)]);\n integrated_quantities[7] += SQR(y_n_gfs[IDX4ptS(STILDED1GF,idx)] - evol_gfs_exact[IDX4ptS(STILDED1GF,idx)]);\n integrated_quantities[8] += SQR(y_n_gfs[IDX4ptS(STILDED2GF,idx)] - evol_gfs_exact[IDX4ptS(STILDED2GF,idx)]);\n integrated_quantities[9] += SQR(auxevol_gfs[IDX4ptS(VALENCIAVU0GF,idx)] - auxevol_gfs_exact[IDX4ptS(VALENCIAVU0GF,idx)]);\n integrated_quantities[10] += SQR(auxevol_gfs[IDX4ptS(VALENCIAVU1GF,idx)] - auxevol_gfs_exact[IDX4ptS(VALENCIAVU1GF,idx)]);\n integrated_quantities[11] += SQR(auxevol_gfs[IDX4ptS(VALENCIAVU2GF,idx)] - auxevol_gfs_exact[IDX4ptS(VALENCIAVU2GF,idx)]);\n integrated_quantities[12] += SQR(y_n_gfs[IDX4ptS(PSI6PHIGF,idx)] - evol_gfs_exact[IDX4ptS(PSI6PHIGF,idx)]);\n num_points++;\n }\n }\n }\n }\n // Divide by N, take the square root:\n for(int ii=0; ii t+dt) in time using\n // chosen RK-like MoL timestepping algorithm\n#include \"MoLtimestepping/RK_MoL.h\"\n } // End main loop to progress forward in time.\n\n // Step 4: Free all allocated memory\n#include \"MoLtimestepping/RK_Free_Memory.h\"\n free(auxevol_gfs);\n free(auxevol_gfs_exact);\n free(evol_gfs_exact);\n for(int i=0;i<3;i++) free(xx[i]);\n return 0;\n}\n```\n\n Writing GiRaFFE_staggered_standalone_Ccodes//GiRaFFE_NRPy_standalone.c\n\n\n\n```python\ncmd.C_compile(os.path.join(Ccodesdir,\"GiRaFFE_NRPy_standalone.c\"),\n os.path.join(Ccodesdir,\"output\",\"GiRaFFE_NRPy_standalone\"),compile_mode=\"safe\")\n# !gcc -g -O2 -fopenmp GiRaFFE_standalone_Ccodes/GiRaFFE_NRPy_standalone.c -o GiRaFFE_NRPy_standalone -lm\n\n# Change to output directory\nos.chdir(outdir)\n# Clean up existing output files\ncmd.delete_existing_files(\"out*.txt\")\ncmd.delete_existing_files(\"out*.png\")\n# cmd.Execute(os.path.join(Ccodesdir,\"output\",\"GiRaFFE_NRPy_standalone\"), \"640 16 16\", os.path.join(outdir,\"out640.txt\"))\ncmd.Execute(\"GiRaFFE_NRPy_standalone\", \"64 64 64\",\"out64.txt\")\n# cmd.Execute(\"GiRaFFE_NRPy_standalone\", \"128 128 128\",\"out128.txt\")\n# !OMP_NUM_THREADS=1 valgrind --track-origins=yes -v ./GiRaFFE_NRPy_standalone 1280 32 32\n# Return to root directory\nos.chdir(os.path.join(\"../../\"))\n```\n\n Compiling executable...\n (EXEC): Executing `gcc -O2 -g -fopenmp GiRaFFE_staggered_standalone_Ccodes/GiRaFFE_NRPy_standalone.c -o GiRaFFE_staggered_standalone_Ccodes/output/GiRaFFE_NRPy_standalone -lm`...\n (BENCH): Finished executing in 2.614776611328125 seconds.\n Finished compilation.\n (EXEC): Executing `taskset -c 0,1,2,3 ./GiRaFFE_NRPy_standalone 64 64 64`...\n (BENCH): Finished executing in 117.32049703598022 seconds.\n\n\nNow, we will load the data generated by the simulation and plot it in order to test for convergence. \n\n\n```python\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 0 1 2 3 4 5 6 7 8 9 10 11 12 13\nlabels = [\"x\",\"BU0\",\"BU1\",\"BU2\",\"AD0\",\"AD1\",\"AD2\",\"StildeD0\",\"StildeD1\",\"StildeD2\",\"ValenciavU0\",\"ValenciavU1\",\"ValenciavU2\", \"psi6Phi\"]\n# Data_numer = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out64-00000010.txt\"))\n# # Data_num_2 = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out239-00000080.txt\"))\n# # Data_old = np.loadtxt(\"/home/penelson/OldCactus/Cactus/exe/ABE-GiRaFFEfood_1D_AlfvenWave/giraffe-grmhd_primitives_bi.x.asc\")\n# # Data_o_2 = np.loadtxt(\"/home/penelson/OldCactus/Cactus/exe/ABE-GiRaFFEfood_1D_AlfvenWave_2/giraffe-grmhd_primitives_bi.x.asc\")\n# # Data_numer = Data_old[5000:5125,11:15] # The column range is chosen for compatibility with the plotting script.\n# # Data_num_2 = Data_o_2[19600:19845,11:15] # The column range is chosen for compatibility with the plotting script.\n# Data_exact = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out64-00000000.txt\"))\n# # Data_exa_2 = np.loadtxt(os.path.join(Ccodesdir,\"output\",\"out239-00000080_exact.txt\"))\n\n# predicted_order = 2.0\n# column = 8\n# plt.figure()\n# # # plt.plot(Data_exact[2:-2,0],np.log2(np.absolute((Data_numer[2:-2,column]-Data_exact[2:-2,column])/\\\n# # # (Data_num_2[2:-2:2,column]-Data_exa_2[2:-2:2,column]))),'.')\n# plt.plot(Data_exact[0:22,0],Data_exact[0:22,column],'b')\n# plt.plot(Data_exact[49:-1,0],Data_exact[49:-1,column],'b')\n# plt.plot(Data_exact[0:22,0],Data_numer[0:22,column],'r.')\n# plt.plot(Data_exact[49:-1,0],Data_numer[49:-1,column],'r.')\n# # plt.xlim(-0.0,1.0)\n# # # plt.ylim(-1.0,5.0)\n# # # plt.ylim(-0.0005,0.0005)\n# plt.xlabel(labels[0])\n# plt.ylabel(labels[column])\n# plt.show()\n\n# Plotting scripts for comparison with original GiRaFFE:\nold_files = [\"\",\n \"giraffe-grmhd_primitives_bi.x.asc\",\"giraffe-grmhd_primitives_bi.x.asc\",\"giraffe-grmhd_primitives_bi.x.asc\",\n \"giraffe-em_ax.x.asc\",\"giraffe-em_ay.x.asc\",\"giraffe-em_az.x.asc\",\n \"giraffe-grmhd_conservatives.x.asc\",\"giraffe-grmhd_conservatives.x.asc\",\"giraffe-grmhd_conservatives.x.asc\",\n \"giraffe-grmhd_primitives_allbutbi.x.asc\",\"giraffe-grmhd_primitives_allbutbi.x.asc\",\"giraffe-grmhd_primitives_allbutbi.x.asc\",\n \"giraffe-em_psi6phi.x.asc\"]\ncolumn = 6\ncolumn_old = [0,12,13,14,12,12,12,12,13,14,12,13,14,12]\nold_path = \"/home/penelson/Cactus/exe/ABE-GiRaFFEfood_ExactWald_newcode_agreement\"\nperturb_path = \"/home/penelson/Cactus/exe/ABE-GiRaFFEfood_ExactWald_newcode_agreement_pert\"\nnew_path = os.path.join(Ccodesdir,\"output\")\ndata_old = np.loadtxt(os.path.join(old_path,old_files[column]))\ndata_per = np.loadtxt(os.path.join(perturb_path,old_files[column]))\nn=80\ndata_old = data_old[n*70:n*70+70,:]# Select only the nth timestep\ndata_per = data_per[n*70:n*70+70,:]# Select only the nth timestep\ndata_new = np.loadtxt(os.path.join(new_path,\"out64-00000080.txt\"))\n\n# deltaA_old = data_old[125:250,:] - data_old[0:125,:]\n# data_new_t0 = np.loadtxt(os.path.join(new_path,\"out119-00000000.txt\"))\n# deltaA_new = data_new[:,:] - data_new_t0[:,:]\n\nplt.figure()\nplt.semilogy(data_new[:,0],(data_new[:,column]-data_old[:,column_old[column]])/(data_new[:,column]+data_old[:,column_old[column]]),label=\"Old vs. New\")\n\n# plt.plot(data_new[4:22,0],data_new[4:22,column]-data_old[4:22,column_old[column]])\n# plt.plot(data_new[49:-4,0],data_new[49:-4,column]-data_old[49:-4,column_old[column]])\n\n# plt.plot(data_new[:,0],data_old[:,column_old[column]])\n# plt.plot(data_new[:,0],data_new[:,column],'.')\n\n# plt.plot(data_new[:22,0],data_old[:22,column_old[column]])\n# plt.plot(data_new[49:,0],data_old[49:,column_old[column]])\n# plt.plot(data_new[:22,0],data_new[:22,column],'.')\n# plt.plot(data_new[49:,0],data_new[49:,column],'.')\n\n# plt.plot(data_new[3:-3,0],deltaA_new[3:-3,column],'.')\n# plt.plot(data_new[3:-3,0],deltaA_old[3:-3,column_old[column]]-deltaA_new[3:-3,column])\n# plt.xlabel(labels[0])\n# plt.ylabel(labels[column])\n# plt.show()\n\n# plt.figure()\nplt.semilogy(data_new[:,0],(data_old[:,column_old[column]]-data_per[:,column_old[column]])/(data_old[:,column_old[column]]+data_per[:,column_old[column]]),label=\"Old vs. Perturbed\")\nplt.xlabel(labels[0])\nplt.ylabel(\"E_rel in \"+labels[column])\nplt.legend()\nplt.show()\n```\n\nThis code will create an animation of the wave over time.\n\n\n```python\n# import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import savefig\nfrom IPython.display import HTML\nimport matplotlib.image as mgimg\n\nimport glob\nimport sys\nfrom matplotlib import animation\n\ncmd.delete_existing_files(\"out64-00*.png\")\nglobby = glob.glob(os.path.join(Ccodesdir,'output','out64-00*.txt'))\nfile_list = []\nfor x in sorted(globby):\n file_list.append(x)\n\nnumber_of_files = int(len(file_list))\n\nfor timestep in range(number_of_files):\n fig = plt.figure()\n numer_filename = file_list[timestep]\n exact_filename = os.path.join(Ccodesdir,'output','out64-00000000.txt')\n Numer = np.loadtxt(numer_filename)\n Exact = np.loadtxt(exact_filename)\n\n plt.title(\"Exact Wald\")\n plt.xlabel(\"x\")\n plt.ylabel(\"BU2\")\n# plt.xlim(-0.5,0.5)\n# plt.ylim(1.0,1.7)\n\n plt.plot(Numer[3:22,0],Numer[3:22,3],'.',label=\"Numerical\")\n plt.plot(Numer[49:-3,0],Numer[49:-3,3],'.',label=\"Numerical\")\n plt.plot(Exact[3:22,0],Exact[3:22,3],label=\"Exact\")\n plt.plot(Exact[49:-3,0],Exact[49:-3,3],label=\"Exact\")\n plt.legend()\n savefig(numer_filename+\".png\",dpi=150)\n plt.close(fig)\n sys.stdout.write(\"%c[2K\" % 27)\n sys.stdout.write(\"Processing file \"+numer_filename+\"\\r\")\n sys.stdout.flush()\n```\n\n \u001b[2KProcessing file GiRaFFE_staggered_standalone_Ccodes/output/out64-00000087.txt\r\n\n\n```python\n## VISUALIZATION ANIMATION, PART 2: Combine PNGs to generate movie ##\n# https://stackoverflow.com/questions/14908576/how-to-remove-frame-from-matplotlib-pyplot-figure-vs-matplotlib-figure-frame\n# https://stackoverflow.com/questions/23176161/animating-pngs-in-matplotlib-using-artistanimation\n# !rm -f GiRaFFE_NRPy-1D_tests.mp4\ncmd.delete_existing_files(\"GiRaFFE_NRPy-3D_tests.mp4\")\n\nfig = plt.figure(frameon=False)\nax = fig.add_axes([0, 0, 1, 1])\nax.axis('off')\n\nmyimages = []\n\nfor i in range(number_of_files):\n img = mgimg.imread(file_list[i]+\".png\")\n imgplot = plt.imshow(img)\n myimages.append([imgplot])\n\nani = animation.ArtistAnimation(fig, myimages, interval=100, repeat_delay=1000)\nplt.close()\nani.save('GiRaFFE_NRPy-1D_tests.mp4', fps=5,dpi=150)\n```\n\n\n```python\n%%HTML\n\n```\n\n\n\n\n\n\n\n```python\nimport cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface\ncmd.output_Jupyter_notebook_to_LaTeXed_PDF(\"Tutorial-GiRaFFE_NRPy_Main_Driver\",location_of_template_file=os.path.join(\"..\"))\n```\n\n Created Tutorial-GiRaFFE_NRPy_Main_Driver.tex, and compiled LaTeX file to\n PDF file Tutorial-GiRaFFE_NRPy_Main_Driver.pdf\n\n", "meta": {"hexsha": "72cdc000dbdcc45c0f71b832b0a8a62b9f816960", "size": 78981, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "in_progress/Tutorial-Start_to_Finish-GiRaFFE_NRPy-3D_tests-staggered.ipynb", "max_stars_repo_name": "fedelopezar/nrpytutorial", "max_stars_repo_head_hexsha": "753acd954be4a2f99639c9f9fd5e623689fc7493", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-12-13T05:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T05:51:18.000Z", "max_issues_repo_path": "in_progress/Tutorial-Start_to_Finish-GiRaFFE_NRPy-3D_tests-staggered.ipynb", "max_issues_repo_name": "fedelopezar/nrpytutorial", "max_issues_repo_head_hexsha": "753acd954be4a2f99639c9f9fd5e623689fc7493", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "in_progress/Tutorial-Start_to_Finish-GiRaFFE_NRPy-3D_tests-staggered.ipynb", "max_forks_repo_name": "fedelopezar/nrpytutorial", "max_forks_repo_head_hexsha": "753acd954be4a2f99639c9f9fd5e623689fc7493", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.3932172319, "max_line_length": 20388, "alphanum_fraction": 0.6915207455, "converted": true, "num_tokens": 14644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.30134434654370224}} {"text": "\n\n\n```python\npip install tensorflow==2.4.1 tensorflow-quantum\n```\n\n\n```python\n# Update package resources to account for version changes.\nimport importlib, pkg_resources\nimportlib.reload(pkg_resources)\n```\n\n\n\n\n \n\n\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\nfrom google.colab import drive\ndrive.mount('/content/drive')\n```\n\n Mounted at /content/drive\n\n\n\n```python\nimport sys\nsys.path.append('/content/drive/My Drive')\n```\n\n\n```python\nimport eecs598\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport statistics\nimport numpy as np\n```\n\n\n```python\nimport tensorflow as tf\nimport tensorflow_quantum as tfq\n\nimport cirq\nimport sympy\nimport numpy as np\nimport seaborn as sns\nimport collections\n\n# visualization tools\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom cirq.contrib.svg import SVGCircuit\n```\n\n\n```python\n\n# Control qrid size for visualization\nplt.rcParams['figure.figsize'] = (10.0, 8.0)\nplt.rcParams['font.size'] = 16\n```\n\n\n```python\nx_train, y_train, x_test, y_test = eecs598.data.cifar10()\n\nprint('Training set:', )\nprint(' data shape:', x_train.shape)\nprint(' labels shape: ', y_train.shape)\nprint('Test set:')\nprint(' data shape: ', x_test.shape)\nprint(' labels shape', y_test.shape)\n```\n\n Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./cifar-10-python.tar.gz\n\n\n\n 0%| | 0/170498071 [00:00 THRESHOLD, dtype=np.float32)\nx_test_bin = np.array(x_test_s > THRESHOLD, dtype=np.float32)\n```\n\n\n```python\nqubits = cirq.GridQubit.rect(4, 4)\n\n```\n\n\n```python\nxx=cirq.Y(qubits[1])\n\n```\n\n\n```python\ncirq.X(qubits[1])\ncirq.Y(qubits[1])\ncirq.Z\n```\n\n\n\n\n Y((0, 1))\n\n\n\n\n```python\nnp.random.uniform(size=(4, 3))\n```\n\n\n\n\n array([[0.7967969 , 0.30777665, 0.44788952],\n [0.18320573, 0.26701107, 0.49590493],\n [0.05564715, 0.00566145, 0.81495824],\n [0.77629675, 0.28633108, 0.49930407]])\n\n\n\n\n```python\ncirq.Circuit(cirq.X(qubits[1]), cirq.Y(qubits[1]))\n```\n\n\n\n\n
(0, 1): ───X───Y───
\n\n\n\n\n```python\n\n```\n\n\n```python\ndef convert_to_circuit(image):\n \"\"\"Encode truncated classical image into quantum datapoint.\"\"\"\n values = np.ndarray.flatten(image)\n qubits = cirq.GridQubit.rect(6, 6)\n circuit = cirq.Circuit()\n for i, value in enumerate(values):\n if value:\n cirq.X(qubits[i])\n circuit.append((cirq.X(qubits[i]), cirq.Y(qubits[i]), cirq.Z(qubits[i]) ))\n\n return circuit\n\n\nx_train_circ = [convert_to_circuit(x) for x in x_train_bin]\nx_test_circ = [convert_to_circuit(x) for x in x_test_bin]\n```\n\n\n```python\nSVGCircuit(x_train_circ[0])\n\n```\n\n findfont: Font family ['Arial'] not found. Falling back to DejaVu Sans.\n\n\n\n\n\n \n\n \n\n\n\n\n```python\nx_train_tfcirc = tfq.convert_to_tensor(x_train_circ)\nx_test_tfcirc = tfq.convert_to_tensor(x_test_circ)\n```\n\n\n```python\nclass CircuitLayerBuilder():\n def __init__(self, data_qubits, readout):\n self.data_qubits = data_qubits\n self.readout = readout\n\n def add_layer(self, circuit, gate, prefix):\n for i, qubit in enumerate(self.data_qubits):\n symbol = sympy.Symbol(prefix + '-' + str(i))\n circuit.append(gate(qubit, self.readout)**symbol)\n```\n\n\n```python\ndemo_builder = CircuitLayerBuilder(data_qubits = cirq.GridQubit.rect(4,1),\n readout=cirq.GridQubit(-1,-1))\n\ncircuit = cirq.Circuit()\ndemo_builder.add_layer(circuit, gate = cirq.XX, prefix='xx')\nSVGCircuit(circuit)\n```\n\n\n\n\n \n\n \n\n\n\n\n```python\ndef create_quantum_model():\n \"\"\"Create a QNN model circuit and readout operation to go along with it.\"\"\"\n data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.\n readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]\n circuit = cirq.Circuit()\n\n # Prepare the readout qubit.\n circuit.append(cirq.X(readout))\n circuit.append(cirq.H(readout))\n\n builder = CircuitLayerBuilder(\n data_qubits = data_qubits,\n readout=readout)\n\n # Then add layers (experiment by adding more).\n builder.add_layer(circuit, cirq.XX, \"xx1\")\n builder.add_layer(circuit, cirq.ZZ, \"zz1\")\n\n # Finally, prepare the readout qubit.\n circuit.append(cirq.H(readout))\n\n return circuit, cirq.Z(readout)\n```\n\n\n```python\nmodel_circuit, model_readout = create_quantum_model()\n```\n\n\n```python\nmodel = tf.keras.Sequential([\n # The input is the data-circuit, encoded as a tf.string\n tf.keras.layers.Input(shape=(), dtype=tf.string),\n # The PQC layer returns the expected value of the readout gate, range [-1,1].\n tfq.layers.PQC(model_circuit, model_readout),\n])\n```\n\n\n```python\ny_train_hinge = 2.0*y_train-1.0\ny_test_hinge = 2.0*y_test-1.0\n\n```\n\n\n```python\ndef hinge_accuracy(y_true, y_pred):\n y_true = tf.squeeze(y_true) > 0.0\n y_pred = tf.squeeze(y_pred) > 0.0\n result = tf.cast(y_true == y_pred, tf.float32)\n\n return tf.reduce_mean(result)\n```\n\n\n```python\nmodel.compile(\n loss=tf.keras.losses.Hinge(),\n optimizer=tf.keras.optimizers.Adam(),\n metrics=[hinge_accuracy])\n\n```\n\n\n```python\nprint(model.summary())\n```\n\n Model: \"sequential\"\n _________________________________________________________________\n Layer (type) Output Shape Param # \n =================================================================\n pqc (PQC) (None, 1) 32 \n =================================================================\n Total params: 32\n Trainable params: 32\n Non-trainable params: 0\n _________________________________________________________________\n None\n\n\n\n```python\nEPOCHS = 3\nBATCH_SIZE = 128\n\nNUM_EXAMPLES = len(x_train_tfcirc)\n\n```\n\n\n```python\nx_train_tfcirc_sub = x_train_tfcirc[:NUM_EXAMPLES]\ny_train_hinge_sub = y_train_hinge[:NUM_EXAMPLES]\n\n```\n\n\n```python\nimport time\nstart_time = time.time()\n```\n\n\n```python\nqnn_history = model.fit(\n x_train_tfcirc_sub, y_train_hinge_sub,\n batch_size=32,\n epochs=EPOCHS,\n verbose=1,\n validation_data=(x_test_tfcirc, y_test_hinge))\n\nqnn_results = model.evaluate(x_test_tfcirc, y_test)\n\n```\n\n Epoch 1/3\n 12/313 [>.............................] - ETA: 3:09:25 - loss: 1.0009 - hinge_accuracy: 0.5213\n", "meta": {"hexsha": "4c8873a59dfa605b3c76320beea35bc319219ee6", "size": 669054, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "qua.ipynb", "max_stars_repo_name": "WebheadTech/QCourse511-1", "max_stars_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qua.ipynb", "max_issues_repo_name": "WebheadTech/QCourse511-1", "max_issues_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qua.ipynb", "max_forks_repo_name": "WebheadTech/QCourse511-1", "max_forks_repo_head_hexsha": "e8396eb5b292203669eda5d04541d31c3d947803", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 525.9858490566, "max_line_length": 588094, "alphanum_fraction": 0.9280371988, "converted": true, "num_tokens": 2424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.3009288816037545}} {"text": "# KVLCC2 Ikeda method\n\n# Purpose\nHow good is original Ikeda method for this ship?\n\n# Methodology\nRun PyScoresII and calculate Ikeda\n\n# WIP - improvements\n(WORK IN PROGRESS)\nUse this section only if the notebook is not final.\n\nNotable TODOs:\n* todo 1\n* todo 2\n* todo 3\n\n## Results\nDescribe and comment the most important results.\n\n# Suggested next steps\nState suggested next steps, based on results obtained in this notebook.\n\n# Setup\n\n\n```python\n# %load imports.py\n\"\"\"\nThese is the standard setup for the notebooks.\n\"\"\"\n\n%matplotlib inline\n%load_ext autoreload\n%autoreload 2\n\nfrom jupyterthemes import jtplot\njtplot.style(theme='onedork', context='notebook', ticks=True, grid=False)\n\nimport pandas as pd\npd.options.display.max_rows = 999\npd.options.display.max_columns = 999\npd.set_option(\"display.max_columns\", None)\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\n#plt.style.use('paper')\n\n#import data\nimport copy\nfrom mdldb.run import Run\n\nfrom sklearn.pipeline import Pipeline\nfrom rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer\nfrom rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic\nfrom rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator\nimport rolldecayestimators.equations as equations\nimport rolldecayestimators.lambdas as lambdas\nfrom rolldecayestimators.substitute_dynamic_symbols import lambdify\nimport rolldecayestimators.symbols as symbols\nimport sympy as sp\n\nfrom sympy.physics.vector.printing import vpprint, vlatex\nfrom IPython.display import display, Math, Latex\n\nfrom sklearn.metrics import r2_score\nfrom src.data import database\nfrom mdldb import tables\n\n```\n\n\n```python\nimport pyscores2\nimport pyscores2.runScores2\nimport pyscores2.xml_hydrostatics\nfrom pyscores2.output import OutputFile\nfrom rolldecayestimators.ikeda import Ikeda, IkedaR\n\nfrom rolldecayestimators.simplified_ikeda_class import SimplifiedIkeda, SimplifiedIkedaABS\nfrom rolldecayestimators.simplified_ikeda import limits_kawahara\nfrom pyscores2.runScores2 import Calculation\nimport shutil\n```\n\n\n```python\ndb = database.get_db()\n```\n\n\n```python\nsql = \"\"\"\nSELECT * from run\nWHERE model_number='M5057-01-A' and test_type='roll decay' and project_number=40178362;\n\"\"\"\ndf_rolldecays = pd.read_sql(sql=sql, con=db.engine, index_col='id')\n\ndf_rolldecays['ship_speed'].fillna(0, inplace=True)\n\n```\n\n\n```python\ndf_rolldecays=df_rolldecays.loc[[21337,21338]].copy()\n```\n\n\n```python\nrow = df_rolldecays.iloc[0]\nrun = db.session.query(Run).get(int(row.name))\nrun = database.load_run(run, save_as_example=False, prefer_hdf5=True)\n \n```\n\n\n```python\nprint(run.project.project_path)\n```\n\n## Run ScoresII\n\n\n```python\nxml_parser = pyscores2.xml_hydrostatics.Parser(fileName='../data/external/KVLCC2m_kbk_final_ScoresData.xml')\nindata = xml_parser.convertToScores2Indata(conditionName='Design')\nindata.runOptions[\"IJ\"].set_value(1)\nindata.runOptions[\"IK\"].set_value(2)\n```\n\n\n```python\nindata.kxx = run.loading_condition.KXX*0.78 # To get correct natural frequency\nindata.kyy = run.loading_condition.KZZ\nindata.speedMax=15.5\nindata.speedIncrement=15\nindata.waveFrequenciesMax = 1.0\nindata.waveFrequenciesMin = 0.3\nindata.waveFrequenciesIncrement = 0.015\n#indata.zcg = run.loading_condition.kg\n```\n\n\n```python\nindata.save('../models/KVLCC2_0speed.IN')\n```\n\n\n```python\nsave_dir_name = 'scores'\nif not os.path.exists(save_dir_name):\n os.mkdir(save_dir_name)\n \ncalculation = Calculation(outDataDirectory='scores')\n```\n\n\n```python\ncalculation.run(indata=indata)\n```\n\n## Load ScoresII results\n\n\n```python\noutput_file = OutputFile(filePath=calculation.outDataPath)\n```\n\n\n```python\nshutil.copyfile(calculation.outDataPath,'../data/interim/KVLCC2_0speed.out')\n```\n\n\n```python\noutput_file.results\n```\n\n\n```python\ndf = output_file.get_result()\n```\n\n\n```python\ndf.describe()\n```\n\n\n```python\ndf.head()\n```\n\n\n```python\ndf[r'lambda/lpp'] = df['waveLengths']/run.ship.lpp \n\n\nfig,ax=plt.subplots()\nfor index, group in df.groupby(by=['speed','wave direction']):\n group.plot(x=r'lambda/lpp', y='heaveAmplitude', style='o-', label=index, ax=ax)\n \nax.grid(True)\nax.legend();\nax.set_ylabel('Heave');\n```\n\n\n```python\nRAO_15_0 = df.groupby(by=['speed','wave direction']).get_group((15,180))\n```\n\n\n```python\nfig,ax=plt.subplots()\nRAO_15_0.plot(x=r'lambda/lpp', y='heaveAmplitude', style='o-', ax=ax)\nax.set_xlim((0,1.8))\n\nfig,ax=plt.subplots()\nRAO_15_0.plot(x=r'lambda/lpp', y='pitchAmplitude', style='o-', ax=ax)\n#ax.set_xlim((0,1.8))\n```\n\n\n```python\ndf_roll_damping = output_file.get_roll_damping()\ndf_roll_damping\n```\n\n## Run Ikeda\n\n\n```python\nw = 2.462149630662348\n\nscale_factor=run.model.scale_factor\nV = row.ship_speed*1.852/3.6/np.sqrt(scale_factor)\n\nif not run.ship.BKL:\n BKL=0\nelse:\n BKL=run.ship.BKL/scale_factor\n\nif not run.ship.BKB:\n BKB = 0\nelse:\n BKB=run.ship.BKB/scale_factor\n\n#fi_as = np.deg2rad([1,10])\nfi_as = np.deg2rad(10)\n\nikeda = Ikeda.load_scoresII(V=V, w=w, fi_a=fi_as, indata=indata, output_file=output_file, \n scale_factor=scale_factor, BKL=BKL, BKB=BKB)\n\nR = 0.05*run.ship.beam/scale_factor # Just guessing...\nikeda.R = R\n```\n\n\n```python\ndef calculate_ikeda(ikeda):\n\n output = pd.DataFrame()\n output['B_44_hat'] = ikeda.calculate_B44()\n output['B_W0_hat'] = float(ikeda.calculate_B_W0())\n output['B_W_hat'] = float(ikeda.calculate_B_W())\n output['B_F_hat'] = ikeda.calculate_B_F()\n output['B_E_hat'] = ikeda.calculate_B_E()\n output['B_BK_hat'] = ikeda.calculate_B_BK()\n output['B_L_hat'] = float(ikeda.calculate_B_L())\n output['Bw_div_Bw0'] = float(ikeda.calculate_Bw_div_Bw0())\n return output\n```\n\n\n```python\nresult_datas = calculate_ikeda(ikeda) # DataFrame with two roll amplitudes\n```\n\n\n```python\nresult_datas\n```\n\n## Simplified Ikeda also...\n\n\n```python\nlpp = run.ship.lpp/scale_factor\nbeam = run.ship.beam/scale_factor\nkg = run.loading_condition.kg/scale_factor\nvolume = run.loading_condition.Volume/(scale_factor**3)\ndraught = (run.loading_condition.TA + run.loading_condition.TF)/2/scale_factor\nA0 = run.loading_condition.A0\n\nif not run.ship.BKL:\n BKL=0\nelse:\n BKL = run.ship.BKL\n\nif not run.ship.BKB:\n BKB = 0\nelse:\n BKB = run.ship.BKB\n\nsi = SimplifiedIkeda(V=V, w=w, fi_a=fi_as, beam=beam, lpp=lpp, kg = kg, volume=volume, draught=draught, A0=A0, BKL=BKL, BKB=BKB)\n```\n\n\n```python\ndef calculate_SI(si):\n \n output = pd.DataFrame()\n output['B_44_hat'] = si.calculate_B44()\n output['B_W0_hat'] =si.calculate_B_W0()\n output['B_W_hat'] =si.calculate_B_W()\n output['B_F_hat'] =si.calculate_B_F()\n output['B_E_hat'] =si.calculate_B_E()\n output['B_BK_hat'] =si.calculate_B_BK()\n output['B_L_hat'] =si.calculate_B_L()\n output['Bw_div_Bw0'] =si.calculate_Bw_div_Bw0()\n \n return output\n```\n\n\n```python\nresult_datas_SI = calculate_SI(si=si)\n```\n\n\n```python\nresult_datas_SI\n```\n\n\n```python\ndf_results = pd.DataFrame(columns=result_datas.columns)\ndf_results.loc['ikeda']=result_datas.iloc[0]\ndf_results.loc['SI']=result_datas_SI.iloc[0]\n\n```\n\n\n\n\n```python\ninteresting = ['B_W_hat','B_F_hat','B_E_hat']\ndf_results[interesting].plot(kind='bar',stacked=True)\n```\n\n\n```python\nlimits_kawahara\n```\n\n\n```python\ndf_limits = pd.DataFrame(data = limits_kawahara, index = ['min','max']).transpose()\ndf_limits\n```\n\n\n```python\ng=9.81\nomega_hat = lambdas.omega_hat(beam=beam, g=g, omega0=w)\n```\n\n\n```python\nCb = volume/(lpp*beam*draught)\nOG = draught-kg\nship_limits = {\n 'CB': Cb,\n 'B/d': beam/draught,\n 'OG/d': OG/draught,\n 'CMID': A0,\n 'bBk/B': BKB/beam,\n 'lBk/LPP': BKL/beam,\n 'OMEGA_hat': omega_hat}\nship_limits = pd.Series(ship_limits,name='ship')\n```\n\n\n```python\ndf_limits['ship'] = ship_limits\n```\n\n\n```python\ndf_limits_clean = df_limits.copy()\nif df_limits.loc['bBk/B','ship']==0:\n df_limits_clean.drop('bBk/B', inplace=True)\n \nif df_limits.loc['lBk/LPP','ship']==0:\n df_limits_clean.drop('lBk/LPP', inplace=True)\n```\n\n\n```python\nfig,ax=plt.subplots()\nax.errorbar(df_limits_clean.index,df_limits_clean['ship'],yerr=[df_limits_clean['ship']-df_limits_clean['min'],df_limits_clean['max']-df_limits_clean['ship']], \n fmt='ok', lw=1, ecolor='gray', capsize=20)\nax.set_title('Ship vs. SI limits')\n```\n\n\n```python\ndf_ = df_limits_clean.sub(df_limits['min'],axis=0)\ndf_limits_normalized = df_.div(df_['max'], axis=0)\n```\n\n\n\n\n```python\nfig,ax=plt.subplots()\nax.errorbar(df_limits_normalized.index,df_limits_normalized['ship'],yerr=[df_limits_normalized['ship']-df_limits_normalized['min'],\n df_limits_normalized['max']-df_limits_normalized['ship']], fmt='ok', lw=1, ecolor='gray', capsize=20)\nax.set_title('Ship vs. SI limits')\nax.set_ylabel('Norlimized limit')\n```\n\n\n```python\n\n```\n", "meta": {"hexsha": "329f857ad074cf8feca13252e4f5e28288dba2ea", "size": 16662, "ext": "ipynb", "lang": "Jupyter Notebook", "max_stars_repo_path": "notebooks/04.1_KVLCC2_Ikeda_method.ipynb", "max_stars_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_stars_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "notebooks/04.1_KVLCC2_Ikeda_method.ipynb", "max_issues_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_issues_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "notebooks/04.1_KVLCC2_Ikeda_method.ipynb", "max_forks_repo_name": "rddaz2013/Prediction-of-roll-motion-using-fully-nonlinear-potential-flow-and-Ikedas-method", "max_forks_repo_head_hexsha": "ac0a27e31d64edc8ae8912b6ed10005029868c90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-06-05T15:38:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T15:38:54.000Z", "avg_line_length": 24.3953147877, "max_line_length": 183, "alphanum_fraction": 0.5531148722, "converted": true, "num_tokens": 2588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3005463427108183}}