type()
mylist[1]=‘five’
My list.append()
len()
mylist[1][2]
Loops:
1.for loop:
for i in range(-2,10,2):
for i in range(len(list)): range就是0到list长度-1
2.while loop:
while x<10:
x+=1
if statement, elif, else
Boolean logic: (the conditional True/False statement) allows you to perform tests that return True or False
A 不等于 B: a != b
A and B: A,B 全对就是T; A or B: 其一正确就是T
% sign: 结果是reminder
Function: def c_b():
Import math
math.degree()
imports the pyplot module from matplotlib:
%matplotlib inline
import matplotlib.pyplot as plt
list 算数 需要用for loop 或者变成array-- np.array():
(1)x1 = [2,4,6,8,10,12,14,16,18]
s=[]
c=[]
for i in range(len(x1)):
s.append(math.sin(x1[i]))
c.append(math.cos(x1[i]))
plt.plot(x1,s,color=‘green’,label=‘sin(x)’)
plt.plot(x1,c,color=‘orange’,label=‘cos(x)’)
plt.legend()
(2)x1 = [2,4,6,8,10,12,14,16,18]
x=np.array(x1)
plt.plot(x1,np.sin(x),color=‘green’,label=‘sin(x)’)
plt.plot(x1,np.cos(x),color=‘orange’,label=‘cos(x)’)
plt.legend()
plt.subplots()
plt.figure()
Make the width of the plot extend from num1 to num2 and height of the plot extend from n3 to n4:
plt.axis([num1,num2,n3,n4])
0~2pi,以0.1增加:
(1)x1=np.arange(0,2np.pi,0.1)
(2)x=[]
i=0.0
while i <= 2math.pi:
x.append(i)
i += 0.1
list=[]
for i in range(5):
list.append(i)
for i in range(5):
ary=np.append(ary,i)
np.arange(a,b,c): range from a to b-1, 以c增加
np.linspace(a,b,c) : range from a to b, 直接有c个点
(1)import numpy as np
list=np.arange(0,10)
print(list/3)
(2)a=[]
for i in range(10):
a.append(i)
b=[]
for j in a:
b.append(j/3)
print(b)
np.random.randn(a): 随机抽a个数
ary=np.array([[1,2,3],[4,5,6]])
ary.shape
(2, 3)
两行三列
ary.size 是6 指有多少个elements
np.zeros(3)——array([0., 0., 0.])
np.oners(3)——array([1., 1., 1.])
np.sqrt()
np.sort():从小到大排列
a = np.array([[1,4],[3,1]])
np.sort(a) # sort along the last axis
array([[1, 4],
[1, 3]])np.sort(a, axis=None) # sort the flattened array
array([1, 1, 3, 4])np.sort(a, axis=0) # sort along the first axis
array([[1, 1],
[3, 4]])
Load file(cvs):
np.loadtxt(“eri.csv”, usecols = (0,1), unpack=True, skiprows = 1, delimiter=‘,’, dtype=str):
usecols : int or sequence, optional which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns.
unpack: If True, read the data into a separate variable for each column, so that arguments may be unpacked using x, y, z = loadtxt(…). When used with a structured data-type, arrays are returned for each field. Default is False.
unpack=True: x:[x,…], y:[y,…], z:[z,…]
unpack=False: [x,y,z],[x1,y1,z1]
skiprows = 1: 第一排(1st row) 不读,不出现
np.median()
np.mean()
np.average()
np.std()
min()
max()
plt.hist(f,bins=,alpha=0.8,rwidth=0.5):
plt.tight_layout()
i = int(k/5) #integerqw
j = k % 5 #reminder
#convert numpy array to list and draw a random set of numbers
rand_draw = sample(list(xvals_pareto), draw_size)
Saving plot:
plt.savefig(‘foo.png’)
plt.savefig(‘foo.pdf’)
ODE:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.integrate import odeint
STEP 1: Identifying Paramaters and State Variables:
State Variables = x, y, z
Parameters =𝜎,𝜌,𝛽
STEP 2: Define a Derivative Function:
sigma=10
rho=28
beta=8/3
def derivative(state, t, sigma, rho, beta):
x=state[0]
y=state[1]
z=state[2]
dxdt=sigma*(y-x)
dydt=x*(rho-z)-y
dzdt=x*y-beta*z
return dxdt, dydt, dzdt
STEP 3: Create an Initial State Vector:
x_0 = 0
y_0 = 1
z_0 = 2
state_0=(x_0,y_0,z_0)
STEP 4: Create a Time Interval¶:
(1)t=np.arange(0,60.01,0.01)
(2)b=np.linspace(0,60, 6001) #60/0.01+1
STEP 5: Solve the System:
soln=odeint(derivative, state_0, t, args=(sigma, rho, beta,))
x=soln[:,0]
y=soln[:,1]
z=soln[:,2]
STEP 6: Interpret the Solution with Plots:
3d-plot:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams[‘legend.fontsize’] = 10
fig = plt.figure()
ax = fig.gca(projection=‘3d’)
ax.plot(soln[:,0],soln[:,1],soln[:,2])
Compartmental models:
Viral Kinetics (VK) Model:
Target cells:these are the healthy cells the virion might enter
Infected cell: these cells produce new virions, and might die over time
Virion population:the number of virions at any given time during the infection
rate at which cells become infected: this reduces the value of T and increases the value of I
the production rate of new virions, which increases the value of V
rate at which infected cells die
rate at which virions degrade and leave the system
(2)Social Science: Spread of Rumors:
1.the unknown rumor will start through the media. 2.And then first one will affect the people who do not know the rumor. 3.the outcomes of the second thing will tranfor two group, one is the people who believe the romor and second is the people do not believe the rumor. 4 These goups will affect the the rumor in the first box.
2D numpy array is an array where each element in itself is an array.It can also be referred to as a matrix.example: medical information for each patient and all patients information that are stored under the same hospital; all hospitals that are stored in the entire state.
e.g. game Battleship as a kid
plt.imshow()
board[2, 1:6] = 1
plt.axis(‘off’) # Don’t include the axes!
Masking :
car_information[ car_information[:, 1] >= 300]
from PIL import Image
picture = Image.open(“example.jpeg")
import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(picture)
plt.axis(‘off’)
Random:
import random
random.random() #0~1之间随机取数
random.uniform(a,b) #a~b之间随机取数
random.seed() #每次run出的随机取数一致,不会改变
random.randint(a,b) #a~b之间随机取整数
random.shuffle(list) #洗牌list
dictionary:
list={“a”:[],”b”:[]}
plt.scatter(x, y, label = “relationship between x and y”)
plt.plot(x_model, y_expected, color = “orange”, label = “fit”)
plt.legend()
plt.xlabel(‘x’)
plt.ylabel(‘y’)
plt.title(‘best fit with curve_fit model’)
plt.show()
agent-based model is:
agent-based is a class of computational models that model the most general framework in the modeling and Simulation of complex system, which actually includes cellular automata and dynamic network. ABMS are widely used in various disciplines to simulate the dynamic behavior of systems composed of a large number of entities. It is usually implemented as a simulation model in a computer, in which the behavior rules of each agent are described by algorithm rather than by pure mathematics.
这篇博客总结了Python编程的基础知识,包括类型检查、列表操作、循环语句(for和while)、条件判断和布尔逻辑。还探讨了matplotlib库进行数据可视化的用法,如绘制sin和cos曲线,调整坐标轴范围以及保存图像。此外,还涉及numpy库的使用,如创建数组、算术运算、随机数生成,并讲解了如何从文件中加载数据。最后,文章简要提到了ODE求解和3D绘图。

5797

被折叠的 条评论
为什么被折叠?



