{ "cells": [ { "cell_type": "markdown", "id": "babe426a-c2bf-46ff-b9ad-ee0ecbb5af57", "metadata": {}, "source": [ "# Programming Assignment 3\n", "## \"Paint by numbers\"\n", "" ] }, { "cell_type":...

1 answer below ยป
Solve this assignment please


{ "cells": [ { "cell_type": "markdown", "id": "babe426a-c2bf-46ff-b9ad-ee0ecbb5af57", "metadata": {}, "source": [ "# Programming Assignment 3\n", "## \"Paint by numbers\"\n", "" ] }, { "cell_type": "markdown", "id": "5b89034c-51e1-4e03-bc7f-a4175ffaeec4", "metadata": {}, "source": [ "Insert the names of the group members here:\n", " \n", " * Name 1\n", " * Name 2" ] }, { "cell_type": "markdown", "id": "59767431-7186-4cb6-9cfb-0c8262820577", "metadata": {}, "source": [ "For a better understanding of the flow field around a circular cylinder with a diameter of 7.5 mm, [CFD simulations](https://en.wikipedia.org/wiki/Computational_fluid_dynamics) were done.\n", "The calculations were done on an irregular 2D grid, which cuts through the cylinder, so that it is visible as a circle.\n", "The results for one instant in time were exported as [CSV file](https://en.wikipedia.org/wiki/Comma-separated_values).\n", "\n", "**All the programming for this assignment can be done without any if-statements or loops! It's okay if you need them for your initial solution, but try to come up with a variant that doesn't involve these structures and instead makes use of the numpy features.**\n", "\n", "### 1. Grid information\n", "\n", "**1.1) Load the data from the file `U_xyplane.csv` and unpack the content of the columns into new variables (1D-arrays) `u,v,w,x,y,z`. For how many points do we have data?**\n", "\n", "_Note: \"Unpacking\" an array `A` that has 2 rows is possible like this: `a,b = A`. All values are given in SI units (m and m/s)._" ] }, { "cell_type": "code", "execution_count": null, "id": "cb934408-d100-43bc-89f4-59b65e9af275", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from matplotlib.patches import Circle\n", "# Write your own code here ...\n" ] }, { "cell_type": "markdown", "id": "04bd9eec-a6ad-439d-87c0-0752c89b41b2", "metadata": {}, "source": [ "To get an idea of the setup, it would be nice to have a quick overview of the simulation area including the \"cylinder circle\".\n", "\n", "**1.2) Determine the minimum and maximum x and y values and draw a rectangle that covers the area and surrounds a circle positioned at (x,y)=(0.06 m, 0.15 m) with a diameter of 7.5 mm.**\n", "\n", " * Write a function that gets the draws an unfilled rectangle using the [_plot()_] command.\n", "\n", "Adding a circle to an existing figure is possible e.g. by this:\n", "```python\n", " plt.gca().add_patch(Circle((x_center, y_center), radius, color='k'))\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "cc19bf14-9157-4ca8-88b5-61a95cc25d64", "metadata": {}, "outputs": [], "source": [ "def rectangle(xmin,xmax,ymin,ymax):\n", " # Write your own code here ...\n", " \n", "\n", "plt.figure(1,(10,6))\n", "# plot rectangle ...\n", "\n", "# plot circle ...\n", "\n", "# add axes labels ...\n", "\n", "plt.axis('equal')\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "e20945dc-6d60-47cd-ae1b-5cd894038f16", "metadata": {}, "source": [ "Before looking at the data itself, lets have a look at the structure of the grid.\n", "\n", "**1.3) Visualize the grid points in a 20x13-inch plot using `'.'`-markers with a size of 0.5.**\n", "\n", " * Select a sub-area of this grid that contains only the points with $5.9\\,$cm $< x="">< 6.1\\,$cm="" and="" $y=""> 15\\,$cm. \n", " * How many grid points lie in this area?\n", " * Add the corresponding grid points in a different color to the original plot.\n", "\n", "_Note: For combining multiple boolean expressions in arrays, the [bitwise operators](https://wiki.python.org/moin/BitwiseOperators) `&` (and) and `|` (or) can be used._" ] }, { "cell_type": "code", "execution_count": null, "id": "540a5e72-10b9-4424-8cac-ad07af92943d", "metadata": { "tags": [] }, "outputs": [], "source": [ "# Write your own code here ...\n" ] }, { "cell_type": "markdown", "id": "a2b04f02-80ab-410c-ad99-fbfa70c3e1a0", "metadata": {}, "source": [ "**1.4) For each point in the smaller sub-grid you just selected, calculate the distance to its nearest neighbor.**\n", "\n", "This can be done, e.g., by calculating the distance from all points to all other points and then looking for the minimum value (but larger than 0!) for each point.\n", "\n", " * Sort the distances in ascending order.\n", " * Provide a plot with just an index on the $x$-axis and the respective minimum distances on the logarithmically scaled $y$-axis." ] }, { "cell_type": "code", "execution_count": null, "id": "9099517b-7b40-4008-b42c-60a48eb228de", "metadata": { "tags": [] }, "outputs": [], "source": [ "# Write your own code here ...\n", "\n", "plt.grid(True)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "0719dd41-6269-4812-977a-f421950cb249", "metadata": {}, "source": [ "## 2. Flow speeds\n", "\n", "Now let's look at the speeds that are present in the data set.\n", "\n", "**2.1) For a general overview, provide [histograms](https://en.wikipedia.org/wiki/Histogram) of the three speed components.**\n", "\n", " * You can use matplotlib's [_hist()_](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html) function for this.\n", " * Plot the graphs side-by-side (3 plots in one row).\n", " * For each plot, use 100 equal-width bins.\n", " * What is the maximum speed in $x$ direction?" ] }, { "cell_type": "code", "execution_count": null, "id": "5eba8412-ba7e-457a-98fd-c96715234cdf", "metadata": {}, "outputs": [], "source": [ "# Write your own code here ...\n" ] }, { "cell_type": "markdown", "id": "00b34b62-5868-4851-9274-feb2fd3d2b74", "metadata": {}, "source": [ "**2.2) Visualize the flow testing different plot variants.**\n", "\n", " * Calculate the magnitude of the flow speeds (lengths of the velocity vectors at the grid points).\n", " * Generate 3 visualization of these magnitudes:\n", " 1. using the [_scatter()_](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html) function a color-representation of the values.\n", " 2. using the [_tricontourf()_](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontourf.html) function with 8, 32, and 256 levels (this is the one exception where using a loop would actually be efficient).\n", " * Make sure that the cylinder circle is represented in white.\n", " * Add a [colorbar](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html) so that the colors can be attributed to speeds." ] }, { "cell_type": "code", "execution_count": null, "id": "4fa8d35c-4d12-496e-a5bf-911a54a0ee44", "metadata": {}, "outputs": [], "source": [ "plt.figure(5,(20,50))\n", "plt.subplot(411)\n", "# Write your own code here ...\n" ] }, { "cell_type": "markdown", "id": "92e66dc7-b15f-4615-8aa4-517dd606756e", "metadata": {}, "source": [ "## 3. Vorticity\n", "\n", "To identify \"interesting\" regions in a flow field, often the [vorticity](https://en.wikipedia.org/wiki/Vorticity) is used, which we now want to calculate.\n", "We shall content ourselves with the calculation in 2D, i.e. the
Answered Same DayAug 05, 2021

Answer To: { "cells": [ { "cell_type": "markdown", "id": "babe426a-c2bf-46ff-b9ad-ee0ecbb5af57", "metadata":...

Swapnil answered on Aug 06 2021
145 Votes
89198/.ipynb_checkpoints/Final-checkpoint.ipynb
{
"cells": [
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"from PIL import Image\n",
"from scipy.spatial import Delaunay\n",
"from scipy.interpolate import griddata\n",
"from scipy.optimize import leastsq\n",
"import plotly.graph_objects as go\n",
"import plotly.io as pio\n",
"import plotly.figure_factory as ff\n",
"from plotly.subplots import make_subplots"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"def create_folder(type_=None, train_data=None, valid_data=None, classes=[], folder='data'):\n",
" os.mkdir(F'{folder}/{type_}')\n",
" os.mkdir(F'{folder}/{type_}/train')\n",
"\n",
" for label in classes:\n",
" os.mkdir(F'{folder}/{type_}/train/{label}')\n",
" \n",
" for index, elem in train_data.iterrows():\n",
" file_ = elem['filename']\n",
" label = elem[type_]\n",
" if label in classes:\n",
" source = F'{datafolder}/data/{file_}'\n",
" target = F'{datafolder}/{type_}/data/{label}/{file_}'\n",
" copyfile(source, target)\n",
"\n",
" samples = valid_data[labels][type_].value_counts()\n",
" class_ = {}\n",
" for elem in list(zip(samples,samples.index)):\n",
" if elem[1] in classes:\n",
" valid = round(elem[0]*0.5)\n",
" test = elem[0] - valid\n",
" class_[elem[1]] = {'valid':valid, 'test':test}\n",
"\n",
" for index, elem in valid_data.iterrows():\n",
" file_ = elem['filename']\n",
" name = elem[type_]\n",
" if name in classes:\n",
" samples = class_[name]\n",
" if samples['valid'] > 0:\n",
" class_[name]['valid'] -= 1\n",
" source = F'{folder}/data/{file_}'\n",
" target = F'{folder}/{type_}/valid/{name}/{file_}'\n",
" copyfile(source, target)\n",
" else:\n",
" samples['test'] -= 1\n",
" source = F'{folder}/data/{file_}'\n",
" target = F'{folder}/{type_}/data/{name}/{file_}'\n",
" copyfile(source, target)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"datafolder = '.'"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"
\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"
U:0U:1U:2Points:0Points:1Points:2
036.7028-0.0006650.008076-0.0017930.0780000.09
136.7027-0.0014540.004049-0.0040000.0780000.09
236.7032-0.0015840.008007-0.0017930.0802120.09
336.70000.0000000.000000-0.0040000.0802150.09
436.7054-0.0016220.0133990.0004150.0780000.09
\n",
"
"
],
"text/plain": [
" U:0 U:1 U:2 Points:0 Points:1 Points:2\n",
"0 36.7028 -0.000665 0.008076 -0.001793 0.078000 0.09\n",
"1 36.7027 -0.001454 0.004049 -0.004000 0.078000 0.09\n",
"2 36.7032 -0.001584 0.008007 -0.001793 0.080212 0.09\n",
"3 36.7000 0.000000 0.000000 -0.004000 0.080215 0.09\n",
"4 36.7054 -0.001622 0.013399 0.000415 0.078000 0.09"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dataset = pd.read_csv('data.csv'); \n",
"dataset.head()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"labels = ['U:0', 'U:1', 'U:2']"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(35267, 6)"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dataset.shape"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"def load_data(size=64):\n",
" # Load image, resize, make monochrome (black and white) copy and convert to Numpy array\n",
" image_rgb = Image.open(\"data.csv\").resize([size, size])\n",
" image_bw = image_rgb.convert('L')\n",
" image_rgb = np.asarray(image_rgb)\n",
" image_bw = np.asarray(image_bw)\n",
"\n",
" # Get size and color info\n",
" height, width, channels = image_rgb.shape\n",
" colors = np.array([f\"rgb{rgb[0], rgb[1], rgb[2]}\" for rgb in image_rgb.reshape(-1, 3)])\n",
" values = image_bw.reshape(-1).astype(str)\n",
"\n",
" # Make grid to paint colors (or pixel values) on\n",
" x, y = np.meshgrid(np.arange(width), np.arange(height))\n",
" flat_x, flat_y = x.reshape(-1), y.reshape(-1)\n",
"\n",
" red = np.array([rgb[0] for rgb in image_rgb.reshape(-1, 3)]).astype(str)\n",
" green = np.array([rgb[1] for rgb in image_rgb.reshape(-1, 3)]).astype(str)\n",
" blue = np.array([rgb[2] for rgb in image_rgb.reshape(-1, 3)]).astype(str)\n",
" \n",
" return {\"rgb\": image_rgb,\n",
" \"mono\": image_bw,\n",
" \"x\": flat_x,\n",
" \"y\": flat_y,\n",
" \"colors\": colors,\n",
" \"values\": values,\n",
" \"red\": red,\n",
" \"green\": green,\n",
" \"blue\": blue}"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"def get_layout():\n",
" return go.Layout(template=\"plotly_white\",\n",
" xaxis=dict(constrain=\"domain\",\n",
" visible=False),\n",
" yaxis=dict(scaleanchor='x',\n",
" visible=False,\n",
" autorange=\"reversed\"),\n",
" hoverlabel=dict(font_size=18),\n",
" height=1024,\n",
" margin=dict(r=0, l=0, b=0, t=0, pad=0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor":...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions ยป

Submit New Assignment

Copy and Paste Your Assignment Here