Programming Assignments

Main.CourseHomework History

Hide minor edits - Show changes to markup

May 02, 2023, at 02:37 PM by 136.36.4.38 -
Changed line 120 from:

Complete the following assignments with Microsoft Excel or Google Sheet (1-6) and Python for (1-17). The first 6 assignments are the same problems but completed with both a Spreadsheet program (Excel or Google Sheets) and Python. Solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment.

to:

Complete the following assignments with Microsoft Excel or Google Sheet (1-6) and Python for (1-17). The first 6 assignments are the same problems but completed with both a Spreadsheet program (Excel or Google Sheets) and Python. Solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment. Join Online for homework help sessions.

May 31, 2022, at 07:27 PM by 10.35.117.248 -
Changed lines 337-339 from:

Python Solutions

to:

Python Solutions 1-2+

Python Solution 3

April 28, 2021, at 04:34 AM by 10.35.117.248 -
Deleted lines 118-119:

Excel and Python Assignments

May 07, 2019, at 04:42 AM by 45.56.3.173 -
Added lines 256-257:

Python Solution

May 06, 2019, at 01:21 PM by 45.56.3.173 -
Added lines 241-242:

Python Solution 2

May 06, 2019, at 12:51 PM by 45.56.3.173 -
Added lines 239-240:

Python Solution 1

May 03, 2019, at 01:53 PM by 45.56.3.173 -
Added lines 224-225:

Python Solution 3

May 03, 2019, at 01:17 PM by 45.56.3.173 -
Added lines 222-223:

Python Solution 2

May 02, 2019, at 01:56 PM by 45.56.3.173 -
Added lines 220-221:

Python Solution 1

May 02, 2019, at 01:12 PM by 45.56.3.173 -
Added lines 197-198:

Python Solution 4

May 02, 2019, at 12:37 PM by 45.56.3.173 -
Added lines 195-196:

Python Solution 3

May 01, 2019, at 01:37 PM by 45.56.3.173 -
Added lines 193-194:

Python Solution 2

May 01, 2019, at 01:18 PM by 45.56.3.173 -
Added lines 191-192:

Python Solution 1

May 01, 2019, at 11:48 AM by 45.56.3.173 -
Added lines 172-173:

Python Solution 3

April 30, 2019, at 02:27 PM by 45.56.3.173 -
Added lines 168-169:

Python Solution 1

April 29, 2019, at 05:02 PM by 45.56.3.173 -
Added lines 147-148:

Python Solution

April 26, 2019, at 09:46 AM by 49.45.133.240 -
Changed lines 124-126 from:

(:table border=0 frame=hsides width=95%:)

(:cell width=10%:)

to:

(:table border=0 frame=hsides width=100%:)

(:cell width=5%:)

Changed line 131 from:

(:cell width=30%:)

to:

(:cell width=35%:)

April 26, 2019, at 09:46 AM by 49.45.133.240 -
Changed lines 120-122 from:

Excel Assignments

Complete the following assignments with Microsoft Excel, Google Sheets, or another similar spreadsheet program. Microsoft Excel solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment. Python solutions are shown as examples of programming but are not required.

to:

Excel and Python Assignments

Complete the following assignments with Microsoft Excel or Google Sheet (1-6) and Python for (1-17). The first 6 assignments are the same problems but completed with both a Spreadsheet program (Excel or Google Sheets) and Python. Solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment.

April 26, 2019, at 09:43 AM by 49.45.133.240 -
Added lines 137-138:

Google Colab 1

Added lines 154-155:

Google Colab 2

Added lines 173-174:

Google Colab 3

Added lines 196-197:

Google Colab 4

Added lines 211-212:

Google Colab 5

Added lines 224-225:

Google Colab 6

April 26, 2019, at 09:41 AM by 49.45.133.240 -
Deleted line 145:

Python Solutions

Changed lines 163-164 from:

Python Solutions

to:

Python Solution 2

Deleted line 179:

Python Solutions

Deleted line 198:

Python Solutions

Deleted line 209:

Python Solutions

Deleted line 220:

Python Solutions

Changed lines 301-303 from:

Python Solutions 1-2

Python Solution 3

to:

Python Solutions

April 18, 2019, at 04:59 AM by 59.10.106.1 -
Changed lines 126-127 from:

(:cell width=25%:)

to:

(:cell width=10%:) (:cell width=30%:)

Deleted lines 128-129:

(:cell width=35%:) Knowledge Building

Added lines 130-131:

Knowledge Building (:cell width=30%:)

Deleted lines 132-133:
Added lines 134-135:

1 (:cell:)

Deleted lines 146-147:
Added lines 148-149:

2 (:cell:)

Deleted lines 164-165:
Added lines 166-167:

3 (:cell:)

Deleted lines 180-181:
Added lines 182-183:

4 (:cell:)

Added lines 202-203:

5 (:cell:)

Added lines 214-215:

6 (:cell:)

Added lines 226-227:

7 (:cell:)

Added lines 245-246:

8 (:cell:)

Added lines 257-258:

9 (:cell:)

Added lines 273-274:

10 (:cell:)

Added lines 285-286:

11 (:cell:)

Added lines 297-298:

12 (:cell:)

Added lines 309-310:

13 (:cell:)

Added lines 321-322:

14 (:cell:)

Added lines 335-336:

15 (:cell:)

Added lines 347-348:

16 (:cell:)

Added lines 357-358:

17 (:cell:)

April 18, 2019, at 04:53 AM by 59.10.106.1 -
Changed lines 230-236 from:

Solution 1

Solution 2

Solution 3

Soluiton 4

to:

Python Solution 1

Python Solution 2

Python Solution 3

Python Solution 4

April 18, 2019, at 04:52 AM by 59.10.106.1 -
Changed lines 250-251 from:

Google Colab 9(:cell:)

to:

Google Colab 9 (:cell:)

April 18, 2019, at 04:51 AM by 59.10.106.1 -
Changed line 151 from:
to:
Changed lines 199-200 from:

Python Solutions

to:

Python Solutions

Changed lines 209-210 from:

Python Solutions

to:

Python Solutions

Added line 211:
Added line 213:
Changed lines 215-216 from:
to:

Excel Solution 1

Excel Solution 2

Python Solutions

Added lines 221-224:

Assignment #7

Google Colab 7

Added lines 226-228:
Changed lines 230-231 from:
to:

Solution 1

Solution 2

Solution 3

Soluiton 4

Added lines 238-240:

Assignment #8

Google Colab 8

Added lines 242-244:
Changed lines 246-247 from:
to:

Python Solutions

Added lines 248-251:

Assignment #9

Google Colab 9(:cell:) Generate Plots

Changed lines 253-255 from:

(:cell:)

to:

Python Solution 1

Python Solution 2

Python Solution 3

Python Solution 4

Added lines 261-263:

Assignment #10

Google Colab 10

Added line 265:

Temperature Control Lab

Changed lines 267-268 from:
to:

Python Solution 1

Python Solution 2

Added lines 271-273:

Assignment #11

Google Colab 11

Added line 275:
Changed lines 277-278 from:
to:

Python Solutions 1-5

Python Solution 6

Added lines 281-283:

Assignment #12

Google Colab 12

Added line 285:
Changed lines 287-288 from:
to:

Python Solutions 1-2

Python Solution 3

Added lines 291-293:

Assignment #13

Google Colab 13

Added line 295:

Classes (collections of values and functions)

Changed lines 297-298 from:
to:

Python Solutions 1

Python Solutions 2

Added lines 301-303:

Assignment #14

Google Colab 14

Added line 305:
Changed lines 307-308 from:
to:

Python Solutions 1-2

Python Solution 3

Python Solution 4

Added lines 313-315:

Assignment #15

Google Colab 15

Added line 317:
Changed lines 319-320 from:
to:

Python Solution 1

Python Solutions 2-4

Added lines 323-325:

Assignment #16

Google Colab 16

Added line 327:
Changed lines 329-330 from:
to:

Python Solution

Added lines 331-333:

Assignment #17

Google Colab 17

Added lines 335-337:

Symbolic Derivatives

Integrals

Changed lines 339-360 from:

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

to:

Python Solution

Deleted lines 340-1144:

(:div id=hw1_2:) (:source lang=python:)

  1. constants

L = 2 # m Tplate = 343 # K v = 1.45 # m/s Twater = 294 # K mu = 9.79e-4 # Pa*s rho = 998 # kg/m^3 k = 0.601 # W/m-K cp = 4.18e3 # J/kg-K

  1. derived quantities

Re = rho*L*v/mu Pr = mu*cp/k Nu = 0.332 * Pr**(1.0/3.0) * Re**(1.0/2.0) h = Nu * k / L q = h * (Tplate-Twater)

print('Rate of Heat Transfer') print(str(q)+' W/m^2') (:sourceend:) (:divend:)

  • (:toggle hide hw1_3 button show="Solution 3 (Python)":)

(:div id=hw1_3:)

(:source lang=python:) import numpy as np import matplotlib.pyplot as plt

  1. calculate initial moles of N2

T = 298.15 # K P = 1.25 # atm V = 4000 # L Rg = 0.0821 # L*atm/mol/K n_N2 = P*V/(Rg*T) # moles of N2 n_N2 = n_N2 * 0.25 # moles with 25% remaining

  1. calculate N2 pressure at different V and T

n = 20 # grid points V = np.linspace(500,1000,n) T = np.linspace(100,600,n)

  1. create meshgrid

Vm,Tm = np.meshgrid(V,T)

  1. calculate pressure

Pm = n_N2 * Rg * Tm / Vm

  1. plot results

plt.figure() plt.contourf(Vm,Tm,Pm,cmap='RdBu_r') plt.colorbar() CS2 = plt.contour(Vm,Tm,Pm,[1.0,2.5],colors='k') plt.clabel(CS2, inline=1, fontsize=10) plt.xlabel('Volume (L)') plt.ylabel('Temperature (K)') plt.show() (:sourceend:) (:divend:)

(:div id=hw2_1:) (:source lang=python:) import pandas as pd import matplotlib.pyplot as plt import numpy as np

  1. import April 2018 data or get new data from finance.yahoo.com

appl = pd.read_csv('https://apmonitor.com/che263/uploads/Main/AAPL.csv') goog = pd.read_csv('https://apmonitor.com/che263/uploads/Main/GOOG.csv')

  1. xom = pd.read_csv('https://apmonitor.com/che263/uploads/Main/XOM.csv')
  2. create dictionary of stocks

s = dict([('Apple',appl),('Google',goog)]) #,('ExxonMobil',xom)])

  1. print column headers and starting rows (5 is default)

print('Apple Data') print(s['Apple'].head())

  1. print column headers and ending close price (4 rows)

print('Google Data') print(s['Google']['Close'].tail(4))

  1. basic data statistics

for i in s:

    print('Stock: ' + i)
    print(' max   : ' + str(max(s[i]['Close'])))
    print(' min   : ' + str(min(s[i]['Close'])))
    print(' stdev : ' + str(np.std(s[i]['Close'])))
    print(' avg   : ' + str(np.mean(s[i]['Close'])))
    print(' median: ' + str(np.median(s[i]['Close'])))
  1. plot data

plt.figure() sty = dict([('Apple','r--'),('Google','b:'),('ExxonMobil','k-')]) ni = 0 for i in s:

    mc = max(s[i]['Close'])
    plt.plot(s[i]['Date'],s[i]['Close']/mc,sty[i],linewidth=3,label=i)
    plt.plot(s[i]['Date'],s[i]['High']/mc,sty[i],linewidth=1)
    plt.plot(s[i]['Date'],s[i]['Low']/mc,sty[i],linewidth=1)

plt.xticks(rotation=90) plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw2_2 button show="Solution 2 (Python)":)

(:div id=hw2_2:) (:source lang=python:) import pandas as pd import matplotlib.pyplot as plt

  1. import data
  2. Time (sec), Heater 1, Heater 2, Temperature 1, Temperature 2

x = pd.read_csv('https://apmonitor.com/che263/uploads/Main/tclab.txt')

  1. print column headers and starting 10 rows (5 is default)

print('Data') print(x.head(10))

  1. plot data

plt.figure() plt.subplot(2,1,1) plt.title('Temperature Control Lab') plt.plot(x['Time (sec)'],x['Temperature 1'],'r--') plt.plot(x['Time (sec)'],x['Temperature 2'],'b-') plt.ylabel('Temp (degC)') plt.legend(loc='best')

plt.subplot(2,1,2) plt.plot(x['Time (sec)'],x['Heater 1'],'r--') plt.plot(x['Time (sec)'],x['Heater 2'],'b-') plt.ylabel('Heater (%)') plt.xlabel('Time (sec)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw2_3 button show="Solution 3 (Python)":)

(:div id=hw2_3:) (:source lang=python:) import math as m

  1. part a

help(m.cos) y = m.cos(0.5) print('cos(0.5): ' + str(y))

  1. part b

y = m.sin(30.0*(m.pi/180.0)) print('sin(30 deg): ' + str(y))

  1. part c

y = m.tan(m.pi/2.0) print('tan(pi/x): ' + str(y))

  1. part d

x = 5.0 y = max(2.0*m.sqrt(x),(x**2)/2.0, (x**3)/3.0,(x**2+x**3)/5.0) print('max value: ' + str(y))

  1. part e

x = 25 y = m.factorial(x) print('25!: ' + str(y))

  1. part f

x = 0.5

  1. if..else statement

if x<1.0:

    y = x**2

else:

    y = m.sin(m.pi*x/2.0)
  1. same but one line

y = x**2 if x<1.0 else m.sin(m.pi*x/2.0) print('if statement result: ' + str(y))

  1. part g

x = 4.999 y = m.floor(x) print('floor(4.999): ' + str(y)) (:sourceend:) (:divend:)

(:div id=hw3_1:) (:source lang=python:)

  1. method #1: NumPy

from numpy.linalg import solve A = b = [45.0, 30.0, 15.0, 20.0, 92.0] x = solve(A,b) print('NumPy Solution') print(x)

  1. method #2: Gekko

from gekko import GEKKO m = GEKKO() x1,x2,x3,x4,x5 = [m.Var() for i in range(5)] m.Equation(11*x1+3*x2+x4+2*x5==45) m.Equation(4*x2+2*x3+x5==30) m.Equation(3*x1+2*x2+7*x3+x4==15) m.Equation(4*x1+4*x3+10*x4+x5==20) m.Equation(2*x1+5*x2+x3+3*x4+14*x5==92) m.solve(disp=False) print('Gekko Solution') print(x1.value) print(x2.value) print(x3.value) print(x4.value) print(x5.value) (:sourceend:) (:divend:)

  • (:toggle hide hw3_2 button show="Solution 2 (Python)":)

(:div id=hw3_2:) (:source lang=python:)

  1. method #1: NumPy

from scipy.optimize import fsolve def f(z):

    x,y=z
    f1 = 2*x**2+y**2-1
    f2 = (0.5*x-0.5)**2+2.0*(y-0.25)**2-1
    return [f1,f2]

x,y = fsolve(f,[1,1]) print('NumPy Solution') print(x,y)

  1. method #2: Gekko

from gekko import GEKKO m = GEKKO() x,y = [m.Var(value=1) for i in range(2)] m.Equation(2*x**2+y**2==1) m.Equation((0.5*x-0.5)**2+2.0*(y-0.25)**2==1) m.solve(disp=False) print('Gekko Solution') print(x.value) print(y.value) (:sourceend:) (:divend:)

  • (:toggle hide hw3_3 button show="Solution 3 (Python)":)

(:div id=hw3_3:) (:source lang=python:) import numpy as np from scipy.optimize import fsolve

  1. constants

TC = 77 # degC P = 1.0 # bar a = 2.877e8 # cm^6 bar K^0.5 / mol^2 b = 60.211 # cm^3 / mol Rg = 83.144598 # cm^3 bar / K-mol

  1. derived quantities

TK = TC+273.15 # K

  1. method #1: NumPy

def f(V):

    return P - Rg*TK/(V-b)+a/(np.sqrt(TK)*V*(V+b))

V_liq = fsolve(f,82) # Liquid root V_vap = fsolve(f,28600) # Vapor root print('NumPy Solution') print(V_liq,V_vap)

  1. method #2: Gekko

from gekko import GEKKO m = GEKKO() V = m.Var(value=[82,28600]) m.Equation(P==Rg*TK/(V-b)-a/(m.sqrt(TK)*V*(V+b))) m.options.IMODE=2 m.solve(disp=False) print('Gekko Solution') print(V.value) (:sourceend:) (:divend:)

  • (:toggle hide hw3_4 button show="Solution 4 (Python)":)

(:div id=hw3_4:) (:source lang=python:) from gekko import GEKKO

  1. constants

y1 = 0.33 y2 = 1.0-y1 P = 120.0 # kPa

  1. Antoine constants
  2. Benzene

ac1 = [13.7819, 2726.81, 217.572]

  1. Toluene

ac2 = [13.9320, 3056.96, 217.625]

  1. gekko model

m = GEKKO() T = m.Var(value=100) x1,x2 = [m.Var(value=0.5,lb=0,ub=1) for i in range(2)]

  1. vapor pressure

Psat1 = m.Intermediate(m.exp(ac1[0]-ac1[1]/(T+ac1[2]))) Psat2 = m.Intermediate(m.exp(ac2[0]-ac2[1]/(T+ac2[2])))

  1. Raoult's law

m.Equation(y1*P==x1*Psat1) m.Equation(y2*P==x2*Psat2) m.Equation(x1+x2==1) m.options.IMODE=1 m.solve(disp=False) print('Gekko Solution') print('x1: ' + str(x1.value)) print('x2: ' + str(x2.value)) print('T: ' + str(T.value)) (:sourceend:) (:divend:)

(:div id=hw4_1a:) (:source lang=python:) import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from sklearn.metrics import r2_score

  1. import data
  2. Time (sec),Heart Rate (BPM)

url = 'https://apmonitor.com/che263/uploads/Main/heart_rate.txt' x = pd.read_csv(url)

  1. print first rows

print('Data') print(x.head())

  1. extract vectors

t = x['Time (sec)'].values ym = x['Heart Rate (BPM)'].values

  1. define function for fitting

def bpm(t,c0,c1,c2,c3):

    return c0+c1*t-c2*np.exp(-c3*t)
  1. find optimal parameters

p0 = [100,0.01,100,0.01] # initial guesses c,cov = curve_fit(bpm,t,ym,p0) # fit model

  1. print parameters

print('Optimal parameters') print(c)

  1. calculate prediction

yp = bpm(t,c[0],c[1],c[2],c[3])

  1. calculate r^2

print('R^2: ' + str(r2_score(ym,yp)))

  1. plot data and prediction

plt.figure() plt.title('Heart Rate Regression') plt.plot(t/60.0,ym,'r--',label='Measured') plt.plot(t/60.0,yp,'b-',label='Predicted') plt.ylabel('Rate (BPM)') plt.xlabel('Time (min)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw4_1b button show="Solution 1 (Python GEKKO)":)

(:div id=hw4_1b:) (:source lang=python:) import numpy as np import pandas as pd import matplotlib.pyplot as plt from gekko import GEKKO from sklearn.metrics import r2_score

  1. import data
  2. Time (sec),Heart Rate (BPM)

url = 'https://apmonitor.com/che263/uploads/Main/heart_rate.txt' x = pd.read_csv(url)

  1. print first rows

print('Data') print(x.head())

  1. extract vectors

t = np.array(x['Time (sec)']) ym = np.array(x['Heart Rate (BPM)'])

  1. GEKKO model

m = GEKKO()

  1. parameters

tm = m.Param(value=t) c0 = m.FV(value=100) c1 = m.FV(value=0.01) c2 = m.FV(value=100) c3 = m.FV(value=0.01) c0.STATUS=1 c1.STATUS=1 c2.STATUS=1 c3.STATUS=1

  1. variables

bpm = m.CV(value=ym) bpm.FSTATUS=1

  1. regression equation

m.Equation(bpm==c0+c1*tm-c2*m.exp(-c3*tm))

  1. regression mode

m.options.IMODE = 2

  1. optimize

m.solve()

  1. print parameters

print('Optimal parameters') print(c0.value[0]) print(c1.value[0]) print(c2.value[0]) print(c3.value[0])

  1. calculate r^2

print('R^2: ' + str(r2_score(ym,bpm)))

  1. plot data and prediction

plt.figure() plt.title('Heart Rate Regression') plt.plot(t/60.0,ym,'r--',label='Measured') plt.plot(t/60.0,bpm,'b-',label='Predicted') plt.ylabel('Rate (BPM)') plt.xlabel('Time (min)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw4_2 button show="Solution 2 (Python)":)

(:div id=hw4_2:) (:source lang=python:) import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from sklearn.metrics import r2_score

  1. import data
  2. time (min),y

url = 'https://apmonitor.com/che263/uploads/Main/dynamics.txt' x = pd.read_csv(url)

  1. print first rows

print('Data') print(x.head())

  1. extract vectors

t = x['time (min)'].values ym = x['y'].values

  1. define function for fitting

def yfcn(t,tau,theta):

    n = len(t)
    res = np.zeros(n)
    for i in range(n):
        if i>=theta:
            res[i] = 5.0*(1.0-np.exp(-(t[i]-theta)/tau))
    return res
  1. find optimal parameters

c,cov = curve_fit(yfcn,t,ym)

  1. print parameters

print('Optimal parameters') tau = c[0] theta = c[1] print(c)

  1. calculate prediction

yp = yfcn(t,tau,theta)

  1. calculate r^2

print('R^2: ', r2_score(yp,ym))

  1. plot data and prediciton

plt.figure() plt.title('Step Test Regression') plt.plot(t,ym,'ro',label='Measured') plt.plot(t,yp,'b-',label='Predicted') plt.ylabel('Response') plt.xlabel('Time (min)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw4_3 button show="Solution 3 (Python)":)

(:div id=hw4_3:) (:source lang=python:) import numpy as np import matplotlib.pyplot as plt

  1. generate 1000 random numbers
  2. with Poisson distribution and lambda=1

n = 1000 lam = 1 x = np.random.poisson(lam,n)

  1. count number in each bin

bins=[0,1,2,3,4,5,6] hist, _ = np.histogram(x, bins)

  1. plot histogram data

plt.bar(bins[0:-1],hist,label='1000 samples') plt.xlabel('bin') plt.ylabel('count') plt.title('Poisson Distribution (lambda=1)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

(:div id=hw5_1ab:) (:source lang=python:) import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO from scipy.integrate import odeint

  1. number of time points

n = 15

  1. final time

tf = 7.0

  1. initial concentration

Ca0 = 5.0

  1. constants

k = 1 # 1/s

  1. method #1 Analytical solution
  2. Ca(t) = Ca(0) * exp(-k*t)

t = np.linspace(0,tf,n) Ca_m1 = Ca0 * np.exp(-k*t)

  1. method #2 Euler's method

Ca_m2 = np.empty(n) Ca_m2[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t[i] - t[i-1]
    Ca_m2[i] = Ca_m2[i-1] - k * Ca_m2[i-1] * dt
  1. method #3: GEKKO solution
  2. create new gekko model

m = GEKKO()

  1. integration time points

m.time = t

  1. variables

Ca = m.Var(value=Ca0)

  1. differential equation

m.Equation(Ca.dt()==-k*Ca)

  1. set options

m.options.IMODE = 4 # dynamic simulation m.options.NODES = 3 # collocation nodes

  1. simulate ODE

m.solve()

  1. method #4: ODEINT from SciPy

def dCadt(t,Ca):

    return -k * Ca

Ca_m4 = odeint(dCadt,t,Ca0)

  1. plot results

plt.figure(1) plt.plot(t,Ca_m1,'r-',label='Ca (Analytical)') plt.plot(t,Ca_m2,'ko',label='Ca (Euler)') plt.plot(t,Ca,'b--',label='Ca (GEKKO)') plt.plot(t,Ca,'ys',label='Ca (ODEINT)') plt.xlabel('Time (sec)') plt.ylabel(r'$C_a (kmol/m^3)$') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw5_1c button show="Solution 1c (Python)":)

(:div id=hw5_1c:) (:source lang=python:) import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO from scipy.integrate import odeint

  1. number of time points

n = 15

  1. final time

tf = 7.0

  1. initial concentration

Ca0 = 5.0

  1. constants

k = 1 # 1/s

  1. method #1 Analytical solution
  2. Ca(t) = Ca(0) * exp(-k*t)

t = np.linspace(0,tf,n) Ca_m1 = Ca0 * np.exp(-k*t)

  1. method #2 Euler's method

t2 = np.arange(0,tf,0.5) n = len(t2) Ca_m2 = np.empty_like(t2) Ca_m2[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t2[i] - t2[i-1]
    Ca_m2[i] = Ca_m2[i-1] - k * Ca_m2[i-1] * dt

t3 = np.arange(0,tf,1.5) n = len(t3) Ca_m3 = np.empty_like(t3) Ca_m3[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t3[i] - t3[i-1]
    Ca_m3[i] = Ca_m3[i-1] - k * Ca_m3[i-1] * dt

t4 = np.arange(0,tf,2.1) n = len(t4) Ca_m4 = np.empty_like(t4) Ca_m4[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t4[i] - t4[i-1]
    Ca_m4[i] = Ca_m4[i-1] - k * Ca_m4[i-1] * dt
  1. plot results

plt.figure(1) plt.plot(t,Ca_m1,'r-',label='Ca (Analytical)') plt.plot(t2,Ca_m2,'k.-',label='Ca (Euler 0.5)') plt.plot(t3,Ca_m3,'bo-',label='Ca (Euler 1.5)') plt.plot(t4,Ca_m4,'y--',label='Ca (Euler 2.1)') plt.xlabel('Time (sec)') plt.ylabel(r'$C_a (kmol/m^3)$') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

  • (:toggle hide hw5_2 button show="Solution 2 (Python)":)

(:div id=hw5_2:) (:source lang=python:) import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO

  1. final time

tf = 3.0

  1. constants

k1 = 1.0 # L/mol-s k2 = 1.5 # L/mol-s

  1. GEKKO solution
  2. create new gekko model

m = GEKKO()

  1. integration time points

m.time = np.arange(0,tf+0.01,0.2)

  1. variables

Ca = m.Var(value=1.0) Cb = m.Var(value=1.0) Cc = m.Var(value=0.0) Cd = m.Var(value=0.0) S = m.Var(value=1.0)

  1. differential equations

m.Equation(Ca.dt()==-k1*Ca*Cb) m.Equation(Cb.dt()==-k1*Ca*Cb-k2*Cb*Cc) m.Equation(Cc.dt()== k1*Ca*Cb-k2*Cb*Cc) m.Equation(Cd.dt()== k2*Cb*Cc) m.Equation(S==Cc/(Cc+Cd))

  1. set options

m.options.IMODE = 4 # dynamic simulation m.options.NODES = 3 # collocation nodes

  1. simulate ODE

m.solve()

  1. plot results

plt.figure(1) plt.subplot(2,1,1) plt.plot(m.time,Ca,'r-',label='Ca',linewidth=2.0) plt.plot(m.time,Cb,'k.-',label='Cb',linewidth=2.0) plt.plot(m.time,Cc,'b--',label='Cc',linewidth=2.0) plt.plot(m.time,Cd,'y:',label='Cd',linewidth=3.0) plt.ylabel('Conc (mol/L)') plt.legend(loc='best')

plt.subplot(2,1,2) plt.plot(m.time,S,'k-',label='Selectivity',linewidth=2.0) plt.xlabel('Time (sec)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

(:div id=hw6_2:) (:source lang=python:) import numpy as np

r = 5 # m h = 10 # m F = 15 # m^3/min t = 180 # min

V_tank = np.pi * r**2 * h # m^3 V_crude_oil = F * t # m^3

if V_crude_oil > V_tank:

    print('Tank Overfilled by '           + str(V_crude_oil-V_tank) + ' m^3')

else:

    print('Not Overfilled') 

(:sourceend:) (:divend:)

Python Assignments

MathCAD Assignments

April 18, 2019, at 04:31 AM by 59.10.106.1 -
Added line 133:
Changed lines 141-171 from:

Excel Solution 2

Excel Solution 3

Python CL1

  • (:toggle hide hw1_2 button show="Solution 2 (Python)":)

(:div id=hw1_2:) (:source lang=python:)

  1. constants

L = 2 # m Tplate = 343 # K v = 1.45 # m/s Twater = 294 # K mu = 9.79e-4 # Pa*s rho = 998 # kg/m^3 k = 0.601 # W/m-K cp = 4.18e3 # J/kg-K

  1. derived quantities

Re = rho*L*v/mu Pr = mu*cp/k Nu = 0.332 * Pr**(1.0/3.0) * Re**(1.0/2.0) h = Nu * k / L q = h * (Tplate-Twater)

print('Rate of Heat Transfer') print(str(q)+' W/m^2') (:sourceend:) (:divend:)

to:

Excel Solution 2

Excel Solution 3

Python Solutions

Added lines 149-151:
Added lines 153-155:
Changed lines 157-165 from:
to:

Excel Solution 1

Excel Solution 2

Excel Solution 3

Python Solutions

Added line 167:
Added line 169:
Changed lines 171-291 from:
to:

Excel Solution 1

Excel Solution 2

Excel Solution 3

Excel Solution 4

Python Solutions

(:cellnr:) Assignment #4

Excel Template

HR Data

Dynamic Data (:cell:) Data Regression (:cell:) Excel Solution 1

Excel Solution 2

Excel Solution 3

Python Solutions

(:cellnr:) Assignment #5 (:cell:) Differential Equation Solution (:cell:) Excel Solution 1

Excel Solution 2

Python Solutions

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

Added lines 293-295:
April 18, 2019, at 04:21 AM by 59.10.106.1 -
Added lines 145-169:
  • (:toggle hide hw1_2 button show="Solution 2 (Python)":)

(:div id=hw1_2:) (:source lang=python:)

  1. constants

L = 2 # m Tplate = 343 # K v = 1.45 # m/s Twater = 294 # K mu = 9.79e-4 # Pa*s rho = 998 # kg/m^3 k = 0.601 # W/m-K cp = 4.18e3 # J/kg-K

  1. derived quantities

Re = rho*L*v/mu Pr = mu*cp/k Nu = 0.332 * Pr**(1.0/3.0) * Re**(1.0/2.0) h = Nu * k / L q = h * (Tplate-Twater)

print('Rate of Heat Transfer') print(str(q)+' W/m^2') (:sourceend:) (:divend:)

April 18, 2019, at 04:20 AM by 59.10.106.1 -
Changed lines 136-137 from:
to:
Changed lines 140-142 from:
  • Excel Solution 2
  • Excel Solution 3
  • Python CL1
to:

Excel Solution 2

Excel Solution 3

Python CL1

April 18, 2019, at 04:19 AM by 59.10.106.1 -
Added lines 5-119:

(:html:) <style type="text/css"> div.table-title {

   display: block;
  margin: auto;
  max-width: 600px;
  padding:5px;
  width: 100%;

}

.table-title h3 {

   color: #fafafa;

}

.table-fill {

  background: white;
  border-radius:3px;
  border-collapse: collapse;
  height: 320px;
  margin: auto;
  max-width: 600px;
  padding:5px;
  width: 100%;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  animation: float 5s infinite;

}

th {

  color:#D5DDE5;;
  background:#1b1e24;
  border-bottom:4px solid #9ea7af;
  border-right: 1px solid #343a45;
  text-align:left;
  vertical-align:middle;

}

th:first-child {

  border-top-left-radius:3px;

}

th:last-child {

  border-top-right-radius:3px;
  border-right:none;

}

tr {

  border-top: 1px solid #C1C3D1;
  border-bottom-: 1px solid #C1C3D1;
  color:#666B85;
  font-weight:normal;

}

tr:hover td {

  border-top: 1px solid #22262e;
  border-bottom: 1px solid #22262e;

}

tr:first-child {

  border-top:none;

}

tr:last-child {

  border-bottom:none;

}

tr:nth-child(odd) td {

  background:#EEEEEE;

}

tr:last-child td:first-child {

  border-bottom-left-radius:3px;

}

tr:last-child td:last-child {

  border-bottom-right-radius:3px;

}

td {

  background:#FFFFFF;
  padding:5px;
  text-align:left;
  vertical-align:middle;
  border-right: 1px solid #C1C3D1;

}

td:last-child {

  border-right: 0px;

}

th.text-left {

  text-align: left;

}

th.text-center {

  text-align: center;

}

th.text-right {

  text-align: right;

}

td.text-left {

  text-align: left;

}

td.text-center {

  text-align: center;

}

td.text-right {

  text-align: right;

} </style> (:htmlend:)

Added lines 123-154:

(:table border=0 frame=hsides width=95%:)

(:cell width=25%:) Assignment (:cell width=35%:) Knowledge Building (:cell width=30%:) Solutions

(:cellnr:) Assignment #1 (:cell:)

(:cell:)

  • Excel Solution 2
  • Excel Solution 3
  • Python CL1

(:cellnr:) (:cell:) (:cell:)

(:cellnr:) (:cell:) (:cell:)

(:tableend:)

April 17, 2019, at 03:18 AM by 101.53.21.242 -
Changed line 297 from:
  • (:toggle hide hw3_4 button show="Solution 3 (Python)":)
to:
  • (:toggle hide hw3_4 button show="Solution 4 (Python)":)
May 25, 2018, at 06:01 AM by 45.56.3.173 -
Changed lines 765-766 from:
  • Solutions (1-5), Solution 6
to:
  • Solutions 1-5, Solution 6
Changed line 769 from:
  • Solutions
to:
  • Solutions 1-2, Solution 3
May 21, 2018, at 05:15 PM by 184.254.134.139 -
Changed line 761 from:
  • Solution 2
to:
  • Solution 1, Solution 2
May 17, 2018, at 02:15 PM by 45.56.3.173 -
Changed lines 760-761 from:
to:
  • Temperature Control Lab
  • Solution 2
May 08, 2018, at 02:44 PM by 45.56.3.173 -
Added line 336:
  • Python Solution 1
May 08, 2018, at 02:42 PM by 45.56.3.173 -
Changed line 376 from:
  1. plot data and prediciton
to:
  1. plot data and prediction
Changed line 446 from:
  1. plot data and prediciton
to:
  1. plot data and prediction
May 07, 2018, at 02:53 PM by 45.56.3.173 -
Changed line 7 from:

Complete the following assignments with Microsoft Excel, Google Sheets, or another similar spreadsheet program. Microsoft Excel solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment. Python solutions are shown as a reference and introduction to programming but are not required.

to:

Complete the following assignments with Microsoft Excel, Google Sheets, or another similar spreadsheet program. Microsoft Excel solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment. Python solutions are shown as examples of programming but are not required.

May 07, 2018, at 02:51 PM by 45.56.3.173 -
Deleted lines 720-725:
  • (:toggle hide hw6_1 button show="Solution 1 (Python)":)

(:div id=hw6_1:) (:source lang=python:)

(:sourceend:) (:divend:)

May 07, 2018, at 02:50 PM by 45.56.3.173 -
Changed lines 300-329 from:
to:

from gekko import GEKKO

  1. constants

y1 = 0.33 y2 = 1.0-y1 P = 120.0 # kPa

  1. Antoine constants
  2. Benzene

ac1 = [13.7819, 2726.81, 217.572]

  1. Toluene

ac2 = [13.9320, 3056.96, 217.625]

  1. gekko model

m = GEKKO() T = m.Var(value=100) x1,x2 = [m.Var(value=0.5,lb=0,ub=1) for i in range(2)]

  1. vapor pressure

Psat1 = m.Intermediate(m.exp(ac1[0]-ac1[1]/(T+ac1[2]))) Psat2 = m.Intermediate(m.exp(ac2[0]-ac2[1]/(T+ac2[2])))

  1. Raoult's law

m.Equation(y1*P==x1*Psat1) m.Equation(y2*P==x2*Psat2) m.Equation(x1+x2==1) m.options.IMODE=1 m.solve(disp=False) print('Gekko Solution') print('x1: ' + str(x1.value)) print('x2: ' + str(x2.value)) print('T: ' + str(T.value))

Changed lines 336-337 from:
  • (:toggle hide hw4_1 button show="Solution 1 (Python)":)

(:div id=hw4_1:)

to:
  • (:toggle hide hw4_1a button show="Solution 1 (Python curve_fit)":)

(:div id=hw4_1a:)

Changed lines 339-384 from:
to:

import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from sklearn.metrics import r2_score

  1. import data
  2. Time (sec),Heart Rate (BPM)

url = 'https://apmonitor.com/che263/uploads/Main/heart_rate.txt' x = pd.read_csv(url)

  1. print first rows

print('Data') print(x.head())

  1. extract vectors

t = x['Time (sec)'].values ym = x['Heart Rate (BPM)'].values

  1. define function for fitting

def bpm(t,c0,c1,c2,c3):

    return c0+c1*t-c2*np.exp(-c3*t)
  1. find optimal parameters

p0 = [100,0.01,100,0.01] # initial guesses c,cov = curve_fit(bpm,t,ym,p0) # fit model

  1. print parameters

print('Optimal parameters') print(c)

  1. calculate prediction

yp = bpm(t,c[0],c[1],c[2],c[3])

  1. calculate r^2

print('R^2: ' + str(r2_score(ym,yp)))

  1. plot data and prediciton

plt.figure() plt.title('Heart Rate Regression') plt.plot(t/60.0,ym,'r--',label='Measured') plt.plot(t/60.0,yp,'b-',label='Predicted') plt.ylabel('Rate (BPM)') plt.xlabel('Time (min)') plt.legend(loc='best') plt.show()

Changed lines 387-388 from:
  • (:toggle hide hw4_2 button show="Solution 2 (Python)":)

(:div id=hw4_2:)

to:
  • (:toggle hide hw4_1b button show="Solution 1 (Python GEKKO)":)

(:div id=hw4_1b:)

Changed lines 390-454 from:
to:

import numpy as np import pandas as pd import matplotlib.pyplot as plt from gekko import GEKKO from sklearn.metrics import r2_score

  1. import data
  2. Time (sec),Heart Rate (BPM)

url = 'https://apmonitor.com/che263/uploads/Main/heart_rate.txt' x = pd.read_csv(url)

  1. print first rows

print('Data') print(x.head())

  1. extract vectors

t = np.array(x['Time (sec)']) ym = np.array(x['Heart Rate (BPM)'])

  1. GEKKO model

m = GEKKO()

  1. parameters

tm = m.Param(value=t) c0 = m.FV(value=100) c1 = m.FV(value=0.01) c2 = m.FV(value=100) c3 = m.FV(value=0.01) c0.STATUS=1 c1.STATUS=1 c2.STATUS=1 c3.STATUS=1

  1. variables

bpm = m.CV(value=ym) bpm.FSTATUS=1

  1. regression equation

m.Equation(bpm==c0+c1*tm-c2*m.exp(-c3*tm))

  1. regression mode

m.options.IMODE = 2

  1. optimize

m.solve()

  1. print parameters

print('Optimal parameters') print(c0.value[0]) print(c1.value[0]) print(c2.value[0]) print(c3.value[0])

  1. calculate r^2

print('R^2: ' + str(r2_score(ym,bpm)))

  1. plot data and prediciton

plt.figure() plt.title('Heart Rate Regression') plt.plot(t/60.0,ym,'r--',label='Measured') plt.plot(t/60.0,bpm,'b-',label='Predicted') plt.ylabel('Rate (BPM)') plt.xlabel('Time (min)') plt.legend(loc='best') plt.show()

Changed lines 457-458 from:
  • (:toggle hide hw4_3 button show="Solution 3 (Python)":)

(:div id=hw4_3:)

to:
  • (:toggle hide hw4_2 button show="Solution 2 (Python)":)

(:div id=hw4_2:)

Changed lines 460-511 from:
to:

import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit from sklearn.metrics import r2_score

  1. import data
  2. time (min),y

url = 'https://apmonitor.com/che263/uploads/Main/dynamics.txt' x = pd.read_csv(url)

  1. print first rows

print('Data') print(x.head())

  1. extract vectors

t = x['time (min)'].values ym = x['y'].values

  1. define function for fitting

def yfcn(t,tau,theta):

    n = len(t)
    res = np.zeros(n)
    for i in range(n):
        if i>=theta:
            res[i] = 5.0*(1.0-np.exp(-(t[i]-theta)/tau))
    return res
  1. find optimal parameters

c,cov = curve_fit(yfcn,t,ym)

  1. print parameters

print('Optimal parameters') tau = c[0] theta = c[1] print(c)

  1. calculate prediction

yp = yfcn(t,tau,theta)

  1. calculate r^2

print('R^2: ', r2_score(yp,ym))

  1. plot data and prediciton

plt.figure() plt.title('Step Test Regression') plt.plot(t,ym,'ro',label='Measured') plt.plot(t,yp,'b-',label='Predicted') plt.ylabel('Response') plt.xlabel('Time (min)') plt.legend(loc='best') plt.show()

Changed lines 514-519 from:

(:div id=hw5_1:)

to:
  • (:toggle hide hw4_3 button show="Solution 3 (Python)":)

(:div id=hw4_3:)

Changed lines 517-536 from:
to:

import numpy as np import matplotlib.pyplot as plt

  1. generate 1000 random numbers
  2. with Poisson distribution and lambda=1

n = 1000 lam = 1 x = np.random.poisson(lam,n)

  1. count number in each bin

bins=[0,1,2,3,4,5,6] hist, _ = np.histogram(x, bins)

  1. plot histogram data

plt.bar(bins[0:-1],hist,label='1000 samples') plt.xlabel('bin') plt.ylabel('count') plt.title('Poisson Distribution (lambda=1)') plt.legend(loc='best') plt.show()

Changed lines 539-540 from:
  • (:toggle hide hw5_2 button show="Solution 2 (Python)":)

(:div id=hw5_2:)

to:

(:div id=hw5_1ab:)

Changed lines 546-601 from:
to:

import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO from scipy.integrate import odeint

  1. number of time points

n = 15

  1. final time

tf = 7.0

  1. initial concentration

Ca0 = 5.0

  1. constants

k = 1 # 1/s

  1. method #1 Analytical solution
  2. Ca(t) = Ca(0) * exp(-k*t)

t = np.linspace(0,tf,n) Ca_m1 = Ca0 * np.exp(-k*t)

  1. method #2 Euler's method

Ca_m2 = np.empty(n) Ca_m2[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t[i] - t[i-1]
    Ca_m2[i] = Ca_m2[i-1] - k * Ca_m2[i-1] * dt
  1. method #3: GEKKO solution
  2. create new gekko model

m = GEKKO()

  1. integration time points

m.time = t

  1. variables

Ca = m.Var(value=Ca0)

  1. differential equation

m.Equation(Ca.dt()==-k*Ca)

  1. set options

m.options.IMODE = 4 # dynamic simulation m.options.NODES = 3 # collocation nodes

  1. simulate ODE

m.solve()

  1. method #4: ODEINT from SciPy

def dCadt(t,Ca):

    return -k * Ca

Ca_m4 = odeint(dCadt,t,Ca0)

  1. plot results

plt.figure(1) plt.plot(t,Ca_m1,'r-',label='Ca (Analytical)') plt.plot(t,Ca_m2,'ko',label='Ca (Euler)') plt.plot(t,Ca,'b--',label='Ca (GEKKO)') plt.plot(t,Ca,'ys',label='Ca (ODEINT)') plt.xlabel('Time (sec)') plt.ylabel(r'$C_a (kmol/m^3)$') plt.legend(loc='best') plt.show()

Changed lines 604-609 from:

(:div id=hw6_1:)

to:
  • (:toggle hide hw5_1c button show="Solution 1c (Python)":)

(:div id=hw5_1c:)

Changed lines 607-660 from:
to:

import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO from scipy.integrate import odeint

  1. number of time points

n = 15

  1. final time

tf = 7.0

  1. initial concentration

Ca0 = 5.0

  1. constants

k = 1 # 1/s

  1. method #1 Analytical solution
  2. Ca(t) = Ca(0) * exp(-k*t)

t = np.linspace(0,tf,n) Ca_m1 = Ca0 * np.exp(-k*t)

  1. method #2 Euler's method

t2 = np.arange(0,tf,0.5) n = len(t2) Ca_m2 = np.empty_like(t2) Ca_m2[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t2[i] - t2[i-1]
    Ca_m2[i] = Ca_m2[i-1] - k * Ca_m2[i-1] * dt

t3 = np.arange(0,tf,1.5) n = len(t3) Ca_m3 = np.empty_like(t3) Ca_m3[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t3[i] - t3[i-1]
    Ca_m3[i] = Ca_m3[i-1] - k * Ca_m3[i-1] * dt

t4 = np.arange(0,tf,2.1) n = len(t4) Ca_m4 = np.empty_like(t4) Ca_m4[0] = Ca0 # kmol/m^3 for i in range(1,n):

    dt = t4[i] - t4[i-1]
    Ca_m4[i] = Ca_m4[i-1] - k * Ca_m4[i-1] * dt
  1. plot results

plt.figure(1) plt.plot(t,Ca_m1,'r-',label='Ca (Analytical)') plt.plot(t2,Ca_m2,'k.-',label='Ca (Euler 0.5)') plt.plot(t3,Ca_m3,'bo-',label='Ca (Euler 1.5)') plt.plot(t4,Ca_m4,'y--',label='Ca (Euler 2.1)') plt.xlabel('Time (sec)') plt.ylabel(r'$C_a (kmol/m^3)$') plt.legend(loc='best') plt.show()

Changed lines 663-664 from:
  • (:toggle hide hw6_2 button show="Solution 2 (Python)":)

(:div id=hw6_2:)

to:
  • (:toggle hide hw5_2 button show="Solution 2 (Python)":)

(:div id=hw5_2:)

Changed lines 666-744 from:
to:

import numpy as np import matplotlib.pyplot as plt from gekko import GEKKO

  1. final time

tf = 3.0

  1. constants

k1 = 1.0 # L/mol-s k2 = 1.5 # L/mol-s

  1. GEKKO solution
  2. create new gekko model

m = GEKKO()

  1. integration time points

m.time = np.arange(0,tf+0.01,0.2)

  1. variables

Ca = m.Var(value=1.0) Cb = m.Var(value=1.0) Cc = m.Var(value=0.0) Cd = m.Var(value=0.0) S = m.Var(value=1.0)

  1. differential equations

m.Equation(Ca.dt()==-k1*Ca*Cb) m.Equation(Cb.dt()==-k1*Ca*Cb-k2*Cb*Cc) m.Equation(Cc.dt()== k1*Ca*Cb-k2*Cb*Cc) m.Equation(Cd.dt()== k2*Cb*Cc) m.Equation(S==Cc/(Cc+Cd))

  1. set options

m.options.IMODE = 4 # dynamic simulation m.options.NODES = 3 # collocation nodes

  1. simulate ODE

m.solve()

  1. plot results

plt.figure(1) plt.subplot(2,1,1) plt.plot(m.time,Ca,'r-',label='Ca',linewidth=2.0) plt.plot(m.time,Cb,'k.-',label='Cb',linewidth=2.0) plt.plot(m.time,Cc,'b--',label='Cc',linewidth=2.0) plt.plot(m.time,Cd,'y:',label='Cd',linewidth=3.0) plt.ylabel('Conc (mol/L)') plt.legend(loc='best')

plt.subplot(2,1,2) plt.plot(m.time,S,'k-',label='Selectivity',linewidth=2.0) plt.xlabel('Time (sec)') plt.legend(loc='best') plt.show() (:sourceend:) (:divend:)

(:div id=hw6_1:) (:source lang=python:)

(:sourceend:) (:divend:)

  • (:toggle hide hw6_2 button show="Solution 2 (Python)":)

(:div id=hw6_2:) (:source lang=python:) import numpy as np

r = 5 # m h = 10 # m F = 15 # m^3/min t = 180 # min

V_tank = np.pi * r**2 * h # m^3 V_crude_oil = F * t # m^3

if V_crude_oil > V_tank:

    print('Tank Overfilled by '           + str(V_crude_oil-V_tank) + ' m^3')

else:

    print('Not Overfilled') 
May 07, 2018, at 02:45 PM by 45.56.3.173 -
Changed lines 266-294 from:
to:

import numpy as np from scipy.optimize import fsolve

  1. constants

TC = 77 # degC P = 1.0 # bar a = 2.877e8 # cm^6 bar K^0.5 / mol^2 b = 60.211 # cm^3 / mol Rg = 83.144598 # cm^3 bar / K-mol

  1. derived quantities

TK = TC+273.15 # K

  1. method #1: NumPy

def f(V):

    return P - Rg*TK/(V-b)+a/(np.sqrt(TK)*V*(V+b))

V_liq = fsolve(f,82) # Liquid root V_vap = fsolve(f,28600) # Vapor root print('NumPy Solution') print(V_liq,V_vap)

  1. method #2: Gekko

from gekko import GEKKO m = GEKKO() V = m.Var(value=[82,28600]) m.Equation(P==Rg*TK/(V-b)-a/(m.sqrt(TK)*V*(V+b))) m.options.IMODE=2 m.solve(disp=False) print('Gekko Solution') print(V.value)

May 07, 2018, at 02:44 PM by 45.56.3.173 -
Changed lines 7-8 from:

Complete the following assignments with Microsoft Excel, Google Sheets, or another equivalent spreadsheet program. Python solutions are also shown as a reference and introduction but not required.

to:

Complete the following assignments with Microsoft Excel, Google Sheets, or another similar spreadsheet program. Microsoft Excel solutions are shown for each problem but should only be used as a learning resource, not to merely complete the assignment. Python solutions are shown as a reference and introduction to programming but are not required.

Changed line 12 from:
  • Solution 2, Solution 3
to:
  • Excel Solution 2, Solution 3
Changed line 63 from:

plt.contourf(Tm,Vm,Pm,cmap='RdBu_r')

to:

plt.contourf(Vm,Tm,Pm,cmap='RdBu_r')

Changed line 65 from:

CS2 = plt.contour(Tm,Vm,Pm,[1.0,2.5],colors='k')

to:

CS2 = plt.contour(Vm,Tm,Pm,[1.0,2.5],colors='k')

Changed lines 67-68 from:

plt.xlabel('Temperature (K)') plt.ylabel('Volume (L)')

to:

plt.xlabel('Volume (L)') plt.ylabel('Temperature (K)')

Changed line 76 from:
  • Solution 1, Solution 2, Solution 3
to:
  • Excel Solution 1, Solution 2, Solution 3
Added lines 80-119:

import pandas as pd import matplotlib.pyplot as plt import numpy as np

  1. import April 2018 data or get new data from finance.yahoo.com

appl = pd.read_csv('https://apmonitor.com/che263/uploads/Main/AAPL.csv') goog = pd.read_csv('https://apmonitor.com/che263/uploads/Main/GOOG.csv')

  1. xom = pd.read_csv('https://apmonitor.com/che263/uploads/Main/XOM.csv')
  2. create dictionary of stocks

s = dict([('Apple',appl),('Google',goog)]) #,('ExxonMobil',xom)])

  1. print column headers and starting rows (5 is default)

print('Apple Data') print(s['Apple'].head())

  1. print column headers and ending close price (4 rows)

print('Google Data') print(s['Google']['Close'].tail(4))

  1. basic data statistics

for i in s:

    print('Stock: ' + i)
    print(' max   : ' + str(max(s[i]['Close'])))
    print(' min   : ' + str(min(s[i]['Close'])))
    print(' stdev : ' + str(np.std(s[i]['Close'])))
    print(' avg   : ' + str(np.mean(s[i]['Close'])))
    print(' median: ' + str(np.median(s[i]['Close'])))
  1. plot data

plt.figure() sty = dict([('Apple','r--'),('Google','b:'),('ExxonMobil','k-')]) ni = 0 for i in s:

    mc = max(s[i]['Close'])
    plt.plot(s[i]['Date'],s[i]['Close']/mc,sty[i],linewidth=3,label=i)
    plt.plot(s[i]['Date'],s[i]['High']/mc,sty[i],linewidth=1)
    plt.plot(s[i]['Date'],s[i]['Low']/mc,sty[i],linewidth=1)

plt.xticks(rotation=90) plt.legend(loc='best') plt.show()

Added lines 125-151:

import pandas as pd import matplotlib.pyplot as plt

  1. import data
  2. Time (sec), Heater 1, Heater 2, Temperature 1, Temperature 2

x = pd.read_csv('https://apmonitor.com/che263/uploads/Main/tclab.txt')

  1. print column headers and starting 10 rows (5 is default)

print('Data') print(x.head(10))

  1. plot data

plt.figure() plt.subplot(2,1,1) plt.title('Temperature Control Lab') plt.plot(x['Time (sec)'],x['Temperature 1'],'r--') plt.plot(x['Time (sec)'],x['Temperature 2'],'b-') plt.ylabel('Temp (degC)') plt.legend(loc='best')

plt.subplot(2,1,2) plt.plot(x['Time (sec)'],x['Heater 1'],'r--') plt.plot(x['Time (sec)'],x['Heater 2'],'b-') plt.ylabel('Heater (%)') plt.xlabel('Time (sec)') plt.legend(loc='best') plt.show()

Added lines 157-197:

import math as m

  1. part a

help(m.cos) y = m.cos(0.5) print('cos(0.5): ' + str(y))

  1. part b

y = m.sin(30.0*(m.pi/180.0)) print('sin(30 deg): ' + str(y))

  1. part c

y = m.tan(m.pi/2.0) print('tan(pi/x): ' + str(y))

  1. part d

x = 5.0 y = max(2.0*m.sqrt(x),(x**2)/2.0, (x**3)/3.0,(x**2+x**3)/5.0) print('max value: ' + str(y))

  1. part e

x = 25 y = m.factorial(x) print('25!: ' + str(y))

  1. part f

x = 0.5

  1. if..else statement

if x<1.0:

    y = x**2

else:

    y = m.sin(m.pi*x/2.0)
  1. same but one line

y = x**2 if x<1.0 else m.sin(m.pi*x/2.0) print('if statement result: ' + str(y))

  1. part g

x = 4.999 y = m.floor(x) print('floor(4.999): ' + str(y))

Changed lines 203-204 from:
  • Solution 1, Solution 2, Solution 3, Solution 4
to:
  • Excel Solution 1, Solution 2, Solution 3, Solution 4
  • (:toggle hide hw3_1 button show="Solution 1 (Python)":)

(:div id=hw3_1:) (:source lang=python:)

  1. method #1: NumPy

from numpy.linalg import solve A = b = [45.0, 30.0, 15.0, 20.0, 92.0] x = solve(A,b) print('NumPy Solution') print(x)

  1. method #2: Gekko

from gekko import GEKKO m = GEKKO() x1,x2,x3,x4,x5 = [m.Var() for i in range(5)] m.Equation(11*x1+3*x2+x4+2*x5==45) m.Equation(4*x2+2*x3+x5==30) m.Equation(3*x1+2*x2+7*x3+x4==15) m.Equation(4*x1+4*x3+10*x4+x5==20) m.Equation(2*x1+5*x2+x3+3*x4+14*x5==92) m.solve(disp=False) print('Gekko Solution') print(x1.value) print(x2.value) print(x3.value) print(x4.value) print(x5.value) (:sourceend:) (:divend:)

  • (:toggle hide hw3_2 button show="Solution 2 (Python)":)

(:div id=hw3_2:) (:source lang=python:)

  1. method #1: NumPy

from scipy.optimize import fsolve def f(z):

    x,y=z
    f1 = 2*x**2+y**2-1
    f2 = (0.5*x-0.5)**2+2.0*(y-0.25)**2-1
    return [f1,f2]

x,y = fsolve(f,[1,1]) print('NumPy Solution') print(x,y)

  1. method #2: Gekko

from gekko import GEKKO m = GEKKO() x,y = [m.Var(value=1) for i in range(2)] m.Equation(2*x**2+y**2==1) m.Equation((0.5*x-0.5)**2+2.0*(y-0.25)**2==1) m.solve(disp=False) print('Gekko Solution') print(x.value) print(y.value) (:sourceend:) (:divend:)

  • (:toggle hide hw3_3 button show="Solution 3 (Python)":)

(:div id=hw3_3:) (:source lang=python:)

(:sourceend:) (:divend:)

  • (:toggle hide hw3_4 button show="Solution 3 (Python)":)

(:div id=hw3_4:) (:source lang=python:)

(:sourceend:) (:divend:)

Changed lines 278-279 from:
  • Solution 1, Solution 2, Solution 3
to:
  • Excel Solution 1, Solution 2, Solution 3
  • (:toggle hide hw4_1 button show="Solution 1 (Python)":)

(:div id=hw4_1:) (:source lang=python:)

(:sourceend:) (:divend:)

  • (:toggle hide hw4_2 button show="Solution 2 (Python)":)

(:div id=hw4_2:) (:source lang=python:)

(:sourceend:) (:divend:)

  • (:toggle hide hw4_3 button show="Solution 3 (Python)":)

(:div id=hw4_3:) (:source lang=python:)

(:sourceend:) (:divend:)

Changed lines 300-301 from:
  • Solution 1, Solution 2
to:
  • Excel Solution 1, Solution 2
  • (:toggle hide hw5_1 button show="Solution 1 (Python)":)

(:div id=hw5_1:) (:source lang=python:)

(:sourceend:) (:divend:)

  • (:toggle hide hw5_2 button show="Solution 2 (Python)":)

(:div id=hw5_2:) (:source lang=python:)

(:sourceend:) (:divend:)

Changed lines 316-328 from:
  • Solution 1, Solution 2
to:
  • Excel Solution 1, Solution 2
  • (:toggle hide hw6_1 button show="Solution 1 (Python)":)

(:div id=hw6_1:) (:source lang=python:)

(:sourceend:) (:divend:)

  • (:toggle hide hw6_2 button show="Solution 2 (Python)":)

(:div id=hw6_2:) (:source lang=python:)

(:sourceend:) (:divend:)

May 07, 2018, at 02:33 PM by 45.56.3.173 -
Added lines 6-7:

Complete the following assignments with Microsoft Excel, Google Sheets, or another equivalent spreadsheet program. Python solutions are also shown as a reference and introduction but not required.

May 07, 2018, at 02:29 PM by 45.56.3.173 -
Changed line 76 from:

(:div id=hw1_3:)

to:

(:div id=hw2_1:)

Changed line 81 from:

(:div id=hw1_3:)

to:

(:div id=hw2_2:)

Changed line 86 from:

(:div id=hw1_3:)

to:

(:div id=hw2_3:)

May 07, 2018, at 02:29 PM by 45.56.3.173 -
Changed lines 35-70 from:
to:
  • (:toggle hide hw1_3 button show="Solution 3 (Python)":)

(:div id=hw1_3:)

(:source lang=python:) import numpy as np import matplotlib.pyplot as plt

  1. calculate initial moles of N2

T = 298.15 # K P = 1.25 # atm V = 4000 # L Rg = 0.0821 # L*atm/mol/K n_N2 = P*V/(Rg*T) # moles of N2 n_N2 = n_N2 * 0.25 # moles with 25% remaining

  1. calculate N2 pressure at different V and T

n = 20 # grid points V = np.linspace(500,1000,n) T = np.linspace(100,600,n)

  1. create meshgrid

Vm,Tm = np.meshgrid(V,T)

  1. calculate pressure

Pm = n_N2 * Rg * Tm / Vm

  1. plot results

plt.figure() plt.contourf(Tm,Vm,Pm,cmap='RdBu_r') plt.colorbar() CS2 = plt.contour(Tm,Vm,Pm,[1.0,2.5],colors='k') plt.clabel(CS2, inline=1, fontsize=10) plt.xlabel('Temperature (K)') plt.ylabel('Volume (L)') plt.show() (:sourceend:) (:divend:)

Added lines 75-89:
  • (:toggle hide hw2_1 button show="Solution 1 (Python)":)

(:div id=hw1_3:) (:source lang=python:) (:sourceend:) (:divend:)

  • (:toggle hide hw2_2 button show="Solution 2 (Python)":)

(:div id=hw1_3:) (:source lang=python:) (:sourceend:) (:divend:)

  • (:toggle hide hw2_3 button show="Solution 3 (Python)":)

(:div id=hw1_3:) (:source lang=python:) (:sourceend:) (:divend:)

May 07, 2018, at 02:26 PM by 45.56.3.173 -
Added lines 11-34:
  • (:toggle hide hw1_2 button show="Solution 2 (Python)":)

(:div id=hw1_2:) (:source lang=python:)

  1. constants

L = 2 # m Tplate = 343 # K v = 1.45 # m/s Twater = 294 # K mu = 9.79e-4 # Pa*s rho = 998 # kg/m^3 k = 0.601 # W/m-K cp = 4.18e3 # J/kg-K

  1. derived quantities

Re = rho*L*v/mu Pr = mu*cp/k Nu = 0.332 * Pr**(1.0/3.0) * Re**(1.0/2.0) h = Nu * k / L q = h * (Tplate-Twater)

print('Rate of Heat Transfer') print(str(q)+' W/m^2') (:sourceend:) (:divend:)

May 03, 2018, at 07:28 PM by 10.37.57.234 -
Changed line 23 from:
  • Solution 2, Solution 3
to:
  • Solution 1, Solution 2, Solution 3
May 01, 2018, at 02:32 PM by 45.56.3.173 -
Changed line 15 from:
  • Solution 1, Solution 2, Solution 3
to:
  • Solution 1, Solution 2, Solution 3
May 01, 2018, at 12:56 PM by 45.56.3.173 -
Changed line 15 from:
  • Solution 1, Solution 2, Solution 3
to:
  • Solution 1, Solution 2, Solution 3
May 01, 2018, at 12:55 PM by 45.56.3.173 -
Changed line 12 from:
to:
Changed line 15 from:
  • Solution 1, Solution 2, Solution 3
to:
  • Solution 1, Solution 2, Solution 3
June 13, 2017, at 05:46 PM by 174.148.255.132 -
Changed line 85 from:
  • Solutions 1-7 and 8-10 (Python)
to:
  • Solutions 1-7 and 8-10 (Python)
June 13, 2017, at 04:13 PM by 45.56.3.173 -
Changed lines 85-86 from:
  • Solutions 1-7 (Python)
  • Solutions 8-10 (Python)
to:
  • Solutions 1-7 and 8-10 (Python)
June 13, 2017, at 04:11 PM by 45.56.3.173 -
Added lines 85-86:
  • Solutions 1-7 (Python)
  • Solutions 8-10 (Python)
June 13, 2017, at 02:33 PM by 45.56.3.173 -
Changed lines 83-84 from:
to:
May 01, 2017, at 11:16 PM by 45.56.3.173 -
Changed line 58 from:
to:
May 01, 2017, at 11:15 PM by 45.56.3.173 -
Changed line 78 from:
  • Symbolic Derivatives
to:
  • Symbolic Derivatives and Integrals
May 01, 2017, at 11:14 PM by 45.56.3.173 -
Changed lines 8-9 from:
  • Conditions and Functions
to:
Changed lines 13-14 from:
  • Generate Plots and Data Analysis
to:
Changed line 18 from:
  • Solve Equations
to:
Changed line 22 from:
  • Regression
to:
Changed line 26 from:
  • Differential Equations
to:
Changed line 30 from:
  • VBA Macros
to:
Changed lines 36-37 from:
to:
Changed lines 41-42 from:
  • Loops and Arrays
to:
Changed line 46 from:
  • Plot Data and Correlations
to:
Changed line 50 from:
  • User input, loops, ODEs, and plotting
to:
Changed line 54 from:
  • Debugging
to:
Changed line 58 from:
  • File Input and Ouput
to:
Changed line 62 from:
  • Classes (collections of values and functions)
to:
  • Classes (collections of values and functions)
Changed line 66 from:
  • Solve Equations (fsolve)
to:
Changed line 70 from:
  • Integration, interpolation, and regression
to:
Changed line 74 from:
  • Solve differential equations (odeint)
to:
Changed line 78 from:
  • Symbolic solutions (sympy)
to:
  • Symbolic Derivatives
May 01, 2017, at 11:01 PM by 45.56.3.173 -
Changed lines 7-17 from:
to:
May 01, 2017, at 09:21 PM by 173.117.245.75 -
Changed line 22 from:
  • Conditionals, Functions
to:
May 01, 2017, at 09:18 PM by 173.117.245.75 -
Changed line 22 from:
  • Conditionals, Functions, Loops
to:
  • Conditionals, Functions
Changed lines 25-43 from:
to:
May 01, 2017, at 09:09 PM by 173.117.245.75 -
Changed lines 21-23 from:
to:
January 24, 2017, at 04:17 PM by 10.10.148.223 -
Changed line 15 from:
to:
Changed line 11 from:
to:
January 05, 2017, at 01:03 AM by 10.10.144.119 -
Changed line 17 from:
to:
January 05, 2017, at 12:34 AM by 10.10.144.119 -
Changed line 17 from:
to:
January 05, 2017, at 12:23 AM by 10.10.144.119 -
Changed line 15 from:
to:
Changed line 15 from:
to:
January 04, 2017, at 05:52 PM by 10.10.144.119 -
Changed line 13 from:
to:
January 04, 2017, at 05:52 PM by 10.10.144.119 -
Changed line 13 from:
to:
January 04, 2017, at 05:14 PM by 10.10.144.119 -
Changed line 13 from:
to:
January 04, 2017, at 04:41 PM by 10.10.144.119 -
Changed line 11 from:
to:
Changed line 7 from:
to:
Changed line 11 from:
to:
Changed line 11 from:
to:
Changed line 9 from:
to:
Changed line 9 from:
to:
Changed line 9 from:
to:
Changed line 9 from:
to:
January 02, 2017, at 08:48 PM by 173.117.183.12 -
Changed line 7 from:
to:
January 02, 2017, at 08:10 PM by 173.117.183.12 -
Changed line 7 from:
to:
Changed lines 21-42 from:
to:
Changed lines 46-47 from:
to:
  • Solutions
Changed lines 50-51 from:
to:
  • Solutions
Changed lines 53-55 from:
to:
  • Solutions 1-6
  • Solutions 7-9
Deleted line 57:
August 30, 2016, at 07:47 PM by 184.203.103.142 -
Added lines 1-54:

(:title Programming Assignments:) (:keywords homework, nonlinear, optimization, engineering optimization, Excel, Mathcad, Visual Basic, MATLAB, differential, algebraic, modeling language, university course:) (:description Assignments for Problem-Solving Techniques for Chemical Engineers at Brigham Young University:)

Excel Assignments

Python Assignments

MathCAD Assignments