tum-pbs / PhiFlow

A differentiable PDE solving framework for machine learning
MIT License
1.39k stars 189 forks source link

How to assign values to new grid variables #126

Closed XueruiSu closed 1 year ago

XueruiSu commented 1 year ago

When I using phiflow for the case of "smoke_plume", I want to save the arrays of smoke and velocity so that I can continue to calculate the solution when I need. But I don't how to assign numpy array(or tensor) into CenteredGrid and StaggeredGrid object. Could help me to fix my problem?

Here is my code:

First, I defined "smoke", "velocity" and "INFLOW" object:


smoke = CenteredGrid(0, extrapolation.BOUNDARY, x=128, y=128, bounds=Box(x=128, y=128)) velocity = StaggeredGrid(0, extrapolation.ZERO, x=128, y=128, bounds=Box(x=128, y=128))
INFLOW_LOCATION1 = tensor([(20, 25), (50, 50), (80, 25), (110, 25)], batch('inflow_loc'), channel(vector='x,y')) INFLOW_LOCATION2 = tensor([(110, 25), (75, 50), (45, 25), (30, 25)], batch('inflow_loc'), channel(vector='x,y')) sphere1 = Sphere(center=INFLOW_LOCATION1, radius=10) sphere2 = Sphere(center=INFLOW_LOCATION2, radius=10) sphere = flow.union([sphere1, sphere2]) INFLOW = 0.6 * CenteredGrid(sphere, extrapolation.BOUNDARY, x=128, y=128, bounds=Box(x=128, y=128))

then I take some steps to calculate the velocity and smoke, and record the arrays at the same time.


@flow.math.jit_compile def step(velocity_prev, smoke_prev, dt=1.0): smoke_prev = advect.mac_cormack(smoke_prev, velocity_prev, dt=1) + INFLOW buoyancy_force = smoke_prev * (0, 0.5) @ velocity_prev velocity_prev = advect.semi_lagrangian(velocity_prev, velocity_prev, dt=1) + buoyancy_force velocityprev, = fluid.make_incompressible(velocity_prev) return velocity_prev, smoke_prev for i in range(100): velocity, smoke = step(velocity, smoke) v_array = velocity.at_centers().values.numpy("inflow_loc,y,x,vector") smoke_array = smoke.values.numpy("inflow_loc,y,x")

and now I don't know how to use "v_array" and "smoke_array" to rebuild the "smoke", "velocity" object to continue the calculation.


Thanks for help!!!

holl- commented 1 year ago

Hi, the easiest way to read/write grids is using the Scene class

To create grids from NumPy arrays, you need to assign the dimensions first:

v_tensor = math.tensor(v_array, batch('inflow_loc'), spatial('x,y'), channel(vector='x,y'))
velocity = CenteredGrid(v_tensor, ...)
XueruiSu commented 1 year ago

Thank you for your kind answer, it can solve my problem