tum-pbs / PhiFlow

A differentiable PDE solving framework for machine learning
MIT License
1.43k stars 193 forks source link

How to convert a velocity.values to numpy array properly? #75

Closed team0ne1 closed 2 years ago

team0ne1 commented 2 years ago

For example, in ./demos/smoke_plume.py. I try to get velocity grid values


""" Smoke Plume
Hot smoke is emitted from a circular region at the bottom.
The simulation computes the resulting air flow in a closed box.
"""
from phi.flow import *  

velocity = StaggeredGrid((0, 0), 0, x=64, y=64, bounds=Box(x=100, y=100))  # or CenteredGrid(...)
smoke = CenteredGrid(0, extrapolation.BOUNDARY, x=200, y=200, bounds=Box(x=100, y=100))
INFLOW = 0.2 * CenteredGrid(SoftGeometryMask(Sphere(x=50, y=9.5, radius=5)), 0, smoke.bounds, smoke.resolution)
pressure = None

# @math.jit_compile  # Only for PyTorch, TensorFlow and Jax
def step(v, s, p, dt=1.):
    s = advect.mac_cormack(s, v, dt) + INFLOW
    buoyancy = s * (0, 0.1) @ v  # resamples smoke to velocity sample points
    v = advect.semi_lagrangian(v, v, dt) + buoyancy * dt
    v, p = fluid.make_incompressible(v, (), Solve('auto', 1e-5, 0, x0=p))
    return v, s, p

for _ in view(smoke, velocity, 'pressure', play=False, namespace=globals()).range(warmup=1):
    velocity, smoke, pressure = step(velocity, smoke, pressure)
    if _ == 10:        
        print(velocity.values.numpy('x,y'))
        break

then it throw error:

AssertionError: Dimension (vectorᶜ=x,y) missing from 'order'. Got ('x', 'y') but tensor has shape (xˢ=(x=63, y=64), yˢ=(x=64, y=63), vectorᶜ=x,y).

so I have to get velocity Tensor values in this way, but it's so werid.

...
for _ in view(smoke, velocity, 'pressure', play=True, namespace=globals()).range(warmup=1):
    velocity, smoke, pressure = step(velocity, smoke, pressure)
    if _ == 10:
        v_x = velocity.values.unstack('vector')[0].numpy('x,y')
        v_y = velocity.values.unstack('vector')[1].numpy('x,y')
        print(v_x.shape,v_y.shape)
        break

Output:

(63, 64) (64, 63)

So, Is there any better way to get the velocity valus?

And one more question, Why the shape of grid is (63, 64) (64, 63) instead of (64, 64) (64, 64) ? Thanks

holl- commented 2 years ago

Sorry for the late response. Yes, you can get a uniform tensor using velocity.uniform_values on the latest version or velocity.staggered_tensor() on older versions. Then get the numpy representation using .numpy('x,y,vector')