# Python for Engineers Assignment 2018
Answer all questions.

すべての質問に答えなさい。

Submission deadline 07/16 (July 16).

提出締め切り07/16 (7月16日）。

Please submit your answer by email.

どうぞ、メールによってあなたの答えを提出してください。

You may use the following file formats:

あなたは以下のファイル形式を使ってもよい:
- .py
- .ipynb
- .txt

You may use multiple files.

あなたは複数のファイルを使ってもよい。

You will be awarded points for:
あなたは以下のためのポイントを授与される：
- correct solution. 正しい答え。
- concise solution. 簡潔な答え。
- optimising your code by importing relevant library functions. 外部や基準のライブラリやパッケージを利用します。
- writing functions to avoid repetition. 重複を防ぐために関数（functions)を使いなさい。
- using comments to explain what your code does. あなたのコードを説明するために、コメントを用いる。

## Part A : Data Analysis　データ分析

#### Question 1
*(2 marks)*

Import the data from the url to a Pandas data frame:

`Pandas`を使って、以下urlからデータを読み込めよ

https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user

```python
import pandas as pd
import io
import requests
url="https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user"

contents=requests.get(url).content

dataF=pd.read_csv(io.StringIO(contents.decode('utf-8')),delimiter='|')

dataF
```

      user_id
      age
      gender
      occupation
      zip_code

      0
      1
      24
      M
      technician
      85711

      1
      2
      53
      F
      other
      94043

      2
      3
      23
      M
      writer
      32067

      3
      4
      24
      M
      technician
      43537

      4
      5
      33
      F
      other
      15213

      5
      6
      42
      M
      executive
      98101

      6
      7
      57
      M
      administrator
      91344

      7
      8
      36
      M
      administrator
      05201

      8
      9
      29
      M
      student
      01002

      9
      10
      53
      M
      lawyer
      90703

      10
      11
      39
      F
      other
      30329

      11
      12
      28
      F
      other
      06405

      12
      13
      47
      M
      educator
      29206

      13
      14
      45
      M
      scientist
      55106

      14
      15
      49
      F
      educator
      97301

      15
      16
      21
      M
      entertainment
      10309

      16
      17
      30
      M
      programmer
      06355

      17
      18
      35
      F
      other
      37212

      18
      19
      40
      M
      librarian
      02138

      19
      20
      42
      F
      homemaker
      95660

      20
      21
      26
      M
      writer
      30068

      21
      22
      25
      M
      writer
      40206

      22
      23
      30
      F
      artist
      48197

      23
      24
      21
      F
      artist
      94533

      24
      25
      39
      M
      engineer
      55107

      25
      26
      49
      M
      engineer
      21044

      26
      27
      40
      F
      librarian
      30030

      27
      28
      32
      M
      writer
      55369

      28
      29
      41
      M
      programmer
      94043

      29
      30
      7
      M
      student
      55436

      ...
      ...
      ...
      ...
      ...
      ...

      913
      914
      44
      F
      other
      08105

      914
      915
      50
      M
      entertainment
      60614

      915
      916
      27
      M
      engineer
      N2L5N

      916
      917
      22
      F
      student
      20006

      917
      918
      40
      M
      scientist
      70116

      918
      919
      25
      M
      other
      14216

      919
      920
      30
      F
      artist
      90008

      920
      921
      20
      F
      student
      98801

      921
      922
      29
      F
      administrator
      21114

      922
      923
      21
      M
      student
      E2E3R

      923
      924
      29
      M
      other
      11753

      924
      925
      18
      F
      salesman
      49036

      925
      926
      49
      M
      entertainment
      01701

      926
      927
      23
      M
      programmer
      55428

      927
      928
      21
      M
      student
      55408

      928
      929
      44
      M
      scientist
      53711

      929
      930
      28
      F
      scientist
      07310

      930
      931
      60
      M
      educator
      33556

      931
      932
      58
      M
      educator
      06437

      932
      933
      28
      M
      student
      48105

      933
      934
      61
      M
      engineer
      22902

      934
      935
      42
      M
      doctor
      66221

      935
      936
      24
      M
      other
      32789

      936
      937
      48
      M
      educator
      98072

      937
      938
      38
      F
      technician
      55038

      938
      939
      26
      F
      student
      33319

      939
      940
      32
      M
      administrator
      02215

      940
      941
      20
      M
      student
      97229

      941
      942
      48
      F
      librarian
      78209

      942
      943
      22
      M
      student
      77841

943 rows × 5 columns

#### Question 2
*(2 marks)*

Remove all entries with occupation `other` or `retired` from the data set.

職業`occupation`の中に`other`と`retired`に関連するデータを取り除く。

```python
dataF_mod = dataF[dataF.occupation != 'other']
#removes entries 'other' in occupation
dataF_mod = dataF_mod[dataF_mod.occupation != 'retired']
#removes entries 'retired' in occupation

dataF_mod
```

      user_id
      age
      gender
      occupation
      zip_code

      0
      1
      24
      M
      technician
      85711

      2
      3
      23
      M
      writer
      32067

      3
      4
      24
      M
      technician
      43537

      5
      6
      42
      M
      executive
      98101

      6
      7
      57
      M
      administrator
      91344

      7
      8
      36
      M
      administrator
      05201

      8
      9
      29
      M
      student
      01002

      9
      10
      53
      M
      lawyer
      90703

      12
      13
      47
      M
      educator
      29206

      13
      14
      45
      M
      scientist
      55106

      14
      15
      49
      F
      educator
      97301

      15
      16
      21
      M
      entertainment
      10309

      16
      17
      30
      M
      programmer
      06355

      18
      19
      40
      M
      librarian
      02138

      19
      20
      42
      F
      homemaker
      95660

      20
      21
      26
      M
      writer
      30068

      21
      22
      25
      M
      writer
      40206

      22
      23
      30
      F
      artist
      48197

      23
      24
      21
      F
      artist
      94533

      24
      25
      39
      M
      engineer
      55107

      25
      26
      49
      M
      engineer
      21044

      26
      27
      40
      F
      librarian
      30030

      27
      28
      32
      M
      writer
      55369

      28
      29
      41
      M
      programmer
      94043

      29
      30
      7
      M
      student
      55436

      30
      31
      24
      M
      artist
      10003

      31
      32
      28
      F
      student
      78741

      32
      33
      23
      M
      student
      27510

      33
      34
      38
      F
      administrator
      42141

      34
      35
      20
      F
      homemaker
      42459

      ...
      ...
      ...
      ...
      ...
      ...

      908
      909
      50
      F
      educator
      53171

      909
      910
      28
      M
      healthcare
      29301

      910
      911
      37
      F
      writer
      53210

      912
      913
      27
      M
      student
      76201

      914
      915
      50
      M
      entertainment
      60614

      915
      916
      27
      M
      engineer
      N2L5N

      916
      917
      22
      F
      student
      20006

      917
      918
      40
      M
      scientist
      70116

      919
      920
      30
      F
      artist
      90008

      920
      921
      20
      F
      student
      98801

      921
      922
      29
      F
      administrator
      21114

      922
      923
      21
      M
      student
      E2E3R

      924
      925
      18
      F
      salesman
      49036

      925
      926
      49
      M
      entertainment
      01701

      926
      927
      23
      M
      programmer
      55428

      927
      928
      21
      M
      student
      55408

      928
      929
      44
      M
      scientist
      53711

      929
      930
      28
      F
      scientist
      07310

      930
      931
      60
      M
      educator
      33556

      931
      932
      58
      M
      educator
      06437

      932
      933
      28
      M
      student
      48105

      933
      934
      61
      M
      engineer
      22902

      934
      935
      42
      M
      doctor
      66221

      936
      937
      48
      M
      educator
      98072

      937
      938
      38
      F
      technician
      55038

      938
      939
      26
      F
      student
      33319

      939
      940
      32
      M
      administrator
      02215

      940
      941
      20
      M
      student
      97229

      941
      942
      48
      F
      librarian
      78209

      942
      943
      22
      M
      student
      77841

824 rows × 5 columns

#### Question 3
*(6 marks)*

Plot a bar chart showing:

棒グラフをプロットしなさい：
- the number of people per occupation for the 10 occupations that occur most frequently in the data set.

取り除かない各職業の総人数を計算し、総人数最も多い10つの職業を取り出し、各職業の総人数を棒グラフで書きなさい。
- plot an additional bar, labelled other, showing the sum of all remaining entries in the data set.

その以外の職業の人数をまとめて、`other`という名前を付け、同じ棒グラフに書きなさい。

```python
dat = dataF_mod

freq_table = pd.value_counts(dat.occupation).to_frame().reset_index()
freq_table.columns = ['occupation','count']
#obtains frequency of each occupations
#renamed columns

freq_bar = freq_table.iloc[0:10]
othersRow = pd.DataFrame({'occupation': ['others'],
                         'count' : freq_table.iloc[10:][['count']].sum()})
#created 'otherRow' as additional bar which sums the remaining entries
freq_bar = freq_bar.append(othersRow)
#freq_bar = pd.concat([freq_bar,othersRow])
#appended 'otherRow' to 'freq_bar'

freq_plot = freq_bar.plot(x='occupation',y='count',kind="bar")
freq_plot.set_xlabel("Occupation")
freq_plot
```

#### Question 4
*(2 marks)*

Find the:
- mean
- standard deviaion

of the age of people with the occupation: `administrator`.

`administrator`という職業`occupation`の人達を見つけ出す。その人達の年齢の
- 平均値
- 標準偏差

を求めよ。

```python
dat_admin = dat[dat.occupation == 'administrator']
#created another table with only 'administrator's
age_mean = dat_admin["age"].mean()
age_std = dat_admin["age"].std()
print("mean:",age_mean)
print("standard deviation:",age_std)
```

    mean: 38.74683544303797
    standard deviation: 11.123396864533204

## Part B : Movement of a Particle 粒子の動き

A particle moves along a curve.

粒子がある軌跡を沿って移動する。

The cartesian coordinates of the position of the particle $(r_x, r_y)$ are:

粒子の位置$（r_x、r_y）$は時間$t$の変数である。その式は以下：

\begin{align}
r_x &= \exp \left( -\dfrac{t}{T_1} \right)
\\
r_y &= 2 \cos \left(\dfrac{t}{T_2}\right)
\end{align}

$t$ = time (s)

Constants:　その中に、$T$は定数

$T_1 = 1$ s

$T_2 = 1/3$ s.

#### Question 1
*(8 marks)*

Plot the trajectory of the particle in the $xy$-plane over the time interval $t = 0$ to $t = 2\pi$ s.

時間$t=0$から$t=2\pi$までの粒子の軌跡を書きなさい。軌跡を表す点の数は任意。

On the graph, show the particle’s locations at $t = 0$, $\pi/2$ and $2\pi$ using:

同じ図に、以下のものを使って、$t=0$、$t=\pi／2$と$t=2\pi$の粒子の位置を強調せよ：
- a marker
- a label

```python
import numpy as np
import matplotlib.pyplot as plt

t_1 = 1.0
t_2 = 1.0/3.0
pi = np.pi
t= np.arange(0,2.0*pi,0.001)
#t = np.linspace(1,10,14)

def r_x(t):
    return np.exp(-t/t_1)

def r_y(t):
    return 2.0*np.cos(t/t_2)

plt.plot(r_x(t),r_y(t))
plt.plot([r_x(0),r_x(pi/2.0),r_x(2.0*pi)],[r_y(0),r_y(pi/2.0),r_y(2.0*pi)],'ro')
plt.grid()
plt.show()

```

#### Question 2

The $x$ and $y$ components of the particle's acceleration $(a_x, a_y)$:

粒子の加速度$（a_x、a_y）$はの粒子の位置$（r_x、r_y）$の二階微分である：

$$a_x=v_x'=r_x''$$
$$a_y=v_y'=r_y''$$

velocity $(v_x, v_y)$

速度$(v_x, v_y)$

__(a)__ Express the particles acceleration $(a_x、a_y)$ symbolically, i.e. show the equation.

粒子加速度$（a_x、a_y）$を計算せよ。方程式を示す。

*(5 marks)*

```python
def a_x(t):
    return 1.0/(t_1**2.0)*np.exp(-t/t_1)
def a_y(t):
    return -2.0/(t_2**2.0)*np.cos(t/t_2)
```

__(b)__ Plot the *magnitude* of the acceleration of the particle against time over the time interval $t = 0$ to $t = 2\pi$ s.

時間$t=0$から$t=2\pi$までの粒子の加速度の絶対値（マグニチュード加速度）を計算し、時間$t$に対する図を書きなさい。つまり、X軸は時間$t$、Y軸は加速度の絶対値。絶対値の式は以下

*(5 marks)*

The magnitude of acceleration, $A$:
$$A = \sqrt{a_x^2 + a_y^2}$$

```python
def A(t):
    return ((a_x(t))**2.0+(a_y(t))**2.0)**(0.5)
plt.plot(t,A(t))
```

#### Question 3
__(a)__
Find the magnitude velocity of the particle at time $ t = 1$s.

$t=1$時刻の粒子の速度の絶対値（マグニチュード速度）を見つけ出す。

*(5 marks)*

```python
def v_x(t):
    return -1.0/t_1*np.exp(-t/t_1)
def v_y(t):
    return -2.0/t_2*np.sin(t/t_2)
def V(t):
    return ((v_x(t))**2.0+(v_y(t))**2.0)**(0.5)
print('velocity at t = 1s is',V(1))
```

    velocity at t = 1s is 0.923184772150204

__(b)__
Estimate the time/times when $r_y=0$

$r_y=0$を満足する時間（時間達）を逆計算せよ。

*(5 marks)*

```python
tol = 0.001
prev_sol = -10000

print('times which r_y = 0')

for p in np.arange(0,2.0*pi,0.0001):
    if (abs(r_y(p))<tol) :
        if (abs(prev_sol - p)<tol):
            continue
        print(p)
        prev_sol = p
```

    times which r_y = 0
    0.5235000000000001
    1.5707
    2.6179
    3.6651000000000002
    4.7123
    5.7595

#### Question 4
*(10 marks)*

Animate the trajectory of the particle and save your work as a .mp4 file.

粒子の移動軌跡をアニメーション化し、.mp4ファイルとして保存しなさい。

```python
from matplotlib import animation, rc
from IPython.display import HTML

fig = plt.figure()
ax = plt.axes(xlim=(0, 1.0), ylim=(-2, 2))
point, = ax.plot([0.1], [0.1], marker='o', ms=5)

def animate(i):
    t = i/100.0
    x = r_x(t)
    y = r_y(t)
    #print(i)
    point.set_data(x, y)
    return (point)

# Animates data
# 100 frames
# 20ms delay
anim = animation.FuncAnimation(fig, animate, frames=1000, interval=20)
rc('animation', html='html5')
anim
#writer = animation.writers['ffmpeg'](fps=15, bitrate=1800)
#anim.save('./particle_movie.mp4', writer= "teethat")
```

```python

```