Skip to content

Commit

Permalink
add pendulum demo
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Liu committed May 31, 2024
1 parent 5734d15 commit 3fc6604
Show file tree
Hide file tree
Showing 76 changed files with 158 additions and 261 deletions.
73 changes: 3 additions & 70 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,72 +1,5 @@
# This .gitignore file should be placed at the root of your Unity project directory
#
# Get latest from https://github.com/github/gitignore/blob/main/Unity.gitignore
#
/[Ll]ibrary/
/[Tt]emp/
/[Oo]bj/
/[Bb]uild/
/[Bb]uilds/
/[Ll]ogs/
/[Uu]ser[Ss]ettings/
# Byte-compiled / optimized / DLL files
__pycache__/
.pytest_cache/

# MemoryCaptures can get excessive in size.
# They also could contain extremely sensitive data
/[Mm]emoryCaptures/

# Recordings can get excessive in size
/[Rr]ecordings/

# Uncomment this line if you wish to ignore the asset store tools plugin
# /[Aa]ssets/AssetStoreTools*

# Autogenerated Jetbrains Rider plugin
/[Aa]ssets/Plugins/Editor/JetBrains*

# Visual Studio cache directory
.vs/

# Gradle cache directory
.gradle/

# Autogenerated VS/MD/Consulo solution and project files
ExportedObj/
.consulo/
*.csproj
*.unityproj
*.sln
*.suo
*.tmp
*.user
*.userprefs
*.pidb
*.booproj
*.svd
*.pdb
*.mdb
*.opendb
*.VC.db

# Unity3D generated meta files
*.pidb.meta
*.pdb.meta
*.mdb.meta

# Unity3D generated file on crash reports
sysinfo.txt

# Builds
*.apk
*.aab
*.unitypackage
*.app

# Crashlytics generated file
crashlytics-build.properties

# Packed Addressables
/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin*

# Temporary auto-generated Android Assets
/[Aa]ssets/[Ss]treamingAssets/aa.meta
/[Aa]ssets/[Ss]treamingAssets/aa/*
9 changes: 7 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
{
"files.exclude":
{
"**/.DS_Store":true,
Expand Down Expand Up @@ -51,5 +51,10 @@
"ProjectSettings/":true,
"temp/":true,
"Temp/":true
}
},
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
# FlowField
flow field demo

# how to play
## show vector field
```
python play.py
python show.py
```

# config
edit app.yaml
![show filed](./images/show.png "simple pendulum")

You can add your own example in the conf/problems directory

## vector field playground
```
python play.py
```
![playground](./images/play.png "simple pendulum")


3 changes: 2 additions & 1 deletion conf/app.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
cells_side: 24
animate_time: 6 #second
normalize: true
problem: 01_fall #01_fall,02_diffuse,03_fishing
ball_pos: [0,0.8] # normalize coordinate, [1,1] correspond to the top right corner of the screen
problem: 04_pendulum #01_fall,02_diffuse,03_fishing,04_pendulum
10 changes: 3 additions & 7 deletions conf/problems/01_fall.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
desc: free fall with air frcition
U: 1
V: 9.8-k*Y
X:
name: time
range: [0,60]
Y:
name: speed
range: [40,60]
X: ["time",0,60] #name,min,max
Y: ["speed",40,60]
args:
k: 0.2
k: ["drag coefficient",0.2,0,10] #name,value,min,max
10 changes: 3 additions & 7 deletions conf/problems/02_diffuse.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
desc: temperature conduction or concentration diffusion
U: 1
V: k*(20-Y)
X:
name: time
range: [0,60]
Y:
name: temperature
range: [0,40]
X: ["time",0,60] #name,min,max
Y: ["temperature",0,40]
args:
k: 0.2
k: ["coefficient of conduction",0.2,0,10] #name,value,min,max
14 changes: 5 additions & 9 deletions conf/problems/03_fishing.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
desc: aquaculture and fishing
U: 1
V: k1*Y-k2*(Y**2)-k3
X:
name: time
range: [0,1]
Y:
name: fish amount
range: [0,6]
X: ["time",0,1] #name,min,max
Y: ["fish amount",0,6]
args:
k1: 8
k2: 2
k3: 1.6
k1: ["coefficient of reproduction",8,0,10] #name,value,min,max
k2: ["environmental limiting factor",2,0,5]
k3: ["fishing coefficient",1.6,0,3]
8 changes: 8 additions & 0 deletions conf/problems/04_pendulum.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
desc: pendulum
U: Y*1
V: -k1*sin(X)-k2*Y
X: ["angular",0,10] #name,min,max
Y: ["angular velocity",-10,10]
args:
k1: ["coefficient of gravity",2,1,5] #name,value,min,max
k2: ["drag coefficient",0.3,0,3]
File renamed without changes.
Binary file added images/play.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/show.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion pyglet_app/imgui.ini → imgui.ini
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ Collapsed=0
[Window][MyGame]
Pos=184,27
Size=389,143
Collapsed=1
Collapsed=0

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class Pendulum(Space):

def config_args(self):
self.set_args([ArgInfo('a',2,1,5,0.2,'a:acceleration'),ArgInfo('b',1,0,3,0.2,'damp')])
self.description="q:angle q':angle velocity | q''=-a.sin(q)-b.q'"
self.description="q:angle v:angle velocity | v'=-a.sin(q)-b.v"



Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
154 changes: 17 additions & 137 deletions play.py
Original file line number Diff line number Diff line change
@@ -1,137 +1,17 @@
from omegaconf import OmegaConf
import numpy as np
from omegaconf import OmegaConf,DictConfig
from sympy import symbols, sympify, lambdify
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
from scipy.interpolate import interp2d
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
# 初始化小球的位置
ball_x = 0.5
ball_y = 0.5
def load_config(fname='conf/app.yaml')->DictConfig:
cfg = OmegaConf.load(fname)
problem_config = f"conf/problems/{cfg.problem}.yaml"

# 将数据库配置文件的内容合并到主配置中
problem_config = OmegaConf.load(problem_config)
cfg = OmegaConf.merge(cfg, problem_config)

# 现在 config 中包含了主配置和数据库配置
print(OmegaConf.to_yaml(cfg))
return cfg

def show(cfg,x,y,X,Y,U,V):
global ball_x, ball_y
title,xname,yname=cfg.desc,cfg.X.name,cfg.Y.name

# 创建插值函数
u_interp = interp2d(x, y, U*np.ones_like(V), kind='linear')
v_interp = interp2d(x, y, V, kind='linear')
ball_x,ball_y=x[0],y[-1]
step=(x[-1]-x[0])/cfg.cells_side/2,(y[-1]-y[0])/cfg.cells_side/2
#print('ball pos:',ball_x,ball_y)

# 计算矢量的大小
magnitude = np.sqrt(U**2 + V**2)

# 归一化矢量的大小
norm = Normalize(magnitude.min(), magnitude.max())

# 创建颜色映射对象
cmap = plt.cm.coolwarm

# # 创建一个ScalarMappable对象,用于颜色映射和颜色条
sm = ScalarMappable(norm=norm, cmap=cmap)
colors = [sm.to_rgba(m) for m in magnitude.ravel()]

# 创建图形和轴
fig, ax = plt.subplots(figsize=(7, 6))

# 绘制矢量场,为每个箭头指定颜色
if cfg.normalize:
ax.quiver(X, Y, U/magnitude, V/magnitude, color=colors)
else:
ax.quiver(X, Y, U, V, color=colors)
#

ball, = ax.plot(ball_x, ball_y, 'bo') # 'bo' 表示蓝色圆点

def update(frame):
global ball_x, ball_y
# 使用插值函数获取当前位置的矢量分量
u = u_interp(ball_x, ball_y)
v = v_interp(ball_x, ball_y)
# 更新小球的位置
dis=np.sqrt(u**2+v**2)
ball_x += u/(dis+1e-10) * step[0]
ball_y += v/(dis+1e-10) * step[1]
# 确保小球不会离开绘图区域
ball_x = np.clip(ball_x, min(x), max(x))
ball_y = np.clip(ball_y, min(y), max(y))
ball.set_data(ball_x, ball_y)
return ball,
# 显示图形
plt.xlabel(xname)
plt.ylabel(yname)
plt.title(title)
ani = FuncAnimation(fig, update, frames=np.linspace(0, 1, cfg.animate_time*1000//16), blit=True,interval=16)
plt.show()

def main(cfg):
N=cfg.cells_side
# pname=cfg.show
# p=cfg.problems[pname]
x1,x2=cfg.X.range
y1,y2=cfg.Y.range
xs = np.linspace(x1,x2, N)
ys = np.linspace(y1,y2, N)
X, Y = np.meshgrid(xs, ys)

x, y = symbols('X Y')
u=sympify(cfg.U)
v=sympify(cfg.V)
ks=[]
ds=[]
args=cfg.get('args',None)
if args!=None:
for arg in cfg.args.keys():
ks.append(symbols(arg))
ds.append(cfg.args[arg])

func1 = lambdify((x,y,*ks), u, 'numpy')
func2 = lambdify((x,y,*ks), v, 'numpy')
U=func1(X,Y,*ds)
V=func2(X,Y,*ds)
show(cfg,xs,ys,X,Y,U,V)

# def check_config(cfg):
# print(cfg.cells_side)
# print(list(cfg.problems.keys()))
# print(cfg.problems.P1.X)
# print(cfg.problems.P1.U)
# print(cfg.problems.P1.args[0])

# def demo_exp():
# # 定义符号变量
# x = symbols('x')

# # 用户输入的表达式字符串,例如 "k*np.cos(x)"
# expr_str ='k*sin(x)'# input("请输入表达式(例如 'k*np.cos(x)'):")

# # 解析字符串为Sympy表达式
# expr = sympify(expr_str)
# expr = expr.subs('k', 0.5)

# # 创建一个numpy数组
# x_values = np.linspace(0, 2*np.pi, 3) # 从0到2π的100个点
# func = lambdify(x, expr, 'numpy')
# # 计算结果
# result = func(x_values)

# # 打印结果
# print("计算结果:", result)
if __name__ == '__main__':
cfg=load_config()
main(cfg)
import pyglet
from phase_space.app import App
from config import demo_names,make_views,WIDTH,HEIGHT,FPS,TITLE
CFG={
'WIDTH':WIDTH,
'HEIGHT':HEIGHT,
'FPS':FPS,
'TITLE':TITLE,
'demo_names':demo_names,
'make_views':make_views,
}
def main():
App(CFG)
pyglet.app.run()

if __name__ == "__main__":
main() #git push origin --tags
Binary file removed pyglet_app/__pycache__/config.cpython-39.pyc
Binary file not shown.
3 changes: 0 additions & 3 deletions pyglet_app/doc/demo.uxf

This file was deleted.

Binary file removed pyglet_app/doc/demo2.drawio.png
Binary file not shown.
1 change: 0 additions & 1 deletion pyglet_app/doc/des.uxf

This file was deleted.

Binary file not shown.
Binary file not shown.
Binary file removed pyglet_app/phase_space/__pycache__/ui.cpython-39.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
17 changes: 0 additions & 17 deletions pyglet_app/play.py

This file was deleted.

Loading

0 comments on commit 3fc6604

Please sign in to comment.