def cartesian_to_barycentric_3D(tri, xy):
xy = np.asarray(xy)<EOL>tri = np.asarray(tri)<EOL>if len(xy.shape) == <NUM_LIT:1>:<EOL><INDENT>return cartesian_to_barycentric_3D(np.transpose(np.asarray([tri]), (<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:0>)),<EOL>np.asarray([xy]).T)[:,<NUM_LIT:0>]<EOL><DEDENT>xy = xy if xy.shape[<NUM_LIT:0>] == <NUM_LIT:3> else xy.T<EOL>if tri.shape[<NUM_LIT:0>] == <NUM_LIT:3>:<EOL><INDENT>tri = tri if tri.shape[<NUM_LIT:1>] == <NUM_LIT:3> else np.transpose(tri, (<NUM_LIT:0>,<NUM_LIT:2>,<NUM_LIT:1>))<EOL><DEDENT>elif tri.shape[<NUM_LIT:1>] == <NUM_LIT:3>:<EOL><INDENT>tri = tri.T if tri.shape[<NUM_LIT:0>] == <NUM_LIT:3> else np.transpose(tri, (<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:0>))<EOL><DEDENT>elif tri.shape[<NUM_LIT:2>] == <NUM_LIT:3>:<EOL><INDENT>tri = np.transpose(tri, (<NUM_LIT:2>,<NUM_LIT:1>,<NUM_LIT:0>) if tri.shape[<NUM_LIT:1>] == <NUM_LIT:3> else (<NUM_LIT:2>,<NUM_LIT:0>,<NUM_LIT:1>))<EOL><DEDENT>if tri.shape[<NUM_LIT:0>] != <NUM_LIT:3> or tri.shape[<NUM_LIT:1>] != <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if xy.shape[<NUM_LIT:0>] != <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if tri.shape[<NUM_LIT:2>] != xy.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>v0 = tri[<NUM_LIT:1>] - tri[<NUM_LIT:0>]<EOL>v1 = tri[<NUM_LIT:2>] - tri[<NUM_LIT:0>]<EOL>v2 = xy - tri[<NUM_LIT:0>]<EOL>d00 = np.sum(v0 * v0, axis=<NUM_LIT:0>)<EOL>d01 = np.sum(v0 * v1, axis=<NUM_LIT:0>)<EOL>d11 = np.sum(v1 * v1, axis=<NUM_LIT:0>)<EOL>d20 = np.sum(v2 * v0, axis=<NUM_LIT:0>)<EOL>d21 = np.sum(v2 * v1, axis=<NUM_LIT:0>)<EOL>den = d00*d11 - d01*d01<EOL>zero = np.isclose(den, <NUM_LIT:0>)<EOL>unit = <NUM_LIT:1> - zero<EOL>den += zero<EOL>l2 = unit * (d11 * d20 - d01 * d21) / den<EOL>l3 = unit * (d00 * d21 - d01 * d20) / den<EOL>return np.asarray([<NUM_LIT:1.0> - l2 - l3, l2])<EOL>
cartesian_to_barycentric_3D(tri,xy) is identical to cartesian_to_barycentric_2D(tri,xy) except
it works on 3D data. Note that if tri is a 3 x 3 x n, a 3 x n x 3 or an n x 3 x 3 matrix, the
first dimension must always be the triangle vertices and the second 3-sized dimension must be
the (x,y,z) coordinates.