tum-pbs / PhiFlow

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

Can't sum grids depending on global_precision #125

Closed Tartenpi0m closed 1 year ago

Tartenpi0m commented 1 year ago

Hello ! I have this error : IncompatibleShapes: Cannot merge shapes [(xˢ=1024), (xˢ=1023)] because dimension 'x' exists with different sizes.

when I try to execute this code :

import phi
from phi import flow
from phi.field._field_math import spatial_gradient
import numpy as np
phi.math.set_global_precision(64)

N = 1024
u = np.ones(N)
u = flow.math.tensor(u, flow.spatial('x'))
u = flow.field.CenteredGrid(u, flow.extrapolation.PERIODIC, x=N, bounds=flow.Box['x', 0:2*np.pi])
dudx = spatial_gradient(u, type=flow.field.StaggeredGrid, gradient_extrapolation=flow.extrapolation.PERIODIC)[0]
dudx2 = spatial_gradient(dudx, type=flow.field.StaggeredGrid, gradient_extrapolation=flow.extrapolation.PERIODIC)[0]
print(u.shape) #(xˢ=1024)
print(dudx2.shape) #(xˢ=1024)
u + dudx2  # THIS LINE CAUSE THE ERROR

The error occurs only for bad combination of global_precision and N. For example, it occurs with :

holl- commented 1 year ago

Very strange. I'll look into it!

holl- commented 1 year ago

So the problem is that each time you call spatial_gradient with type=StaggeredGrid, the sample points are shifted half a cell to the left. Then, when you call u + dudx2, there is a full cell shift difference.

You can fix this by putting the left-most cell to the right edge instead using

dudx2 = phi.field.pad(dudx2, {'x': (-1, 1)})

Hope that helps!