file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/thread/reduce.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Defines basic thread level reduction with specializations for Array<T, N>.
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/numeric_types.h"
#include "cutlass/array.h"
#include "cutlass/half.h"
#include "cutlass/functional.h"
namespace cutlass {
namespace reduction {
namespace thread {
/// Structure to compute the thread level reduction
template <typename Op, typename T>
struct Reduce;
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Partial Specialization of Reduce for "plus" (a functional operator)
template <typename T>
struct Reduce< plus<T>, T > {
CUTLASS_HOST_DEVICE
T operator()(T lhs, T const &rhs) const {
plus<T> _op;
return _op(lhs, rhs);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Partial specialization of Reduce for Array<T, N>
template <typename T, int N>
struct Reduce < plus<T>, Array<T, N>> {
CUTLASS_HOST_DEVICE
Array<T, 1> operator()(Array<T, N> const &in) const {
Array<T, 1> result;
Reduce< plus<T>, T > scalar_reduce;
result.clear();
CUTLASS_PRAGMA_UNROLL
for (auto i = 0; i < N; ++i) {
result[0] = scalar_reduce(result[0], in[i]);
}
return result;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Partial specializations of Reduce for Array<half_t, N>
template <int N>
struct Reduce < plus<half_t>, Array<half_t, N> > {
CUTLASS_HOST_DEVICE
Array<half_t, 1> operator()(Array<half_t, N> const &input) {
Array<half_t, 1> result;
// If there is only 1 element - there is nothing to reduce
if( N ==1 ){
result[0] = input.front();
} else {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 600)
__half result_d;
Array<half_t, 1> const *in_ptr_half = reinterpret_cast<Array<half_t, 1> const *>(&input);
Array<half_t, 2> const *in_ptr_half2 = reinterpret_cast<Array<half_t, 2> const *>(&input);
__half2 const *x_in_half2 = reinterpret_cast<__half2 const *>(in_ptr_half2);
// Set initial result = first half2, in case N==2
__half2 tmp_result = x_in_half2[0];
CUTLASS_PRAGMA_UNROLL
for (int i = 1; i < N/2; ++i) {
tmp_result = __hadd2(x_in_half2[i], tmp_result);
}
result_d = __hadd(__low2half(tmp_result), __high2half(tmp_result));
// One final step is needed for odd "N" (to add the (N-1)th element)
if( N%2 ){
__half last_element;
Array<half_t, 1> tmp_last;
Array<half_t, 1> *tmp_last_ptr = &tmp_last;
tmp_last_ptr[0] = in_ptr_half[N-1];
last_element = reinterpret_cast<__half const &>(tmp_last);
result_d = __hadd(result_d, last_element);
}
Array<half_t, 1> *result_ptr = &result;
*result_ptr = reinterpret_cast<Array<half_t, 1> &>(result_d);
#else
Reduce< plus<half_t>, half_t > scalar_reduce;
result.clear();
CUTLASS_PRAGMA_UNROLL
for (auto i = 0; i < N; ++i) {
result[0] = scalar_reduce(result[0], input[i]);
}
#endif
}
return result;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Partial specializations of Reduce for AlignedArray<half_t, N>
template <int N>
struct Reduce < plus<half_t>, AlignedArray<half_t, N> > {
CUTLASS_HOST_DEVICE
Array<half_t, 1> operator()(AlignedArray<half_t, N> const &input) {
Array<half_t, 1> result;
// If there is only 1 element - there is nothing to reduce
if( N ==1 ){
result[0] = input.front();
} else {
#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 600)
__half result_d;
AlignedArray<half_t, 1> const *in_ptr_half = reinterpret_cast<AlignedArray<half_t, 1> const *>(&input);
AlignedArray<half_t, 2> const *in_ptr_half2 = reinterpret_cast<AlignedArray<half_t, 2> const *>(&input);
__half2 const *x_in_half2 = reinterpret_cast<__half2 const *>(in_ptr_half2);
// Set initial result = first half2, in case N==2
__half2 tmp_result = x_in_half2[0];
CUTLASS_PRAGMA_UNROLL
for (int i = 1; i < N/2; ++i) {
tmp_result = __hadd2(x_in_half2[i], tmp_result);
}
result_d = __hadd(__low2half(tmp_result), __high2half(tmp_result));
// One final step is needed for odd "N" (to add the (N-1)th element)
if( N%2 ){
__half last_element;
AlignedArray<half_t, 1> tmp_last;
AlignedArray<half_t, 1> *tmp_last_ptr = &tmp_last;
tmp_last_ptr[0] = in_ptr_half[N-1];
last_element = reinterpret_cast<__half const &>(tmp_last);
result_d = __hadd(result_d, last_element);
}
Array<half_t, 1> *result_ptr = &result;
*result_ptr = reinterpret_cast<Array<half_t, 1> &>(result_d);
#else
Reduce< plus<half_t>, half_t > scalar_reduce;
result.clear();
CUTLASS_PRAGMA_UNROLL
for (auto i = 0; i < N; ++i) {
result[0] = scalar_reduce(result[0], input[i]);
}
#endif
}
return result;
}
};
}
}
}
| 7,208 | C | 29.676596 | 112 | 0.56576 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/device/tensor_reduce_affine_strided.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Kernel performing a reduction over one or more ranks of an affine tensor
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/array.h"
#include "cutlass/fast_math.h"
#include "cutlass/numeric_types.h"
#include "cutlass/numeric_conversion.h"
#include "cutlass/device_kernel.h"
#include "cutlass/reduction/kernel/tensor_reduce_affine_strided.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace reduction {
namespace device {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Tensor reduction operator on layouts which are affine
template <
int Rank, ///< Rank of source tensor (e.g. NDHWC => 5)
int ReducedRank, ///< Rank of reduced tensor (includes contiguous, e.g. NC => 2)
typename ElementOutput_,
typename ElementSource_,
typename ReductionOp_,
int VectorLength = 1,
typename ElementCompute_ = ElementOutput_,
int Threads = 256, ///< Number of participating threads
int BatchSize = 4 ///< Number of elements to load per batch
>
struct TensorReductionAffineStrided {
static int const kRank = Rank;
static int const kReducedRank = ReducedRank;
static int const kVectorLength = VectorLength;
static int const kInnerRank = kRank - kReducedRank;
static int const kThreads = Threads;
static int const kBatchSize = BatchSize;
using ElementOutput = ElementOutput_;
using ElementSource = ElementSource_;
using ReductionOp = ReductionOp_;
using ElementCompute = ElementCompute_;
//
// Data members
//
/// Internal status field
Status status;
/// Extent of tensor in source layout
Coord<kRank> extent;
/// Number of points in the outer index space
int64_t outer_count;
/// Number of elements in the inner index space
int64_t inner_count;
/// Number of workspaces needed
int workspace_count;
/// CUDA Grid shape (.x => contiguous, .y => outer, .z => inner)
dim3 grid_shape;
/// CUDA Threadblock shape (.x => contiguous, .y => outer, .z => inner)
dim3 threadblock_shape;
/// CUDA grid shape for the final reduction step if needed
dim3 grid_final;
/// CUDA threadblock shape for the final reduction step if needed
dim3 threadblock_final;
private:
//
// Methods
//
/// Helper to reshape 'count' such that it is less than 2 x 'ext'
static int reshape_pow2(int ext, int count) {
if (ext > count) {
return 1;
}
int x = 1;
for (; count >= ext * 2; ) {
count >>= 1;
x <<= 1;
}
return x;
}
public:
/// Default ctor
TensorReductionAffineStrided():
status(Status::kErrorInvalidProblem),
extent(),
outer_count(0),
inner_count(0),
workspace_count(0),
grid_shape(0, 0, 0),
threadblock_shape(0, 0, 0) { }
/// Constructor
TensorReductionAffineStrided(
Coord<kRank> extent_,
int target_threadblock_count = 128
):
status(Status::kSuccess),
extent(extent_),
outer_count(0),
inner_count(0),
workspace_count(0) {
//
// Plan the parallel mapping strategy.
//
outer_count = 1;
inner_count = 1;
// Compute number of elements in strided ranks
for (int p = 0; p < kReducedRank - 1; ++p) {
outer_count *= extent[p];
}
for (int p = 0; p < kInnerRank; ++p) {
inner_count *= extent[kReducedRank + p - 1];
}
// Compute plan for the reduction
int extent_c = extent[kRank - 1];
int vectors_c = (extent_c -1 + kVectorLength) / kVectorLength;
// Determine CTA shape
int cta_width = kThreads * kVectorLength;
int cta_ways = reshape_pow2(extent_c, cta_width);
int cta_threads_x = kThreads / cta_ways;
threadblock_shape = dim3(cta_threads_x, 1, std::min(cta_ways, 64));
// This leads to an error.
if (threadblock_shape.z > 1) {
if (threadblock_shape.y != 1) {
status = Status::kErrorInternal;
return;
}
}
// Determine grid shape
int cta_count_x = (vectors_c + cta_threads_x - 1) / cta_threads_x;
int cta_count_y = std::max(1, target_threadblock_count / cta_count_x);
// Limit the number of CTAs assigned to outer dimension
if (int64_t(cta_count_y * threadblock_shape.y) > outer_count) {
cta_count_y = int(outer_count + threadblock_shape.y - 1) / threadblock_shape.y;
}
// Limit the number of CTAs assigned to inner dimension
int cta_count_z = std::max(1, target_threadblock_count / cta_count_y);
if (int64_t(cta_count_z * threadblock_shape.z) > inner_count) {
cta_count_z = int(inner_count + threadblock_shape.z - 1) / threadblock_shape.z;
}
grid_shape = dim3(cta_count_x, cta_count_y, cta_count_z);
workspace_count = (cta_count_z > 1 ? cta_count_z : 0);
// Determine shape of final reduction kernel if needed
grid_final = dim3(cta_count_x, int(outer_count));
threadblock_final = dim3(cta_threads_x, 1, 1);
}
/// Simple check to verify the object is initialized correctly
bool good() const {
return status == Status::kSuccess;
}
/// Size of one CTA's workspace
int64_t workspace_stride() const {
// Error condition
if (!good()) {
return 0;
}
int vector_size_bytes = kVectorLength * sizeof_bits<ElementCompute>::value / 8;
return extent[kRank - 1] * vector_size_bytes;
}
/// Returns the size (in bytes) of a temporary workspace needed for reduction across CTAs
int64_t workspace_size() const {
// Error condition
if (!good()) {
return 0;
}
// No reduction across CTAs
if (grid_shape.z == 1) {
return 0;
}
return workspace_stride() * outer_count * grid_shape.z;
}
/// Performs a reduction
Status reduce(
ElementOutput *dst_ptr, ///< Pointer to destination tensor
int64_t dst_stride[], ///< Stride vector (of length kReducedRank - 1)
ElementSource const *src_ptr, ///< Pointer to source tensor
int64_t src_stride[], ///< Stride vector (of length kRank - 1)
void *device_workspace_ptr = nullptr, ///< Device workspace
ElementCompute reduction_identity = ElementCompute(), ///< Reduciton identity
ReductionOp reduction_op = ReductionOp(), ///< Reduction operator
cudaStream_t stream = nullptr) { ///< CUDA Stream into which all kernels are launched
// Initial status check
if (!good()) {
return status;
}
// Guard against null workspace
if (workspace_count > 1 && device_workspace_ptr == nullptr) {
return Status::kErrorWorkspaceNull;
}
// Define reduction kernel
using ReductionKernel = kernel::TensorReductionAffineStrided<
kRank,
kReducedRank,
ElementOutput,
ElementSource,
ReductionOp,
kVectorLength,
ElementCompute,
kThreads>;
using FinalReductionKernel = kernel::TensorReductionAffineStridedFinal<
kRank,
kReducedRank,
ElementOutput,
ElementSource,
ReductionOp,
kVectorLength,
ElementCompute,
kThreads>;
using Params = typename ReductionKernel::Params;
// Construct the parameters
Params params(
extent,
dst_ptr,
dst_stride,
src_ptr,
src_stride,
static_cast<ElementCompute *>(device_workspace_ptr),
workspace_stride(),
workspace_count,
reduction_op,
reduction_identity);
// Shared memory size
int shared_mem_bytes = sizeof(typename ReductionKernel::SharedStorage);
// Launch the kernel
Kernel<ReductionKernel><<< grid_shape, threadblock_shape, shared_mem_bytes, stream >>>(params);
// Check error condition
if (cudaPeekAtLastError() == cudaSuccess) {
status = Status::kSuccess;
}
else {
status = Status::kErrorInternal;
}
// Final reduction kernel
if (workspace_count) {
Kernel<FinalReductionKernel><<< grid_final, threadblock_final, 0, stream >>>(params);
// Check error condition
if (cudaPeekAtLastError() == cudaSuccess) {
status = Status::kSuccess;
}
else {
status = Status::kErrorInternal;
}
}
return status;
}
/// Helper to use overloaded function call operator
Status operator()(
ElementOutput *dst_ptr, ///< Pointer to destination tensor
int64_t dst_stride[], ///< Stride vector (of length kReducedRank - 1)
ElementSource const *src_ptr, ///< Pointer to source tensor
int64_t src_stride[], ///< Stride vector (of length kRank - 1)
void *device_workspace_ptr = nullptr, ///< Pointer to device workspace
ElementCompute reduction_identity = ElementCompute(), ///< Reduciton identity
ReductionOp reduction_op = ReductionOp(), ///< Reduction operator
cudaStream_t stream = nullptr) { ///< CUDA Stream into which all kernels are launched
return reduce(
dst_ptr,
dst_stride,
src_ptr,
src_stride,
device_workspace_ptr,
reduction_identity,
reduction_op,
stream);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace device
} // namespace reduction
} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////
| 11,448 | C | 30.627072 | 109 | 0.611635 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/device/reduce_split_k.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Kernel performing a reduction over densely packed tensors in global memory
*/
#pragma once
#include "cutlass/device_kernel.h"
#include "cutlass/reduction/kernel/reduce_split_k.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace reduction {
namespace device {
/////////////////////////////////////////////////////////////////////////////////////////////////
template <
typename ReductionKernel_
>
class ReduceSplitK {
public:
using ReductionKernel = ReductionKernel_;
using Shape = typename ReductionKernel::Shape;
using ReductionOp = typename ReductionKernel::ReductionOp;
using OutputOp = typename ReductionKernel::OutputOp;
using ElementWorkspace = typename ReductionKernel::ElementWorkspace;
using ElementAccumulator = typename ReductionKernel::ElementAccumulator;
using ElementOutput = typename ReductionKernel::ElementOutput;
using WorkspaceTensorRef = typename ReductionKernel::WorkspaceTensorRef;
using OutputTensorRef = typename ReductionKernel::OutputTensorRef;
using StrideIndex = typename ReductionKernel::StrideIndex;
/// Argument structure
struct Arguments {
//
// Data members
//
MatrixCoord problem_size;
int partitions;
size_t partition_stride;
WorkspaceTensorRef workspace;
OutputTensorRef destination;
OutputTensorRef source;
typename OutputOp::Params output;
typename ReductionOp::Params reduction;
//
// Methods
//
/// Default ctor
CUTLASS_HOST_DEVICE
Arguments() :
problem_size(0, 0),
partitions(1),
partition_stride(0) { }
CUTLASS_HOST_DEVICE
Arguments(
MatrixCoord const & problem_size
):
problem_size(problem_size) { }
CUTLASS_HOST_DEVICE
Arguments(
MatrixCoord problem_size_,
int partitions_,
size_t partition_stride_,
WorkspaceTensorRef workspace_,
OutputTensorRef destination_,
OutputTensorRef source_,
typename OutputOp::Params output_ = typename OutputOp::Params(),
typename ReductionOp::Params reduction_ = typename ReductionOp::Params()
):
problem_size(problem_size_),
partitions(partitions_),
partition_stride(partition_stride_),
workspace(workspace_),
destination(destination_),
source(source_),
output(output_),
reduction(reduction_)
{
}
};
private:
/// Kernel parameters object
typename ReductionKernel::Params params_;
public:
/// Constructs Reduction SplitK
ReduceSplitK() { }
/// Determines whether the ReduceSplitK can execute the given problem.
static Status can_implement(Arguments const &args) {
return Status::kSuccess;
}
/// Gets the workspace size
static size_t get_workspace_size(Arguments const &args) {
// needs no additional workspace
return 0;
}
/// Initializes Reduction state from arguments.
Status initialize(
Arguments const &args,
void *workspace = nullptr,
cudaStream_t stream = nullptr) {
// initialize the params structure from the arguments
params_ = typename ReductionKernel::Params(
args.problem_size,
args.partitions,
args.partition_stride,
args.workspace,
args.destination,
args.source,
args.output,
args.reduction
);
return Status::kSuccess;
}
/// Initializes Reduction kernel state from arguments.
Status update(Arguments const &args, void *workspace = nullptr) {
// update the params structure from the arguments
params_.workspace.reset(args.workspace.non_const_ref().data());
params_.destination.reset(args.destination.non_const_ref().data());
params_.source.reset(args.source.non_const_ref().data());
params_.output = args.output;
params_.reduction = args.reduction;
return Status::kSuccess;
}
/// Runs the kernel using initialized state.
Status run(cudaStream_t stream = nullptr) {
//
// Launch reduction kernel
//
dim3 block = ReductionKernel::block_shape();
dim3 grid = ReductionKernel::grid_shape(params_.problem_size);
Kernel<ReductionKernel><<< grid, block, 0, stream >>>(params_);
cudaError_t result = cudaGetLastError();
return result == cudaSuccess ? Status::kSuccess : Status::kErrorInternal;
}
/// Runs the kernel using initialized state.
Status operator()(cudaStream_t stream = nullptr) {
return run(stream);
}
/// Runs the kernel using initialized state.
Status operator()(
Arguments const &args,
void *workspace = nullptr,
cudaStream_t stream = nullptr) {
Status status = initialize(args, workspace, stream);
if (status == Status::kSuccess) {
status = run(stream);
}
return status;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace kernel
} // namespace reduction
} // namespace cutlass
| 6,823 | C | 29.464286 | 100 | 0.656456 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/device/tensor_reduce.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Kernel performing a reduction over one or more ranks of an affine tensor
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/array.h"
#include "cutlass/fast_math.h"
#include "cutlass/numeric_types.h"
#include "cutlass/numeric_conversion.h"
#include "cutlass/device_kernel.h"
#include "cutlass/reduction/device/tensor_reduce_affine_strided.h"
#include "cutlass/reduction/device/tensor_reduce_affine_contiguous.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace reduction {
namespace device {
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Tensor reduction operator on specific CUTLASS layouts over exactly one index
template <
typename ElementOutput_,
typename ElementSource_,
typename Layout_,
typename ReductionOp_,
int VectorLength_ = 1,
typename ElementCompute_ = ElementOutput_
>
struct TensorReduction {
using ElementOutput = ElementOutput_;
using ElementSource = ElementSource_;
using Layout = Layout_;
using ReductionOp = ReductionOp_;
static int const kVectorLength = VectorLength_;
using ElementCompute = ElementCompute_;
using TensorCoord = typename Layout::TensorCoord;
/// Reduction operator
using ReductionDeviceStridedOperator = TensorReductionAffineStrided<
4, 3, ElementOutput, ElementSource, ReductionOp, kVectorLength, ElementCompute
>;
using ReductionDeviceContiguousOperator = TensorReductionAffineContiguous<
4, 3, ElementOutput, ElementSource, ReductionOp, kVectorLength, ElementCompute
>;
//
// Data members
//
ReductionDeviceStridedOperator reduction_strided;
ReductionDeviceContiguousOperator reduction_contiguous;
int reduction_index;
//
// Methods
//
///
TensorReduction(
TensorCoord extent,
int reduction_index_
):
reduction_index(reduction_index_) {
Coord<4> extent_affine;
switch (reduction_index) {
case 0:
extent_affine[0] = extent[1];
extent_affine[1] = extent[2];
extent_affine[2] = extent[0];
extent_affine[3] = extent[3];
break;
case 1:
extent_affine[0] = extent[0];
extent_affine[1] = extent[2];
extent_affine[2] = extent[1];
extent_affine[3] = extent[3];
break;
case 2:
extent_affine[0] = extent[0];
extent_affine[1] = extent[1];
extent_affine[2] = extent[2];
extent_affine[3] = extent[3];
break;
case 3:
extent_affine[0] = extent[0];
extent_affine[1] = extent[1];
extent_affine[2] = extent[2];
extent_affine[3] = extent[3];
break;
default: break;
}
if (reduction_index == 3) {
reduction_contiguous = ReductionDeviceContiguousOperator(extent_affine);
}
else {
reduction_strided = ReductionDeviceStridedOperator(extent_affine);
}
}
/// Simple check to verify the object is initialized correctly
bool good() const {
if (reduction_index == 3) {
return reduction_contiguous.good();
}
return reduction_strided.good();
}
/// Size of one workspace
int64_t workspace_stride() const {
if (reduction_index == 3) {
return reduction_contiguous.workspace_stride();
}
else {
return reduction_strided.workspace_stride();
}
}
/// Returns the size (in bytes) of a temporary workspace needed for reduction across CTAs
int64_t workspace_size() const {
if (reduction_index == 3) {
return reduction_contiguous.workspace_size();
}
else {
return reduction_strided.workspace_size();
}
}
/// Helper to use overloaded function call operator
Status reduce(
TensorRef<ElementOutput, Layout> dst_ref,
TensorRef<ElementSource, Layout> src_ref,
void *device_workspace_ptr = nullptr,
ElementCompute reduction_identity = ElementCompute(),
ReductionOp reduction_op = ReductionOp(),
cudaStream_t stream = nullptr) {
int64_t src_stride[3];
int64_t dst_stride[3];
switch (reduction_index) {
case 0:
src_stride[0] = src_ref.stride()[1];
src_stride[1] = src_ref.stride()[0];
src_stride[2] = src_ref.stride()[2];
dst_stride[0] = dst_ref.stride()[1];
dst_stride[1] = dst_ref.stride()[0];
break;
case 1:
src_stride[0] = src_ref.stride()[2];
src_stride[1] = src_ref.stride()[0];
src_stride[2] = src_ref.stride()[1];
dst_stride[0] = dst_ref.stride()[2];
dst_stride[1] = dst_ref.stride()[0];
break;
case 2:
src_stride[0] = src_ref.stride()[2];
src_stride[1] = src_ref.stride()[1];
src_stride[2] = src_ref.stride()[0];
dst_stride[0] = dst_ref.stride()[2];
dst_stride[1] = dst_ref.stride()[1];
break;
case 3:
src_stride[0] = src_ref.stride()[2];
src_stride[1] = src_ref.stride()[1];
src_stride[2] = src_ref.stride()[0];
dst_stride[0] = dst_ref.stride()[2];
dst_stride[1] = dst_ref.stride()[1];
dst_stride[2] = dst_ref.stride()[0];
default: break;
}
if (reduction_index == 3) {
return reduction_contiguous(
dst_ref.data(),
dst_stride,
src_ref.data(),
src_stride,
device_workspace_ptr,
reduction_identity,
reduction_op,
stream);
}
else {
return reduction_strided(
dst_ref.data(),
dst_stride,
src_ref.data(),
src_stride,
device_workspace_ptr,
reduction_identity,
reduction_op,
stream);
}
}
Status operator()(
TensorRef<ElementOutput, Layout> dst_ref,
TensorRef<ElementSource, Layout> src_ref,
void *device_workspace_ptr = nullptr,
ElementCompute reduction_identity = ElementCompute(),
ReductionOp reduction_op = ReductionOp(),
cudaStream_t stream = nullptr) {
return reduce(
dst_ref,
src_ref,
device_workspace_ptr,
reduction_identity,
reduction_op,
stream);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace device
} // namespace reduction
} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////
| 8,152 | C | 29.766038 | 100 | 0.61629 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/kernel/tensor_reduce_affine_strided.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Kernel performing a reduction over one or more ranks of an affine tensor
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/array.h"
#include "cutlass/fast_math.h"
#include "cutlass/numeric_types.h"
#include "cutlass/numeric_conversion.h"
#include "cutlass/device_kernel.h"
#include "cutlass/reduction/thread/reduction_operators.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace reduction {
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace kernel {
/// Parameters structure
template <
int Rank, ///< Rank of source tensor (e.g. NDHWC => 5)
int ReducedRank, ///< Rank of reduced tensor (includes contiguous, e.g. NC => 2)
typename ElementOutput, ///< Data type of output tensor
typename ElementSource, ///< Data type of source tensor
typename ReductionOp, ///< Reduction operator
int VectorLength = 1, ///< Vector length for memory
typename ElementCompute = ElementOutput, ///< Internal compute type - input type of reduction operation
int Threads = 256, ///< Number of participating threads
int BatchSize = 4 ///< Number of elements to load per batch
>
struct TensorReductionAffineStridedParams {
static int const kRank = Rank;
static int const kReducedRank = ReducedRank;
static int const kVectorLength = VectorLength;
static int const kInnerRank = kRank - kReducedRank;
static int const kThreads = Threads;
static int const kBatchSize = BatchSize;
Coord<kRank> extent; /// Extent of source tensor
FastDivmodU64 divmod[kRank - 1]; /// FastDivmod by each strided rank
int64_t dst_stride[kReducedRank - 1]; /// stride (units of bytes) - I, J
int64_t src_stride[kRank - 1]; /// stride (units of bytes) - I, J, K
int64_t workspace_stride; /// stride (units of bytes) between workspace
int64_t workspace_outer_stride; /// stride (units of bytes) between 'rows' of the workspace
int workspace_count; /// number of workspaces
uint64_t inner_count; /// Number of elements in reduced index space
uint64_t outer_count; /// Number of elements in outer index space
ElementOutput * destination; /// Pointer to output tensor of rank kReducedRank
ElementSource const * source; /// Poitner to source pointer of rank kRank
ReductionOp reduction_op; /// Reduction operator
ElementCompute reduction_identity; /// Identity element for reduction operator
ElementCompute *device_workspace; /// Pointer to device workspace for inter-CTA reductions
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorReductionAffineStridedParams() {
}
/// Ctor
TensorReductionAffineStridedParams(
Coord<kRank> extent_, ///< Extent of source tensor
ElementOutput * dst_ptr_, ///< Output tensor data
int64_t dst_stride_[], ///< Stride (units of elements)
ElementSource const * src_ptr_, ///< Source tensor data
int64_t src_stride_[], ///< Stride (units of elements)
ElementCompute *device_workspace_, ///< Pointer to device workspace for inter-CTA reductions
int64_t workspace_stride_, ///< Stride between workspaces
int workspace_count_, ///< Number of workspaces
ReductionOp reduction_op_, ///< Reduction operator
ElementCompute reduction_identity_ = ElementCompute() ///< Identity element for reduction operator
):
extent(extent_),
inner_count(1),
outer_count(1),
destination(dst_ptr_),
source(src_ptr_),
device_workspace(device_workspace_),
workspace_outer_stride(0),
workspace_stride(workspace_stride_),
workspace_count(workspace_count_),
reduction_op(reduction_op_),
reduction_identity(reduction_identity_) {
// Initialize divisors for fast div-mod
for (int p = 1; p < kRank; ++p) {
divmod[p - 1] = FastDivmodU64(uint64_t(extent[p]));
}
int input_size_bits = sizeof_bits<ElementSource>::value;
int output_size_bits = sizeof_bits<ElementOutput>::value;
workspace_outer_stride = workspace_stride * workspace_count;
// Compute strides in units of bytes
for (int p = 0; p < kReducedRank - 1; ++p) {
dst_stride[p] = dst_stride_[p] * output_size_bits / 8;
}
for (int p = 0; p < kRank - 1; ++p) {
src_stride[p] = src_stride_[p] * input_size_bits / 8;
}
// Compute number of elements in strided ranks
for (int p = 0; p < kReducedRank - 1; ++p) {
outer_count *= uint64_t(extent[p]);
}
for (int p = 0; p < kInnerRank; ++p) {
inner_count *= uint64_t(extent[kReducedRank + p - 1]);
}
}
};
/// Kernel to reduce a tensor with affine layout over a set of ranks *EXCLUDING* the contiguous
/// rank. This leads to favorable vectorized memory accesses over the contiguous rank.
template <
int Rank, ///< Rank of source tensor (e.g. NDHWC => 5)
int ReducedRank, ///< Rank of reduced tensor (includes contiguous, e.g. NC => 2)
typename ElementOutput, ///< Data type of output tensor
typename ElementSource, ///< Data type of source tensor
typename ReductionOp, ///< Reduction operator
int VectorLength = 1, ///< Vector length for memory
typename ElementCompute = ElementOutput, ///< Internal compute type - input type of reduction operation
int Threads = 256, ///< Number of participating threads
int BatchSize = 4 ///< Number of elements to load per batch
>
class TensorReductionAffineStrided {
public:
static int const kRank = Rank;
static int const kReducedRank = ReducedRank;
static int const kVectorLength = VectorLength;
static int const kInnerRank = kRank - kReducedRank;
static int const kThreads = Threads;
static int const kBatchSize = BatchSize;
using ComputeFragment = Array<ElementCompute, VectorLength>;
using SourceFragment = AlignedArray<ElementSource, VectorLength>;
using OutputFragment = AlignedArray<ElementOutput, VectorLength>;
/// Shared memory allocation used for reduction within the CTA
struct SharedStorage {
Array<ElementCompute, kThreads * kVectorLength> workspace;
};
/// Parameters structure
using Params = TensorReductionAffineStridedParams<
Rank,
ReducedRank,
ElementOutput,
ElementSource,
ReductionOp,
VectorLength,
ElementCompute,
Threads,
BatchSize
>;
private:
/// Computes the coordinate and offset of a given linear index
CUTLASS_DEVICE
void compute_inner_coord_and_offset_(
Params const ¶ms,
Coord<kInnerRank> & coord,
int64_t &src_offset,
uint64_t linear_idx) const {
// Decompose into coordinate
coord = CoordinateDecomposition<kInnerRank>(linear_idx, ¶ms.divmod[kReducedRank - 1]);
// Compute linear offset
src_offset = 0;
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < kInnerRank; ++i) {
src_offset += params.src_stride[kReducedRank + i - 1] * coord[i];
}
}
/// Computes the coordinate and offset of a given linear index
CUTLASS_DEVICE
void compute_outer_coord_and_offset_(
Params const ¶ms,
Coord<kReducedRank - 1> & coord,
int64_t &dst_offset,
int64_t &src_offset,
uint64_t linear_idx) const {
// Decompose linear coordinate
coord = CoordinateDecomposition<kReducedRank - 1>(linear_idx, params.divmod);
// Compute offset into tensors
dst_offset = 0;
src_offset = 0;
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < kReducedRank - 1; ++i) {
dst_offset += params.dst_stride[i] * coord[i];
src_offset += params.src_stride[i] * coord[i];
}
}
/// Reduces over the reduction indices
CUTLASS_DEVICE
ComputeFragment reduce_indices_(
Params const ¶ms,
ElementCompute *threadblock_workspace,
char const *src_byte_ptr) {
NumericArrayConverter<ElementCompute, ElementSource, VectorLength> convert_source;
ReductionOp reduction_op(params.reduction_op);
// Accumulated output
ComputeFragment identity_frag;
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < identity_frag.size(); ++i) {
identity_frag[i] = params.reduction_identity;
}
if (!params.inner_count) {
return identity_frag;
}
ComputeFragment accumulator = identity_frag;
// Compute the coordinate of the first access
int64_t src_byte_offset = 0;
Coord<kInnerRank> coord;
uint64_t linear_idx = threadIdx.z + blockIdx.z * blockDim.z;
compute_inner_coord_and_offset_(params, coord, src_byte_offset, linear_idx);
// Load the first vector
SourceFragment source_fragment[kBatchSize];
bool not_done = true;
// Iterate over vectors in a linearized reduction index space
while (not_done) {
bool guards[kBatchSize];
// Issue a batch of loads
CUTLASS_PRAGMA_UNROLL
for (int b = 0; b < kBatchSize; ++b) {
if (linear_idx < params.inner_count) {
source_fragment[b] = *reinterpret_cast<SourceFragment const *>(src_byte_ptr + src_byte_offset);
guards[b] = true;
}
else {
guards[b] = false;
not_done = false;
}
linear_idx += blockDim.z * gridDim.z;
compute_inner_coord_and_offset_(params, coord, src_byte_offset, linear_idx);
}
// Perform a batch of reduction operations
CUTLASS_PRAGMA_UNROLL
for (int b = 0; b < kBatchSize; ++b) {
if (guards[b]) {
auto cvt = convert_source(source_fragment[b]);
accumulator = cutlass::reduction::thread::detail::ApplyArrayOperator(
reduction_op,
accumulator,
cvt);
}
}
};
// Optional reduction within a CTA
if (blockDim.z > 1) {
// Linearized thread ID
int thread_idx = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * threadIdx.z);
// all threads store to workspace
ComputeFragment *frag_ptr = reinterpret_cast<ComputeFragment *>(threadblock_workspace);
frag_ptr[thread_idx] = accumulator;
__syncthreads();
if (threadIdx.z == 0) {
// Load all additional block indices
for (int z = 1; z < blockDim.z; ++z) {
ComputeFragment frag = frag_ptr[thread_idx + z * blockDim.x * blockDim.y];
accumulator = cutlass::reduction::thread::detail::ApplyArrayOperator(
reduction_op,
accumulator,
frag);
}
}
__syncthreads();
}
return accumulator;
}
public:
/// Perform a reduction
CUTLASS_DEVICE
void operator()(Params const ¶ms, SharedStorage &shared_storage) {
int coord_c = (blockIdx.x * blockDim.x + threadIdx.x) * kVectorLength;
char const * src_byte_ptr = reinterpret_cast<char const *>(params.source + coord_c);
char * dst_byte_ptr = nullptr;
// If performing a reduction across CTAs, redirect output to device workspace
if (gridDim.z == 1) {
dst_byte_ptr = reinterpret_cast<char *>(params.destination + coord_c);
}
else {
dst_byte_ptr = reinterpret_cast<char *>(params.device_workspace + coord_c);
}
// If the C index is out of bounds, exit
if (coord_c >= params.extent[kRank - 1]) {
return;
}
int64_t idx_linear = blockIdx.y * blockDim.y + threadIdx.y;
// Use modulo division to compute location
Coord<kReducedRank - 1> outer_coord;
int64_t dst_byte_offset;
int64_t src_byte_offset;
compute_outer_coord_and_offset_(
params,
outer_coord,
dst_byte_offset,
src_byte_offset,
idx_linear);
if (gridDim.z == 1) {
/// Complete the reduction with no workspace
while (idx_linear < params.outer_count) {
ComputeFragment result;
result = reduce_indices_(
params,
shared_storage.workspace.data(),
src_byte_ptr + src_byte_offset);
// Store the result after possible final reduction within the CTA
if (threadIdx.z == 0) {
// Convert to output type and store
NumericArrayConverter<ElementOutput, ElementCompute, VectorLength> convert_output;
auto cvt = convert_output(result);
*reinterpret_cast<OutputFragment *>(dst_byte_ptr + dst_byte_offset) =
reinterpret_cast<OutputFragment const &>(cvt);
}
// Update indices and pointers
idx_linear += gridDim.y * blockDim.y;
compute_outer_coord_and_offset_(
params,
outer_coord,
dst_byte_offset,
src_byte_offset,
idx_linear);
} // while
}
else {
/// Complete the reduction with a device workspace
while (idx_linear < params.outer_count) {
ComputeFragment result;
result = reduce_indices_(
params,
shared_storage.workspace.data(),
src_byte_ptr + src_byte_offset);
// Store the result after possible final reduction within the CTA
if (threadIdx.z == 0) {
int64_t byte_offset =
blockIdx.z * params.workspace_stride + idx_linear * params.workspace_outer_stride;
// No conversion - store in compute type
*reinterpret_cast<ComputeFragment *>(dst_byte_ptr + byte_offset) =
reinterpret_cast<ComputeFragment const &>(result);
}
// Update indices and pointers
idx_linear += gridDim.y * blockDim.y;
compute_outer_coord_and_offset_(
params,
outer_coord,
dst_byte_offset,
src_byte_offset,
idx_linear);
} // while (outer index)
} // if ()
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Kernel to perform final reduction
template <
int Rank, ///< Rank of source tensor (e.g. NDHWC => 5)
int ReducedRank, ///< Rank of reduced tensor (includes contiguous, e.g. NC => 2)
typename ElementOutput, ///< Data type of output tensor
typename ElementSource, ///< Data type of source tensor
typename ReductionOp, ///< Reduction operator
int VectorLength = 1, ///< Vector length for memory
typename ElementCompute = ElementOutput, ///< Internal compute type - input type of reduction operation
int Threads = 256, ///< Number of participating threads
int BatchSize = 4 ///< Number of elements to load per batch
>
class TensorReductionAffineStridedFinal {
public:
static int const kRank = Rank;
static int const kReducedRank = ReducedRank;
static int const kVectorLength = VectorLength;
static int const kInnerRank = kRank - kReducedRank;
static int const kThreads = Threads;
static int const kBatchSize = BatchSize;
using ComputeFragment = Array<ElementCompute, VectorLength>;
using SourceFragment = AlignedArray<ElementSource, VectorLength>;
using OutputFragment = AlignedArray<ElementOutput, VectorLength>;
/// Shared memory
struct SharedStorage { };
/// Parameters structure
using Params = TensorReductionAffineStridedParams<
Rank,
ReducedRank,
ElementOutput,
ElementSource,
ReductionOp,
VectorLength,
ElementCompute,
Threads,
BatchSize
>;
private:
/// Computes the coordinate and offset of a given linear index
CUTLASS_DEVICE
void compute_outer_coord_and_offset_(
Params const ¶ms,
Coord<kReducedRank - 1> & coord,
int64_t &dst_offset,
uint64_t linear_idx) const {
// Decompose linear index
coord = CoordinateDecomposition<kReducedRank - 1>(linear_idx, params.divmod);
// Compute tensor offset
dst_offset = 0;
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < kReducedRank - 1; ++i) {
dst_offset += params.dst_stride[i] * coord[i];
}
}
/// Reduces over the reduction indices
CUTLASS_DEVICE
ComputeFragment reduce_indices_(
Params const ¶ms,
char *src_byte_ptr) {
ReductionOp reduction_op(params.reduction_op);
// Accumulated output
ComputeFragment identity_frag;
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < identity_frag.size(); ++i) {
identity_frag[i] = params.reduction_identity;
}
ComputeFragment accumulator = identity_frag;
ComputeFragment workspace_fragments[kBatchSize];
// Partially unrolled loop
for (int idx = 0; idx < params.workspace_count; idx += kBatchSize) {
// Issue a batch of loads
CUTLASS_PRAGMA_UNROLL
for (int b = 0; b < kBatchSize; ++b) {
if (idx + b < params.workspace_count) {
workspace_fragments[b] =
*reinterpret_cast<ComputeFragment *>(src_byte_ptr);
}
else {
workspace_fragments[b] = identity_frag;
}
src_byte_ptr += + params.workspace_stride;
}
// Perform a reduction
CUTLASS_PRAGMA_UNROLL
for (int b = 0; b < kBatchSize; ++b) {
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < kVectorLength; ++i) {
accumulator[i] = reduction_op(accumulator[i], workspace_fragments[b][i]);
}
}
}
return accumulator;
}
public:
//
// Methods
//
/// Perform a reduction
CUTLASS_DEVICE
void operator()(Params const ¶ms, SharedStorage &shared_storage) {
int coord_c = (blockIdx.x * blockDim.x + threadIdx.x) * kVectorLength;
char * src_byte_ptr = reinterpret_cast<char *>(params.device_workspace + coord_c);
char * dst_byte_ptr = reinterpret_cast<char *>(params.destination + coord_c);
// If the C index is out of bounds, exit
if (coord_c >= params.extent[kRank - 1]) {
return;
}
int64_t idx_linear = blockIdx.y * blockDim.y + threadIdx.y;
// Use modulo division to compute location
Coord<kReducedRank - 1> outer_coord;
int64_t dst_byte_offset;
compute_outer_coord_and_offset_(
params,
outer_coord,
dst_byte_offset,
idx_linear);
/// Complete the reduction
while (idx_linear < params.outer_count) {
int64_t src_byte_offset = idx_linear * params.workspace_outer_stride;
ComputeFragment result = reduce_indices_(
params,
src_byte_ptr + src_byte_offset);
// Convert to output type and store
NumericArrayConverter<ElementOutput, ElementCompute, VectorLength> convert_output;
auto cvt = convert_output(result);
*reinterpret_cast<OutputFragment *>(dst_byte_ptr + dst_byte_offset) =
reinterpret_cast<OutputFragment const &>(cvt);
// Update indices and pointers
idx_linear += gridDim.y * blockDim.y;
compute_outer_coord_and_offset_(
params,
outer_coord,
dst_byte_offset,
idx_linear);
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace kernel
} // namespace reduction
} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////
| 21,662 | C | 32.742991 | 109 | 0.608808 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/kernel/reduce_split_k.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Kernel performing a reduction over densely packed tensors in global memory
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/tensor_ref.h"
#include "cutlass/numeric_types.h"
#include "cutlass/array.h"
#include "cutlass/functional.h"
#include "cutlass/matrix_shape.h"
#include "cutlass/numeric_conversion.h"
#include "cutlass/layout/matrix.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace reduction {
namespace kernel {
/////////////////////////////////////////////////////////////////////////////////////////////////
template <
typename Shape_, ///< shape of CTA (concept: MatrixShape)
typename OutputOp_ , ///< output operator (concept: epilogue::thread operator)
typename ReductionOp_, ///< reduction operator (concept: ReductionOperator)
int PartitionsPerStage = 4 ///< number of partitions to issue
>
class ReduceSplitK {
public:
using Shape = Shape_;
using ReductionOp = ReductionOp_;
using OutputOp = OutputOp_;
static int const kElementsPerAccess = OutputOp::kCount;
static int const kPartitionsPerStage = PartitionsPerStage;
using ElementWorkspace = typename ReductionOp::Element;
using ElementAccumulator = typename ReductionOp::ElementAccumulator;
using ElementOutput = typename OutputOp::ElementOutput;
using WorkspaceTensorRef = TensorRef<ElementWorkspace, layout::RowMajor>;
using OutputTensorRef = TensorRef<ElementOutput, layout::RowMajor>;
using StrideIndex = typename WorkspaceTensorRef::Layout::Stride::Index;
using FragmentWorkspace = AlignedArray<ElementWorkspace, kElementsPerAccess>;
using FragmentAccumulator = Array<ElementAccumulator, kElementsPerAccess>;
using FragmentOutput = AlignedArray<ElementOutput, kElementsPerAccess>;
//
// Types
//
/// Params structure
struct Params {
MatrixCoord problem_size;
int partitions;
size_t partition_stride;
WorkspaceTensorRef workspace;
OutputTensorRef destination;
OutputTensorRef source;
typename OutputOp::Params output;
typename ReductionOp::Params reduction;
//
// Methods
//
CUTLASS_HOST_DEVICE
Params() { }
CUTLASS_HOST_DEVICE
Params(
MatrixCoord problem_size_,
int partitions_,
size_t partition_stride_,
WorkspaceTensorRef workspace_,
OutputTensorRef destination_,
OutputTensorRef source_,
typename OutputOp::Params output_ = typename OutputOp::Params(),
typename ReductionOp::Params reduction_ = typename ReductionOp::Params()
):
problem_size(problem_size_),
partitions(partitions_),
partition_stride(sizeof(FragmentWorkspace) * partition_stride_ / kElementsPerAccess),
workspace(workspace_),
destination(destination_),
source(source_),
output(output_),
reduction(reduction_) {
}
};
struct SharedStorage { };
public:
/// Computes the grid size given a chosen threadblock shape
CUTLASS_HOST_DEVICE
static dim3 grid_shape(
cutlass::MatrixCoord problem_size) {
return dim3(
(problem_size.row() + Shape::kRow - 1) / Shape::kRow,
(problem_size.column() + Shape::kColumn - 1) / Shape::kColumn);
}
/// Determines the threadblock shape
CUTLASS_HOST_DEVICE
static dim3 block_shape() {
return dim3(Shape::kColumn / kElementsPerAccess, Shape::kRow);
}
/// Perform a reduction
CUTLASS_DEVICE
void operator()(Params const ¶ms, SharedStorage &storage) {
// Determine CTA position
MatrixCoord thread_offset(
MatrixCoord::Index(int(blockIdx.x) * Shape::kRow + threadIdx.y),
MatrixCoord::Index(int(blockIdx.y) * Shape::kColumn + threadIdx.x * kElementsPerAccess)
);
// One guard conditional
if (!(thread_offset.row() < params.problem_size.row() &&
thread_offset.column() < params.problem_size.column())) {
return;
}
ReductionOp reduction_op(params.reduction);
FragmentAccumulator accumulator;
accumulator.clear();
//
// Load the first slice
//
char const *workspace_ptr =
reinterpret_cast<char const *>(
params.workspace.data() + params.workspace.offset(thread_offset));
FragmentWorkspace workspace_frag[kPartitionsPerStage];
//
// Construct the output operator
//
OutputOp output_op(params.output);
//
// Load and accumulate with a simple batched loading sequence.
//
CUTLASS_PRAGMA_NO_UNROLL
for (int k = 0; k < params.partitions; k += kPartitionsPerStage) {
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < kPartitionsPerStage; ++i) {
if (k + i < params.partitions) {
workspace_frag[i] = *reinterpret_cast<FragmentWorkspace const *>(workspace_ptr);
workspace_ptr += params.partition_stride;
}
}
CUTLASS_PRAGMA_UNROLL
for (int i = 0; i < kPartitionsPerStage; ++i) {
if (k + i < params.partitions) {
accumulator = reduction_op(accumulator, workspace_frag[i]);
}
}
}
//
// Conditionally load the source
//
FragmentOutput source_frag;
source_frag.clear();
FragmentOutput const *source_ptr = reinterpret_cast<FragmentOutput const *>(
params.source.data() + params.source.offset(thread_offset));
if (output_op.is_source_needed()) {
reinterpret_cast<FragmentOutput &>(source_frag) = *source_ptr;
}
//
// Compute the output
//
typename OutputOp::FragmentOutput output_frag = output_op(accumulator, source_frag);
//
// Store
//
FragmentOutput *dest_ptr = reinterpret_cast<FragmentOutput *>(
params.destination.data() + params.destination.offset(thread_offset));
*dest_ptr = reinterpret_cast<FragmentOutput const &>(output_frag);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace kernel
} // namespace reduction
} // namespace cutlass
| 7,897 | C | 30.718875 | 100 | 0.651387 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/reduction/kernel/reduce_softmax_final.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Kernel performing a final reduction for softmax
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/numeric_types.h"
#include "cutlass/array.h"
#include "cutlass/functional.h"
#include "cutlass/matrix_shape.h"
#include "cutlass/numeric_conversion.h"
#include "cutlass/arch/memory.h"
#include "cutlass/arch/memory_sm75.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace reduction {
namespace kernel {
template <
typename ElementNorm_,
typename ElementSum_,
typename ElementSoftmaxCompute_,
typename ThreadblockShape_,
bool GroupedProblem = false
>
class ApplySoftmaxFinalReduction {
public:
using ElementNorm = ElementNorm_;
using ElementSum = ElementSum_;
using ElementSoftmaxCompute = ElementSoftmaxCompute_;
using ThreadblockShape = ThreadblockShape_;
static const bool isGroupedProblem = GroupedProblem;
//
// Arguments
//
struct Arguments {
cutlass::gemm::GemmCoord* problem_sizes;
cutlass::gemm::GemmCoord problem_size;
ElementNorm* block_Norm;
ElementSum* block_Sum;
int64_t* offset_Norm_Device;
int64_t* offset_Sum_Device;
int64_t batch_stride_Max;
int64_t batch_stride_Sum;
//
// Methods
//
Arguments() { }
// Non-grouped constructor without batching
Arguments(
cutlass::gemm::GemmCoord problem_size,
ElementNorm* block_Norm,
ElementSum* block_Sum
):
problem_size(problem_size),
block_Norm(block_Norm),
block_Sum(block_Sum),
problem_sizes(nullptr),
offset_Norm_Device(nullptr),
offset_Sum_Device(nullptr),
batch_stride_Max(0),
batch_stride_Sum(0)
{
}
// Non-grouped constructor with batching
Arguments(
cutlass::gemm::GemmCoord problem_size,
ElementNorm* block_Norm,
ElementSum* block_Sum,
int64_t batch_stride_Max,
int64_t batch_stride_Sum
):
problem_size(problem_size),
block_Norm(block_Norm),
block_Sum(block_Sum),
batch_stride_Max(batch_stride_Max),
batch_stride_Sum(batch_stride_Sum),
problem_sizes(nullptr),
offset_Norm_Device(nullptr),
offset_Sum_Device(nullptr)
{
}
// Grouped constructor
Arguments(
cutlass::gemm::GemmCoord *problem_sizes,
ElementNorm* block_Norm,
ElementSum* block_Sum,
int64_t* offset_Norm_Device,
int64_t* offset_Sum_Device
):
problem_sizes(problem_sizes),
problem_size(cutlass::gemm::GemmCoord(0, 0, 0)),
block_Norm(block_Norm),
block_Sum(block_Sum),
offset_Norm_Device(offset_Norm_Device),
offset_Sum_Device(offset_Sum_Device)
{
}
};
struct SharedStorage {
};
//
// Params struct
//
struct Params {
Arguments args;
//
// Methods
//
Params() { }
Params(Arguments const &args_): args(args_) { }
};
private:
public:
CUTLASS_DEVICE
ApplySoftmaxFinalReduction() { }
CUTLASS_DEVICE
void operator()(Params const ¶ms, SharedStorage &shared_storage) {
apply(params, shared_storage);
}
private:
/// Full reduction
CUTLASS_DEVICE
void apply(Params const ¶ms, SharedStorage &shared_storage) {
int tid = threadIdx.x;
int bid = blockIdx.x;
int bdim = blockDim.x;
int block_batch = blockIdx.z;
// defining three vars for a general reduction module
cutlass::gemm::GemmCoord problem_size = isGroupedProblem ? params.args.problem_sizes[bid] : params.args.problem_size;
int m_dim_in_loop = isGroupedProblem ? problem_size.m() : tid + bdim;
int access_offset = isGroupedProblem ? 0 : bid * bdim;
if (!isGroupedProblem && access_offset + tid >= problem_size.m()) return;
ElementNorm *curr_ptr_Max = isGroupedProblem ? \
params.args.block_Norm + params.args.offset_Norm_Device[bid] : \
params.args.block_Norm + block_batch * params.args.batch_stride_Max;
ElementSum *curr_ptr_Sum = isGroupedProblem ? \
params.args.block_Sum + params.args.offset_Sum_Device[bid] : \
params.args.block_Sum + block_batch * params.args.batch_stride_Sum;
int threadblock_num = (problem_size.n() + ThreadblockShape::kN - 1) / ThreadblockShape::kN;
using ConvertSumOutput = cutlass::NumericConverter<ElementSum, ElementSoftmaxCompute>;
using ConvertNormOutput = cutlass::NumericConverter<ElementNorm, ElementSoftmaxCompute>;
using ConvertSum = cutlass::NumericConverter<ElementSoftmaxCompute, ElementSum>;
using ConvertNorm = cutlass::NumericConverter<ElementSoftmaxCompute, ElementNorm>;
ConvertSum convert_sum;
ConvertNorm convert_norm;
ConvertSumOutput convert_sum_output;
ConvertNormOutput convert_norm_output;
uint32_t float_max_bits = 0xff7fffff;
float min_float = reinterpret_cast<float const &>(float_max_bits);
CUTLASS_PRAGMA_UNROLL
for (int idx_m = tid; idx_m < m_dim_in_loop; idx_m += bdim) {
ElementNorm *access_n = curr_ptr_Max + idx_m + access_offset;
ElementSum *access_s = curr_ptr_Sum + idx_m + access_offset;
ElementNorm *access_n_bak = access_n;
ElementSum *access_s_bak = access_s;
ElementSoftmaxCompute max_val = ElementSoftmaxCompute(min_float);
ElementSoftmaxCompute sum_val = ElementSoftmaxCompute(0);
ElementNorm fetch_n;
ElementSum fetch_s;
CUTLASS_PRAGMA_UNROLL
for (int idx_n = 0; idx_n < threadblock_num; idx_n++) {
cutlass::arch::global_load<ElementNorm, sizeof(ElementNorm)>(fetch_n, access_n, true);
max_val = cutlass::fast_max(max_val, convert_norm(fetch_n));
access_n += problem_size.m();
}
access_n = access_n_bak;
CUTLASS_PRAGMA_UNROLL
for (int idx_n = 0; idx_n < threadblock_num; idx_n++) {
cutlass::arch::global_load<ElementNorm, sizeof(ElementNorm)>(fetch_n, access_n, true);
cutlass::arch::global_load<ElementSum, sizeof(ElementSum)>(fetch_s, access_s, true);
sum_val += convert_sum(fetch_s) * cutlass::fast_exp(convert_norm(fetch_n) - max_val);
access_n += problem_size.m();
access_s += problem_size.m();
}
ElementSoftmaxCompute inv_sum = cutlass::constants::one<ElementSoftmaxCompute>() / sum_val;
access_n = access_n_bak;
access_s = access_s_bak;
access_n[0] = convert_norm_output(max_val);
access_s[0] = convert_sum_output(inv_sum);
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace kernel
} // namespace reduction
} // namespace cutlass
| 8,762 | C | 31.697761 | 121 | 0.632618 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/tensor_op_multiplicand_sm70.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/coord.h"
#include "cutlass/layout/pitch_linear.h"
/////////////////////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace layout {
// template <
// int ElementSize,
// gemm::Operand Operand
// >
// struct VoltaTensorOpMultiplicandCongruous;
// template <
// int ElementSize,
// gemm::Operand Operand
// >
// struct ColumnMajorVoltaTensorOpMultiplicandCongruous;
// template <
// int ElementSize,
// gemm::Operand Operand
// >
// struct RowMajorVoltaTensorOpMultiplicandCongruous;
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear memory.
template <int ElementSize>
struct VoltaTensorOpMultiplicandCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
/// This layout is optimized for 128b accesses
static int const kAccessSize = 128;
/// Fundamental tile shape in units of vectors
using TileShape = PitchLinearShape<8, 4>;
/// Fundamental partition shape in units of vectors
using PartitionShape = PitchLinearShape<8, 2>;
//
// Static constants
//
static int const kElementSize = ElementSize;
static int const kElementsPerAccess = kAccessSize / kElementSize;
using PartitionCount = PitchLinearShape<
TileShape::kContiguous / PartitionShape::kContiguous,
TileShape::kStrided / PartitionShape::kStrided
>;
using AccessCount = PitchLinearShape<
PartitionShape::kContiguous,
PartitionShape::kStrided
>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
VoltaTensorOpMultiplicandCongruous(Index ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
VoltaTensorOpMultiplicandCongruous(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static VoltaTensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return VoltaTensorOpMultiplicandCongruous(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
// First, compute c and s of vector within source (in units of vector accesses)
int vec_contiguous_idx = coord.contiguous() / kElementsPerAccess;
int vec_strided_idx = coord.strided();
// Compute the fundamental tile being accessed
int tile_contiguous_idx = vec_contiguous_idx / TileShape::kContiguous;
int tile_strided_idx = vec_strided_idx / TileShape::kStrided;
int tile_contiguous_residual = vec_contiguous_idx % TileShape::kContiguous;
int tile_strided_residual = vec_strided_idx % TileShape::kStrided;
// Then swizzle in a tile
// Swizzle pattern is (tid[2:0] << 2)|(tid[4:3] ^ tid[2:1])
int permuted_strided_within_tile = (tile_contiguous_residual >> 1);
int permuted_contiguous_within_tile = (tile_strided_residual ^ permuted_strided_within_tile) |
((tile_contiguous_residual & 1) << 2);
// Compute final element location
int element_contiguous = (tile_contiguous_idx * TileShape::kContiguous +
permuted_contiguous_within_tile) * kElementsPerAccess + (coord.contiguous() % kElementsPerAccess);
int element_strided = tile_strided_idx * TileShape::kStrided + permuted_strided_within_tile;
return element_contiguous + element_strided * stride_[0];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous
template <int ElementSize>
struct ColumnMajorVoltaTensorOpMultiplicandCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = VoltaTensorOpMultiplicandCongruous<ElementSize>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorVoltaTensorOpMultiplicandCongruous(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorVoltaTensorOpMultiplicandCongruous(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorVoltaTensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return ColumnMajorVoltaTensorOpMultiplicandCongruous(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
/// Template mapping a row-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous
template <int ElementSize>
struct RowMajorVoltaTensorOpMultiplicandCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = VoltaTensorOpMultiplicandCongruous<ElementSize>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorVoltaTensorOpMultiplicandCongruous(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorVoltaTensorOpMultiplicandCongruous(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorVoltaTensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return RowMajorVoltaTensorOpMultiplicandCongruous(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
/// Template based on element size (in bits) - defined in terms of pitch-linear memory.
// template <int ElementSize, Operand Operand>
template <int ElementSize>
struct VoltaTensorOpMultiplicandBCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
/// This layout is optimized for 128b accesses
static int const kAccessSize = 128;
/// Fundamental tile shape in units of vectors
using TileShape = PitchLinearShape<8, 4>;
/// Fundamental partition shape in units of vectors
using PartitionShape = PitchLinearShape<4, 4>;
//
// Static constants
//
static int const kElementSize = ElementSize;
static int const kElementsPerAccess = kAccessSize / kElementSize;
using PartitionCount = PitchLinearShape<
TileShape::kContiguous / PartitionShape::kContiguous,
TileShape::kStrided / PartitionShape::kStrided
>;
using AccessCount = PitchLinearShape<
PartitionShape::kContiguous,
PartitionShape::kStrided
>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
VoltaTensorOpMultiplicandBCongruous(Index ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
VoltaTensorOpMultiplicandBCongruous(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static VoltaTensorOpMultiplicandBCongruous packed(TensorCoord const &extent) {
return VoltaTensorOpMultiplicandBCongruous(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
// First, compute c and s of vector within source (in units of vector accesses)
int vec_contiguous_idx = coord.contiguous() / kElementsPerAccess;
int vec_strided_idx = coord.strided();
// Compute the fundamental tile being accessed
int tile_contiguous_idx = vec_contiguous_idx / TileShape::kContiguous;
int tile_strided_idx = vec_strided_idx / TileShape::kStrided;
int tile_contiguous_residual = vec_contiguous_idx % TileShape::kContiguous;
int tile_strided_residual = vec_strided_idx % TileShape::kStrided;
// Then swizzle in a tile
// Swizzle pattern is (tid[1:0] << 3)|(tid & 0x4)|(tid[1:0])
int permuted_strided_within_tile = (tile_contiguous_residual & 0x3);
int permuted_contiguous_within_tile = (tile_strided_residual ^ permuted_strided_within_tile) |
(tile_contiguous_residual & 0x4);
// Compute final element location
int element_contiguous = (tile_contiguous_idx * TileShape::kContiguous +
permuted_contiguous_within_tile) * kElementsPerAccess + (coord.contiguous() % kElementsPerAccess);
int element_strided = tile_strided_idx * TileShape::kStrided + permuted_strided_within_tile;
return element_contiguous + element_strided * stride_[0];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous
template <int ElementSize>
struct ColumnMajorVoltaTensorOpMultiplicandBCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = VoltaTensorOpMultiplicandBCongruous<ElementSize>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorVoltaTensorOpMultiplicandBCongruous(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorVoltaTensorOpMultiplicandBCongruous(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorVoltaTensorOpMultiplicandBCongruous packed(TensorCoord const &extent) {
return ColumnMajorVoltaTensorOpMultiplicandBCongruous(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
/// Template mapping a row-major view of pitch-linear memory to VoltaTensorOpMultiplicandCongruous
template <int ElementSize>
struct RowMajorVoltaTensorOpMultiplicandBCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = VoltaTensorOpMultiplicandBCongruous<ElementSize>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorVoltaTensorOpMultiplicandBCongruous(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorVoltaTensorOpMultiplicandBCongruous(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorVoltaTensorOpMultiplicandBCongruous packed(TensorCoord const &extent) {
return RowMajorVoltaTensorOpMultiplicandBCongruous(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and KBlock size (in elements).
template <int ElementSize, int KBlock>
struct VoltaTensorOpMultiplicandCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
/// This layout is optimized for 64b accesses
static int const kAccessSize = 64;
//
// Static constants
//
static int const kElementSize = ElementSize;
static int const kElementsPerAccess = kAccessSize / kElementSize;
static int const kKBlock = KBlock;
private:
//
// Data members
//
/// Stride data member. For GEMM, it equals to KBlock x stage.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
VoltaTensorOpMultiplicandCrosswise(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
VoltaTensorOpMultiplicandCrosswise(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static VoltaTensorOpMultiplicandCrosswise packed(TensorCoord const &extent) {
return VoltaTensorOpMultiplicandCrosswise(extent[1]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
//
// First, compute c and s of vector within source (in units of vector
// accesses)
//
int vec_contiguous_idx = coord.contiguous() / kElementsPerAccess;
int vec_strided_idx = coord.strided();
//
// Then swizzle
// The mapping is like this:
// id[1:0]|(id[3]^id[4])|id[2]
int vec_strided_within_tile = vec_contiguous_idx & 0x7;
int permuted_vec_contiguous =
(vec_strided_idx & (~0xF)) + (vec_strided_idx & 0x3) * 4 +
(((vec_strided_idx >> 2) ^ ((vec_strided_idx & 0x10) >> 3)) & 0x3);
permuted_vec_contiguous ^= ((vec_strided_within_tile >> 1) & 0x3);
int permuted_vec_strided = vec_contiguous_idx;
//
// Compute final element location
//
int element_contiguous = permuted_vec_contiguous * kElementsPerAccess +
(coord.contiguous() % kElementsPerAccess);
return element_contiguous + permuted_vec_strided * (stride_[0] * kElementsPerAccess);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[0] * stride_[0];
}
};
/// Template mapping a column-major view of pitch-linear memory to
/// VoltaTensorOpMultiplicandCrosswise
template <int ElementSize, int KBlock>
struct ColumnMajorVoltaTensorOpMultiplicandCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = VoltaTensorOpMultiplicandCrosswise<ElementSize, KBlock>;
/// This layout is optimized for 64b accesses
static int const kAccessSize = Base::kAccessSize;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorVoltaTensorOpMultiplicandCrosswise(Index ldm = 0) : layout_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorVoltaTensorOpMultiplicandCrosswise(Stride stride) : layout_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorVoltaTensorOpMultiplicandCrosswise packed(
TensorCoord const &extent) {
return ColumnMajorVoltaTensorOpMultiplicandCrosswise(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return layout_.stride(); }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return layout_.stride(); }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
/// Template mapping a row-major view of pitch-linear memory to
/// TensorOpMultiplicandCrosswise
template <int ElementSize, int KBlock>
struct RowMajorVoltaTensorOpMultiplicandCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = VoltaTensorOpMultiplicandCrosswise<ElementSize, KBlock>;
/// This layout is optimized for 64b accesses
static int const kAccessSize = Base::kAccessSize;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorVoltaTensorOpMultiplicandCrosswise(Index ldm = 0) : layout_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorVoltaTensorOpMultiplicandCrosswise(Stride stride) : layout_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorVoltaTensorOpMultiplicandCrosswise packed(
TensorCoord const &extent) {
return RowMajorVoltaTensorOpMultiplicandCrosswise(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return layout_.stride(); }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return layout_.stride(); }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
} // namespace layout
} // namespace cutlass
/////////////////////////////////////////////////////////////////////////////////////////////////
| 29,599 | C | 27.325359 | 106 | 0.699652 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/pitch_linear.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Defines layout functions used by TensorRef and derived classes for pitch-linear memory.
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/coord.h"
#include "cutlass/pitch_linear_coord.h"
namespace cutlass {
namespace layout {
template <int Contiguous, int Strided>
using PitchLinearShape = cutlass::PitchLinearShape < Contiguous, Strided >;
using PitchLinearCoord = PitchLinearCoord;
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for pitch-linear memory
class PitchLinear {
public:
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
PitchLinear(LongIndex ldm = 0): stride_(ldm) { }
/// Constructor
CUTLASS_HOST_DEVICE
PitchLinear(Stride _stride): stride_(_stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static PitchLinear packed(TensorCoord const &extent) {
return PitchLinear(extent.contiguous());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return LongIndex(coord.contiguous()) + LongIndex(coord.strided()) * LongIndex(stride_[0]);
}
/// Returns the logical coordinate given an offset.
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex index) const {
return make_Coord(
TensorCoord::Index(index % stride_[0]),
TensorCoord::Index(index / stride_[0])
);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
LongIndex stride(int rank) const {
return stride_[rank];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
LongIndex & stride(int rank) {
return stride_[rank];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent.strided() * stride_[0];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace layout
} // namespace cutlass
| 4,696 | C | 30.52349 | 100 | 0.663969 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/tensor_op_multiplicand_sm80.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief layouts needed by Ampere fp64 tensor core kernels.
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/layout/pitch_linear.h"
#include "cutlass/layout/tensor_op_multiplicand_sm75.h"
////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace layout {
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
struct TensorOpMultiplicandCongruous64b {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Static constants
//
static int const kElementSize = 64;
static int const kElementsPerAccess = 1;
private:
//
// Data members
//
/// Stride data member.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous64b(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous64b(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandCongruous64b packed(TensorCoord const &extent) {
return TensorOpMultiplicandCongruous64b(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
int tc = coord.contiguous() / 16;
int ts = coord.strided() / 4;
int c = coord.contiguous() % 16;
int s = coord.strided() % 4;
int bank = ((((c & 1) * 4 + (c & 6) / 2)) ^ (s & 1)) * 2 + (c / 8);
int row = (c & 6) / 2;
bank ^= ((s & 2) * 2);
LongIndex offset = tc * 16 + bank + (ts * 4 + row) * stride_[0];
return offset;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
return TensorCoord();
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to
/// TensorOpMultiplicand
struct ColumnMajorTensorOpMultiplicandCongruous64b {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCongruous64b;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCongruous64b(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCongruous64b(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorTensorOpMultiplicandCongruous64b packed(TensorCoord const &extent) {
return ColumnMajorTensorOpMultiplicandCongruous64b(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a row-major view of pitch-linear memory to
/// TensorOpMultiplicand
struct RowMajorTensorOpMultiplicandCongruous64b {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCongruous64b;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCongruous64b(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCongruous64b(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorTensorOpMultiplicandCongruous64b packed(TensorCoord const &extent) {
return RowMajorTensorOpMultiplicandCongruous64b(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
struct TensorOpMultiplicand64bCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Static constants
//
static int const kElementSize = 64;
static int const kElementsPerAccess = 1;
private:
//
// Data members
//
/// Stride data member.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicand64bCrosswise(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicand64bCrosswise(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicand64bCrosswise packed(TensorCoord const &extent) {
return TensorOpMultiplicand64bCrosswise(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
int tc = coord.contiguous() / 16;
int ts = coord.strided() / 16;
int c = coord.contiguous() % 16;
int s = coord.strided() % 16;
int k_group = c / 4;
int access_s = s / 2;
int row = access_s % 4;
int bank = ((k_group & 2) << 2) ^ ((s % 2) << 3) + (c % 4) * 2 + (access_s / 4) ^ (k_group & 1);
int smem_row = (k_group * 4 + row) + tc * 16;
int smem_col = ts * 16 + bank;
LongIndex offset = smem_row * stride_[0] + smem_col;
return offset;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
struct ColumnMajorTensorOpMultiplicand64bCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicand64bCrosswise;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicand64bCrosswise(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicand64bCrosswise(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorTensorOpMultiplicand64bCrosswise packed(TensorCoord const &extent) {
return ColumnMajorTensorOpMultiplicand64bCrosswise(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
struct RowMajorTensorOpMultiplicand64bCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicand64bCrosswise;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicand64bCrosswise(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicand64bCrosswise(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorTensorOpMultiplicand64bCrosswise packed(TensorCoord const &extent) {
return RowMajorTensorOpMultiplicand64bCrosswise(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
struct TensorOpMultiplicandCongruous128b {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Static constants
//
static int const kElementSize = 128;
static int const kElementsPerAccess = 1;
private:
//
// Data members
//
/// Stride data member.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous128b(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous128b(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandCongruous128b packed(TensorCoord const &extent) {
return TensorOpMultiplicandCongruous128b(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
Index tc = coord.contiguous() / 8;
Index ts = coord.strided() / 4;
Index c = coord.contiguous() % 8;
Index s = coord.strided() % 4;
Index k_index = (c / 2);
Index bank = (((c & 1) * 4) | (s ^ k_index));
LongIndex offset = tc * 8 + bank + (ts * 4 + k_index) * stride_[0];
return offset;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
return TensorCoord();
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to
/// TensorOpMultiplicand
struct ColumnMajorTensorOpMultiplicandCongruous128b {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCongruous128b;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCongruous128b(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCongruous128b(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorTensorOpMultiplicandCongruous128b packed(TensorCoord const &extent) {
return ColumnMajorTensorOpMultiplicandCongruous128b(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a row-major view of pitch-linear memory to
/// TensorOpMultiplicand
struct RowMajorTensorOpMultiplicandCongruous128b {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCongruous128b;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCongruous128b(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCongruous128b(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorTensorOpMultiplicandCongruous128b packed(TensorCoord const &extent) {
return RowMajorTensorOpMultiplicandCongruous128b(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
struct TensorOpMultiplicandCrosswise128x4 {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Static constants
//
static int const kElementSize = 128;
static int const kElementsPerAccess = 1;
private:
//
// Data members
//
/// Stride data member.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCrosswise128x4(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCrosswise128x4(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandCrosswise128x4 packed(TensorCoord const &extent) {
return TensorOpMultiplicandCrosswise128x4(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
Index tc = coord.contiguous() / 8;
Index ts = coord.strided() / 8;
Index c = coord.contiguous() % 8;
Index s = coord.strided() % 8;
Index liq = c % 4;
Index bank = liq + ((s & 1) * 4) ^ (c & 4);
Index k_index = (c & 4) + (s / 4) * 2 + ((s & 2) / 2);
LongIndex offset = (tc * 8 + k_index) * stride_[0] + ts * 8 + bank;
return offset;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to
/// TensorOpMultiplicand
struct ColumnMajorTensorOpMultiplicandCrosswise128x4 {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCrosswise128x4;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCrosswise128x4(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCrosswise128x4(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorTensorOpMultiplicandCrosswise128x4 packed(TensorCoord const &extent) {
return ColumnMajorTensorOpMultiplicandCrosswise128x4(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a row-major view of pitch-linear memory to
/// TensorOpMultiplicand
struct RowMajorTensorOpMultiplicandCrosswise128x4 {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCrosswise128x4;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCrosswise128x4(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCrosswise128x4(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorTensorOpMultiplicandCrosswise128x4 packed(TensorCoord const &extent) {
return RowMajorTensorOpMultiplicandCrosswise128x4(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
////////////////////////////////////////////////////////////////////////////////
} // namespace layout
} // namespace cutlass
////////////////////////////////////////////////////////////////////////////////
| 29,336 | C | 24.734211 | 100 | 0.667201 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/permute.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Defines layout functions used by GEMM+permute path for common tensor or matrix formats.
Like Layout functions, permute layout functions map logical coordinates to linear memory. They often require additional
data to describe strides between elements.
Permute layout functions must implement all members in the interface of NoPermute<> defined in this file. Address offset
computation lies in operator() with private member variables {col_permute_, row_permute_ and stride_permute_} as new addresses after permute op.
*/
#pragma once
#if defined(__CUDACC_RTC__)
#include <cuda/std/cassert>
#else
#include "assert.h"
#endif
#include "cutlass/cutlass.h"
#include "cutlass/fast_math.h"
#include "cutlass/layout/pitch_linear.h"
#include "cutlass/layout/matrix.h"
#include "cutlass/coord.h"
#include "cutlass/tensor_coord.h"
namespace cutlass {
namespace layout {
class NoPermute {
public:
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
private:
//
// Data members
//
MatrixCoord extent_;
Index stride_unit_; // sizeof(AccessType) / kElementsPerAccess in epilogue's predicated_tile_iterator
Index stride_permute_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
NoPermute() { }
/// Constructor
CUTLASS_HOST_DEVICE
NoPermute(MatrixCoord extent, Index stride_init): extent_(extent) { }
/// Computes the address offset after Permute Op in Bytes
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord offset_init) { return 0; }
};
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Defines permute layouts of various tensor formats.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Permute layout function for 4-D permuted tensors with output matrix (dimension as [M, N]) reshaped
/// as [M/D1, D1, D2, N/D2]. Then perform permute([0, 2, 1, 3]) on the corresponding output tensor.
template <int D1, int D2>
class Tensor4DPermute0213 {
public:
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
private:
//
// Data members
//
MatrixCoord extent_;
Index stride_permute_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
Tensor4DPermute0213() { }
/// Constructor
CUTLASS_HOST_DEVICE
Tensor4DPermute0213(MatrixCoord extent, Index stride_init): extent_(extent) {
/// Update stride_permute with stride_init
stride_permute_ = stride_init / D2 * D1; // stride in Elements
}
/// Computes the address offset after Permute Op in Bytes
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord offset_init) {
// Permute as torch.permute(X1, [0, 2, 1, 3]) -> 4D Tensor indices as [i,j,k,l], the dimension of X
// is [D0, D1, D2, D3], after permutation the dim of X1 is [D0, D2, D1, D3].
assert(extent_.row() % D1 == 0);
assert(extent_.column() % D2 == 0);
int D3 = extent_.column() / D2;
Index col_init = offset_init.column();
Index row_init = offset_init.row();
int l = col_init % D3;
int k = col_init / D3;
int j = row_init % D1;
int i = row_init / D1;
// After the Permute Op
Index col_permute = l + j * D3;
Index row_permute = k + i * D2;
return LongIndex(row_permute) * LongIndex(stride_permute_) + LongIndex(col_permute);
}
/// Return D1
CUTLASS_HOST_DEVICE
Index d1() const {
return D1;
}
/// Return D2
CUTLASS_HOST_DEVICE
Index d2() const {
return D2;
}
};
/// Permute layout function for 4-D permuted tensors for BMM with BMM output tensor (dimension as [B, M, N]) reshaped
/// as [B/D1, D1, M, N]. Then perform permute([0, 2, 1, 3]) on the corresponding whole BMM output tensor.
template <int D1>
class Tensor4DPermuteBMM0213 {
public:
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
private:
//
// Data members
//
MatrixCoord extent_;
Index stride_permute_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
Tensor4DPermuteBMM0213() { }
/// Constructor
CUTLASS_HOST_DEVICE
Tensor4DPermuteBMM0213(MatrixCoord extent, Index stride_init): extent_(extent) {
/// Update stride_permute with stride_init
stride_permute_ = stride_init * D1; // stride in Elements
}
/// Computes the address offset after Permute Op in Bytes
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord offset_init) {
// The batch index for BMM
Index BMM_batch_idx = blockIdx.z;
// Permute as torch.permute(X1, [0, 2, 1, 3]) -> 4D Tensor indices as [i,j,k,l], the dimension of X
// is [D0, D1, D2, D3], after permutation the dim of X1 is [D0, D2, D1, D3].
int D2 = extent_.row();
int D3 = extent_.column();
Index col_init = offset_init.column();
Index row_init = offset_init.row();
int l = col_init;
int k = row_init;
int j = BMM_batch_idx % D1;
int i = BMM_batch_idx / D1;
// After the Permute Op
Index col_permute = l + j * D3;
Index row_permute = k + i * D2;
return LongIndex(row_permute) * LongIndex(stride_permute_) + LongIndex(col_permute);
}
/// Return D1
CUTLASS_HOST_DEVICE
Index d1() const {
return D1;
}
};
/// Permute layout function for 5-D permuted tensors with output matrix (dimension as [M, N]) reshaped
/// as [M/T1, T1, T2, T3, N/T2/T3]. Then perform permute([2, 0, 3, 1, 4]) on the corresponding output tensor.
template <int T1, int T2, int T3>
class Tensor5DPermute20314 {
public:
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
private:
//
// Data members
//
MatrixCoord extent_;
Index stride_permute_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
Tensor5DPermute20314() { }
/// Constructor
CUTLASS_HOST_DEVICE
Tensor5DPermute20314(MatrixCoord extent, Index stride_init): extent_(extent) {
/// Update stride_permute with stride_init
stride_permute_ = stride_init / T2 * T1; // stride in Elements
}
/// Computes the address offset after Permute Op in Bytes
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord offset_init) {
// Permute as torch.permute(X1, [2, 0, 3, 1, 4]) -> 5D Tensor indices as [i,j,k,l,m], the dimension of X
// is [T0, T1, T2, T3, T4], after permutation the dim of X1 is [T2, T0, T3, T1, T4].
int T0 = extent_.row() / T1;
int T4 = extent_.column() / T2 / T3;
Index col_init = offset_init.column();
Index row_init = offset_init.row();
int m = col_init % T4;
int l = int(col_init / T4) % T3;
int k = int(col_init / T4) / T3;
int j = row_init % T1;
int i = row_init / T1;
// After the Permute Op
Index col_permute = m + j * T4 + l * T1 * T4;
Index row_permute = i + k * T0;
return LongIndex(row_permute) * LongIndex(stride_permute_) + LongIndex(col_permute);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace layout
} // namespace cutlass
| 9,133 | C | 27.996825 | 149 | 0.642286 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/vector.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Defines layout functions used for rank=1 vectors.
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/coord.h"
namespace cutlass {
namespace layout {
/// Tensor layout for densely packed vectors.
class PackedVectorLayout {
public:
/// Logical rank of tensor
static int const kRank = 1;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = Coord<kRank, Index>;
/// Stride vector
using Stride = Coord<kStrideRank, Index>;
private:
//
// No actual stride vector stored
//
public:
//
// Methods
//
CUTLASS_HOST_DEVICE
PackedVectorLayout() { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static PackedVectorLayout packed(TensorCoord const &size) {
return PackedVectorLayout();
}
/// Returns the offset of a coordinate in linear memory
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return coord[0];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return make_Coord(1);
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &size) const {
return size[0];
}
};
} // namespace layout
} // namespace cutlass
| 3,328 | C | 30.704762 | 100 | 0.692308 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/tensor_op_multiplicand_sm75.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/coord.h"
#include "cutlass/matrix_coord.h"
#include "cutlass/layout/pitch_linear.h"
////////////////////////////////////////////////////////////////////////////////
namespace cutlass {
namespace layout {
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
/// This one is the base class of all Ampere/Turing fp16/bf16/int8/int4/int1
/// tensor core kernels. tf32 TN uses this too.
template <int ElementSize, int Crosswise>
struct TensorOpMultiplicand {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Static constants
//
/// This layout is optimized for 128b accesses
static int const kAccessSize = 128;
static int const kElementSize = ElementSize;
static int const kElementsPerAccess = kAccessSize / kElementSize;
static int const kCrosswise = Crosswise;
/// Contiguous dimension of the tile shape matches one shared memory cache
/// line - 128B. For 128bit access size, it equals to 8 accesses.
static int const kTileShapeContiguous = 128 / (kAccessSize / 8);
/// Number of kblocks to store PartitionShape::kContiguous Elements
static int const kFactor =
kTileShapeContiguous * kElementsPerAccess / kCrosswise;
static_assert(
(kFactor > 0),
"kCrosswise should be no large than one shared memory cache line.");
/// The strided dimension needs to be at least (WarpSize(32) /
/// kTileShapeContiguous) for a warp to access. To ensure conflict free
/// access, it also needs to be at least (kTileShapeContiguous / kFactor).
/// See comments below
static int const kTileShapeStride =
((kTileShapeContiguous / kFactor) > (32 / kTileShapeContiguous))
? (kTileShapeContiguous / kFactor)
: (32 / kTileShapeContiguous);
/// Fundamental tile shape in units of vectors to guarantee bank conflict free
/// shared memory load/store.
/// For kFactor = 1, TileShape = <8, 8>
/// For kFactor > 1, TileShape = <8, 4>
using TileShape = PitchLinearShape<kTileShapeContiguous, kTileShapeStride>;
/// Fundamental partition shape in units of vectors
using PartitionShape = PitchLinearShape<4, 4>;
using PartitionCount =
PitchLinearShape<TileShape::kContiguous / PartitionShape::kContiguous,
TileShape::kStrided / PartitionShape::kStrided>;
using AccessCount =
PitchLinearShape<PartitionShape::kContiguous, PartitionShape::kStrided>;
private:
//
// Data members
//
/// Stride data member. For GEMM, it equals to kCrosswise x stage.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicand(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicand(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicand packed(TensorCoord const &extent) {
return TensorOpMultiplicand(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
//
// First, compute c and s of vector within source (in units of vector
// accesses)
//
int vec_contiguous_idx = coord.contiguous() / kElementsPerAccess;
int vec_strided_idx = coord.strided() / kFactor;
// Compute the fundamental tile being accessed
int tile_contiguous_idx =
vec_contiguous_idx / (TileShape::kContiguous / kFactor);
int tile_contiguous_residual =
vec_contiguous_idx % (TileShape::kContiguous / kFactor) +
((coord.strided() % kFactor) * (TileShape::kContiguous / kFactor));
int tile_strided_residual = vec_strided_idx % TileShape::kStrided;
// Compute the 'partition' within the fundamental tile
int partition_contiguous_idx =
tile_contiguous_residual / PartitionShape::kContiguous;
int partition_strided_idx =
tile_strided_residual / PartitionShape::kStrided;
int partition_contiguous_residual =
tile_contiguous_residual % PartitionShape::kContiguous;
int partition_strided_residual =
tile_strided_residual % PartitionShape::kStrided;
//
// Then swizzle
//
int permuted_vec_contiguous_within_partition =
partition_contiguous_residual ^ (partition_strided_residual % 4);
int permuted_partition_contiguous_within_tile =
partition_contiguous_idx ^ (partition_strided_idx % 2);
//
// Compute final element location
//
int element_contiguous = (tile_contiguous_idx * TileShape::kContiguous +
permuted_partition_contiguous_within_tile *
PartitionShape::kContiguous +
permuted_vec_contiguous_within_partition) *
kElementsPerAccess +
(coord.contiguous() % kElementsPerAccess);
int element_strided = vec_strided_idx;
return element_contiguous + element_strided * stride_[0] * kFactor;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
template <int ElementSize, int Crosswise>
struct TensorOpMultiplicandCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicand<ElementSize, Crosswise>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous(Index ldm = 0) : layout_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous(Stride stride) : layout_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return TensorOpMultiplicandCongruous(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(coord);
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return coord;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return layout_.stride(); }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return layout_.stride(); }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(extent);
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
/// This one is just for TF32 NT kernel.
template <int Crosswise>
struct TensorOpMultiplicandCongruous<32, Crosswise> {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
/// This layout is optimized for 128b accesses
static int const kAccessSize = 128;
/// Fundamental tile shape in units of vectors
using TileShape = PitchLinearShape<8, 4>;
/// Partitionshape is the same as TileShape for this layout
using PartitionShape = PitchLinearShape<8, 4>;
using PartitionCount =
PitchLinearShape<TileShape::kContiguous / PartitionShape::kContiguous,
TileShape::kStrided / PartitionShape::kStrided>;
using AccessCount =
PitchLinearShape<PartitionShape::kContiguous, PartitionShape::kStrided>;
//
// Static constants
//
static int const kElementSize = 32;
static int const kElementsPerAccess = kAccessSize / kElementSize;
private:
//
// Data members
//
/// Stride data member.
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous(Index ldm = 0) : stride_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCongruous(Stride stride) : stride_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return TensorOpMultiplicandCongruous(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
int tc = coord.contiguous() / 32;
int ts = coord.strided() / 4;
int c = (coord.contiguous() % 32) / kElementsPerAccess;
int s = coord.strided() % 4;
LongIndex offset = (c ^ (2 * s)) * kElementsPerAccess + s * stride_[0] +
tc * 32 + ts * stride_[0] * 4 + coord.contiguous() % 4;
return offset;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return stride_; }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return stride_; }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent[1] * stride_[0];
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to
/// TensorOpMultiplicand
template <int ElementSize, int Crosswise>
struct ColumnMajorTensorOpMultiplicandCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCongruous<ElementSize, Crosswise>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCongruous(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCongruous(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorTensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return ColumnMajorTensorOpMultiplicandCongruous(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a row-major view of pitch-linear memory to
/// TensorOpMultiplicand
template <int ElementSize, int Crosswise>
struct RowMajorTensorOpMultiplicandCongruous {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCongruous<ElementSize, Crosswise>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCongruous(Index ldm = 0): layout_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCongruous(Stride stride): layout_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorTensorOpMultiplicandCongruous packed(TensorCoord const &extent) {
return RowMajorTensorOpMultiplicandCongruous(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return layout_.stride();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return layout_.stride();
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear
/// memory and Crosswise size (in elements).
template <int ElementSize, int Crosswise>
struct TensorOpMultiplicandCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicand<ElementSize, Crosswise>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
static int const kCrosswise = Base::kCrosswise;
static int const kFactor = Base::kFactor;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCrosswise(Index ldm = 0) : layout_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandCrosswise(Stride stride) : layout_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandCrosswise packed(TensorCoord const &extent) {
return TensorOpMultiplicandCrosswise(extent[0]);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(coord);
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return coord;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return layout_.stride(); }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return layout_.stride(); }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(extent);
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a column-major view of pitch-linear memory to
/// TensorOpMultiplicandCrosswise
template <int ElementSize, int Crosswise>
struct ColumnMajorTensorOpMultiplicandCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCrosswise<ElementSize, Crosswise>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCrosswise(Index ldm = 0) : layout_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorTensorOpMultiplicandCrosswise(Stride stride) : layout_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorTensorOpMultiplicandCrosswise packed(
TensorCoord const &extent) {
return ColumnMajorTensorOpMultiplicandCrosswise(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.row(), coord.column()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.contiguous(), coord.strided());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return layout_.stride(); }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return layout_.stride(); }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.row(), extent.column()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template mapping a row-major view of pitch-linear memory to
/// TensorOpMultiplicandCrosswise
template <int ElementSize, int Crosswise>
struct RowMajorTensorOpMultiplicandCrosswise {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
using Base = TensorOpMultiplicandCrosswise<ElementSize, Crosswise>;
/// This layout is optimized for 128b accesses
static int const kAccessSize = Base::kAccessSize;
using TileShape = typename Base::TileShape;
using PartitionShape = typename Base::PartitionShape;
//
// Static constants
//
static int const kElementSize = Base::kElementSize;
static int const kElementsPerAccess = Base::kElementsPerAccess;
using PartitionCount = typename Base::PartitionCount;
using AccessCount = typename Base::AccessCount;
private:
//
// Data members
//
Base layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCrosswise(Index ldm = 0) : layout_(ldm) {}
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorTensorOpMultiplicandCrosswise(Stride stride) : layout_(stride) {}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorTensorOpMultiplicandCrosswise packed(
TensorCoord const &extent) {
return RowMajorTensorOpMultiplicandCrosswise(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return layout_(PitchLinearCoord(coord.column(), coord.row()));
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
PitchLinearCoord coord = layout_.inverse(offset);
return MatrixCoord(coord.strided(), coord.contiguous());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const { return layout_.stride(); }
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride &stride() { return layout_.stride(); }
/// Compute the number of contiguous elements needed to store a tensor with
/// the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return layout_.capacity(PitchLinearCoord(extent.column(), extent.row()));
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear memory.
template <int ElementSize, int InterleavedK>
struct TensorOpMultiplicandColumnMajorInterleaved {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
/// This layout is optimized for 128b accesses
static int const kAccessSize = 128;
//
// Static constants
//
static int const kElementSize = ElementSize;
static int const kElementsPerAccess = kAccessSize / kElementSize;
//static int const kThreadBlockStrided = ThreadBlockStrided;
static int const kInterleavedK = InterleavedK;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandColumnMajorInterleaved(Index ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandColumnMajorInterleaved(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandColumnMajorInterleaved packed(TensorCoord const &extent) {
return TensorOpMultiplicandColumnMajorInterleaved(extent[0] * kInterleavedK);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
int const rows_per_smem_cache_line = 128 / kInterleavedK;
int row_id = coord.strided() / rows_per_smem_cache_line;
int col_id = (coord.strided() % rows_per_smem_cache_line) * kInterleavedK + coord.contiguous();
int access_block_id = col_id >> 4;
int swizzle_access_block_id = access_block_id ^ (row_id & 1);
int swizzle_col_id = swizzle_access_block_id << 4;
return row_id * 128 + swizzle_col_id;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return (extent[1] / kInterleavedK) * stride_[0];
}
};
////////////////////////////////////////////////////////////////////////////////
/// Template based on element size (in bits) - defined in terms of pitch-linear memory.
template <int ElementSize, int InterleavedK>
struct TensorOpMultiplicandRowMajorInterleaved {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = PitchLinearCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index, LongIndex>;
//
// Invariants
//
/// This layout is optimized for 128b accesses
static int const kAccessSize = 128;
//
// Static constants
//
static int const kElementSize = ElementSize;
static int const kElementsPerAccess = kAccessSize / kElementSize;
//static int const kThreadBlockStrided = ThreadBlockStrided;
static int const kInterleavedK = InterleavedK;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandRowMajorInterleaved(Index ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
TensorOpMultiplicandRowMajorInterleaved(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorOpMultiplicandRowMajorInterleaved packed(TensorCoord const &extent) {
return TensorOpMultiplicandRowMajorInterleaved(extent[1] * kInterleavedK);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (contiguous, strided)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
int const rows_per_smem_cache_line = 128 / kInterleavedK;
int row_id = coord.strided() / rows_per_smem_cache_line;
int col_id = (coord.strided() % rows_per_smem_cache_line) * kInterleavedK + coord.contiguous();
int access_block_id = col_id >> 4;
int swizzle_access_block_id = access_block_id ^ (row_id & 1);
int swizzle_col_id = swizzle_access_block_id << 4;
return row_id * 128 + swizzle_col_id;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return (extent[0] / kInterleavedK) * stride_[0];
}
};
////////////////////////////////////////////////////////////////////////////////
} // namespace layout
} // namespace cutlass
////////////////////////////////////////////////////////////////////////////////
| 33,137 | C | 27.518072 | 100 | 0.683194 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/tensor.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Defines layout functions used by TensorRef and derived classes for common 4-D and 5-D
tensor formats.
Layout functions map logical coordinates to linear memory. They often require additional
data to describe strides between elements.
Layout functions must implement all members in the public interface of IdentityTensorLayout<>
defined in cutlass/tensor_ref.h.
*/
#pragma once
#if defined(__CUDACC_RTC__)
#include <cuda/std/cassert>
#else
#include "assert.h"
#endif
#include "cutlass/cutlass.h"
#include "cutlass/fast_math.h"
#include "cutlass/layout/pitch_linear.h"
#include "cutlass/layout/matrix.h"
#include "cutlass/coord.h"
#include "cutlass/tensor_coord.h"
namespace cutlass {
namespace layout {
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Defines data layouts of various tensor formats usable by TensorRef and other classes.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for 4-D NHWC tensors.
class TensorNHWC {
public:
/// Logical rank of tensor
static int const kRank = 4;
/// Rank of stride vector
static int const kStrideRank = 3;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate (n, h, w, c)
using TensorCoord = Tensor4DCoord;
/// Stride vector
using Stride = Coord<kStrideRank>;
private:
//
// Data members
//
/// Stride data member - [stride_w, stride_h, stride_n]
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
TensorNHWC(Stride const &stride = Stride(0)): stride_(stride) { }
/// Constructor
CUTLASS_HOST_DEVICE
TensorNHWC(
typename Stride::Index stride_w, ///< number of elements between adjacent W coordinates
typename Stride::Index stride_h, ///< number of elements between adjacent H coordinates
typename Stride::Index stride_n ///< number of elements between adjacent N coordinates
):
stride_(make_Coord(stride_w, stride_h, stride_n)) { }
/// Constructor
// Once convolutions implement 64b stride this ctor can be deleted
CUTLASS_HOST_DEVICE
TensorNHWC(Coord<kStrideRank, LongIndex> const &stride):
stride_(make_Coord(
static_cast<typename Stride::Index>(stride[0]),
static_cast<typename Stride::Index>(stride[1]),
static_cast<typename Stride::Index>(stride[2]))
) { }
/// Helper returns a layout to a tightly packed NHWC tensor.
CUTLASS_HOST_DEVICE
static TensorNHWC packed(TensorCoord const &extent) {
return TensorNHWC(
make_Coord(
extent.c(),
extent.w() * extent.c(),
extent.h() * extent.w() * extent.c()
)
);
}
/// Returns the offset of a coordinate (n, h, w, c) in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return coord.c() +
LongIndex(stride_[0] * coord.w()) +
LongIndex(stride_[1] * coord.h()) +
LongIndex(stride_[2] * coord.n());
}
/// Returns the offset of a pitchlinear coordinate in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(PitchLinearCoord coord) const {
return coord.contiguous() + LongIndex(coord.strided() * stride_[2]);
}
/// Returns the logical coordinate (n, h, w, c) from a given offset in linear memory.
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex index) const {
int n = 0, h = 0, w = 0, c = 0;
#if defined(__CUDA_ARCH__)
int tmp = 0;
c = int(index % static_cast<int>(stride_[0]));
unsigned int hw_mul, hw_shr, w_mul, w_shr, c_mul, c_shr;
find_divisor(hw_mul, hw_shr, stride_[2]);
find_divisor(w_mul, w_shr, stride_[1]);
find_divisor(c_mul, c_shr, stride_[0]);
fast_divmod(n, tmp, index, int(stride_[2]), hw_mul, hw_shr);
fast_divmod(h, w, tmp, int(stride_[1]), w_mul, w_shr);
fast_divmod(w, tmp, w, int(stride_[0]), c_mul, c_shr);
#else
n = int(index / stride_[2]);
LongIndex residual = index % stride_[2];
h = int(residual / stride_[1]);
residual = (residual % stride_[1]);
w = int(residual / stride_[0]);
c = int(residual % stride_[0]);
#endif
return TensorCoord(n, h, w, c);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
// it does not make sense if the extent is larger than stride
// and we could not rely on the capacity calculation in such cases
// we could move this checkers to debug code only
if ((extent.c() > stride_[0])
|| (extent.w() * stride_[0] > stride_[1])
|| (extent.h() * stride_[1] > stride_[2])) {
assert(0);
}
return extent.n() * stride_[2];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for 4-D NCHW tensors.
class TensorNCHW {
public:
/// Logical rank of tensor
static int const kRank = 4;
/// Rank of stride vector
static int const kStrideRank = 3;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = Tensor4DCoord;
/// Stride vector
using Stride = Coord<kStrideRank>;
private:
//
// Data members
//
/// Stride data member - [w, hw, chw]
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
TensorNCHW(Stride const &stride = Stride(0)): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorNCHW packed(TensorCoord const &extent) {
return TensorNCHW(
make_Coord(
extent.w(),
extent.w() * extent.h(),
extent.h() * extent.w() * extent.c()
)
);
}
/// Returns the offset of a coordinate in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return coord.w() +
LongIndex(stride_[0] * coord.h()) +
LongIndex(stride_[1] * coord.c()) +
LongIndex(stride_[2] * coord.n());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent.n() * stride_[2];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for 4-D NC/xHWx tensors.
template <int Interleave>
class TensorNCxHWx {
public:
/// Interleaving quantity
static int const kInterleave = Interleave;
/// Logical rank of tensor
static int const kRank = 4;
/// Rank of stride vector
static int const kStrideRank = 3;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = Tensor4DCoord;
/// Stride vector
using Stride = Coord<kStrideRank>;
private:
//
// Data members
//
/// Stride data member - [Interleave x w, Interleave x wh, hwc]
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
TensorNCxHWx(Stride const &stride = Stride(0)): stride_(stride) { }
/// Constructor
CUTLASS_HOST_DEVICE
TensorNCxHWx(
typename Stride::Index stride_w, ///< number of elements between adjacent W coordinates
typename Stride::Index stride_h, ///< number of elements between adjacent H coordinates
typename Stride::Index stride_n ///< number of elements between adjacent N coordinates
):
stride_(make_Coord(stride_w, stride_h, stride_n)) { }
/// Constructor
// Once convolutions implement 64b stride this ctor can be deleted
CUTLASS_HOST_DEVICE
TensorNCxHWx(Coord<kStrideRank, LongIndex> const &stride):
stride_(make_Coord(
static_cast<typename Stride::Index>(stride[0]),
static_cast<typename Stride::Index>(stride[1]),
static_cast<typename Stride::Index>(stride[2]))
) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorNCxHWx packed(TensorCoord const &extent) {
return TensorNCxHWx(
make_Coord(
kInterleave * extent.w(),
kInterleave * extent.w() * extent.h(),
extent.h() * extent.w() * extent.c()
)
);
}
/// Returns the offset of a coordinate in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
Index c_minor = (coord.c() % kInterleave);
Index c_major = (coord.c() / kInterleave);
return c_minor +
LongIndex(kInterleave * coord.w()) +
LongIndex(stride_[0] * coord.h()) +
LongIndex(stride_[1] * c_major) +
LongIndex(stride_[2] * coord.n());
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return extent.n() * stride_[2];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for 4-D CxRSKx tensors.
template <int Interleave>
class TensorCxRSKx {
public:
/// Interleaving quantity
static int const kInterleave = Interleave;
/// Logical rank of tensor
static int const kRank = 4;
/// Rank of stride vector
static int const kStrideRank = 3;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = Tensor4DCoord;
/// Stride vector
using Stride = Coord<kStrideRank>;
private:
//
// Data members
//
/// Stride data member - [Interleave x n, Interleave x nw, Interleave x nwh]
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
TensorCxRSKx(Stride const &stride = Stride(0)): stride_(stride) { }
/// Constructor
CUTLASS_HOST_DEVICE
TensorCxRSKx(
typename Stride::Index stride_w, ///< number of elements between adjacent W coordinates
typename Stride::Index stride_h, ///< number of elements between adjacent H coordinates
typename Stride::Index stride_n ///< number of elements between adjacent N coordinates
):
stride_(make_Coord(stride_w, stride_h, stride_n)) { }
/// Constructor
// Once convolutions implement 64b stride this ctor can be deleted
CUTLASS_HOST_DEVICE
TensorCxRSKx(Coord<kStrideRank, LongIndex> const &stride):
stride_(make_Coord(
static_cast<typename Stride::Index>(stride[0]),
static_cast<typename Stride::Index>(stride[1]),
static_cast<typename Stride::Index>(stride[2]))
) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static TensorCxRSKx packed(TensorCoord const &extent) {
return TensorCxRSKx(
make_Coord(
kInterleave * extent.n(),
kInterleave * extent.n() * extent.w(),
kInterleave * extent.n() * extent.w() * extent.h()
)
);
}
/// Returns the offset of a coordinate in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
Index c_minor = (coord.c() % kInterleave);
Index c_major = (coord.c() / kInterleave);
return c_minor +
LongIndex(kInterleave * coord.n()) +
LongIndex(stride_[0] * coord.w()) +
LongIndex(stride_[1] * coord.h()) +
LongIndex(stride_[2] * c_major);
}
/// Returns the offset of a pitchlinear coordinate in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(PitchLinearCoord const &coord) const {
return (coord.contiguous() % kInterleave) +
LongIndex((coord.contiguous() / kInterleave) * stride_[2]) +
LongIndex(coord.strided() * kInterleave);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
return (extent.c() / kInterleave * stride_[2]);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for 5-D NDHWC tensors.
class TensorNDHWC {
public:
/// Logical rank of tensor
static int const kRank = 5;
/// Rank of stride vector
static int const kStrideRank = 4;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate (n, d, h, w, c)
using TensorCoord = Tensor5DCoord;
/// Stride vector
using Stride = Coord<kStrideRank>;
private:
//
// Data members
//
/// Stride data member - [c, wc, hwc, dhwc]
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
TensorNDHWC(Stride const &stride = Stride(0)): stride_(stride) { }
/// Constructor
CUTLASS_HOST_DEVICE
TensorNDHWC(
typename Stride::Index c,
typename Stride::Index wc,
typename Stride::Index hwc,
typename Stride::Index dhwc):
stride_(make_Coord(c, wc, hwc, dhwc)) { }
/// Constructor
// Once convolutions implement 64b stride this ctor can be deleted
CUTLASS_HOST_DEVICE
TensorNDHWC(Coord<kStrideRank, LongIndex> const &stride):
stride_(make_Coord(
static_cast<typename Stride::Index>(stride[0]),
static_cast<typename Stride::Index>(stride[1]),
static_cast<typename Stride::Index>(stride[2]),
static_cast<typename Stride::Index>(stride[3]))
) { }
/// Helper returns a layout to a tightly packed NHWC tensor.
CUTLASS_HOST_DEVICE
static TensorNDHWC packed(TensorCoord const &extent) {
return TensorNDHWC(
make_Coord(
extent.c(),
extent.w() * extent.c(),
extent.h() * extent.w() * extent.c(),
extent.d() * extent.h() * extent.w() * extent.c()
)
);
}
/// Returns the offset of a coordinate (n, d, h, w, c) in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return coord.c() +
LongIndex(stride_[0] * coord.w()) +
LongIndex(stride_[1] * coord.h()) +
LongIndex(stride_[2] * coord.d()) +
LongIndex(stride_[3] * coord.n());
}
/// Returns the offset of a pitchlinear coordinate in linear memory.
CUTLASS_HOST_DEVICE
LongIndex operator()(PitchLinearCoord coord) const {
return coord.contiguous() + LongIndex(coord.strided() * stride_[3]);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
// it does not make sense if the extent is larger than stride
// and we could not rely on the capacity calculation in such cases
// we could move this checkers to debug code only
if ((extent.c() > stride_[0])
|| (extent.w() * stride_[0] > stride_[1])
|| (extent.h() * stride_[1] > stride_[2])
|| (extent.d() * stride_[2] > stride_[3])) {
assert(0);
}
return extent.n() * stride_[3];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace layout
} // namespace cutlass
| 18,295 | C | 27.722135 | 100 | 0.630227 |
NVIDIA/warp/warp/native/cutlass/include/cutlass/layout/matrix.h | /***************************************************************************************************
* Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************************************/
/*! \file
\brief Defines layout functions used by TensorRef and derived classes.
Layout functions map logical coordinates to linear memory. They often require additional
data to describe strides between elements.
Layout functions must implement all members in the public interface of IdentityTensorLayout<>
defined in cutlass/tensor_ref.h.
*/
#pragma once
#include "cutlass/cutlass.h"
#include "cutlass/fast_math.h"
#include "cutlass/matrix_coord.h"
#include "cutlass/pitch_linear_coord.h"
namespace cutlass {
namespace layout {
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Defines data layouts of various matrix formats usable by TensorRef and other classes.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for row-major matrices.
class RowMajor {
public:
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Constructor
CUTLASS_HOST_DEVICE
RowMajor(LongIndex ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajor(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajor packed(MatrixCoord const &extent) {
return RowMajor(extent.column());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
return LongIndex(coord.row()) * LongIndex(stride_[0]) + coord.column();
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
return MatrixCoord(Index(offset / stride_[0]), Index(offset % stride_[0]));
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return LongIndex(extent.row()) * LongIndex(stride_[0]);
}
};
/// Mapping function for column-major matrices.
class ColumnMajor {
public:
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajor(LongIndex ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajor(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajor packed(MatrixCoord const &extent) {
return ColumnMajor(extent.row());
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
return LongIndex(coord.column()) * LongIndex(stride_[0]) + coord.row();
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
return MatrixCoord(Index(offset % stride_[0]), Index(offset / stride_[0]));
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return LongIndex(extent.column()) * LongIndex(stride_[0]);
}
};
/// Mapping function for interleaved matrices. Matrix is structured
/// as row-major arrangement of fixed-size columns.
template <int Interleave>
struct RowMajorInterleaved {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
/// Size of interleaved columns
static int const kInterleave = Interleave;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorInterleaved(LongIndex ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorInterleaved(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorInterleaved packed(MatrixCoord const &extent) {
return RowMajorInterleaved(extent.column() * kInterleave);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
Index row_major = coord.row() / kInterleave;
Index row_minor = coord.row() % kInterleave;
return LongIndex(row_major) * LongIndex(stride_[0]) + LongIndex(coord.column()) * kInterleave + row_minor;
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
Index row_major = Index(offset / stride_[0]);
Index residual = Index(offset % stride_[0]);
Index column = residual / kInterleave;
Index row_minor = residual % kInterleave;
return MatrixCoord(row_major * kInterleave + row_minor, column);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return (extent.row() + kInterleave - 1) / kInterleave * stride_[0];
}
};
/// Mapping function for interleaved matrices. Matrix is structured
/// as column-major arrangement of fixed-size rows.
template <int Interleave>
struct ColumnMajorInterleaved {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
/// Size of interleaved columns
static int const kInterleave = Interleave;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorInterleaved(LongIndex ldm = 0): stride_(ldm) { }
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorInterleaved(Stride stride): stride_(stride) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorInterleaved packed(MatrixCoord const &extent) {
return ColumnMajorInterleaved(extent.row() * kInterleave);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
Index column_major = coord.column() / kInterleave;
Index column_minor = coord.column() % kInterleave;
return LongIndex(column_major) * LongIndex(stride_[0]) + LongIndex(coord.row()) * kInterleave + column_minor;
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
Index column_major = Index(offset / stride_[0]);
Index residual = Index(offset % stride_[0]);
Index row = residual / kInterleave;
Index column_minor = residual % kInterleave;
return MatrixCoord(row, column_major * kInterleave + column_minor);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return (extent.column() + kInterleave - 1) / kInterleave * stride_[0];
}
};
/// Enumerated type for canonical pitch-linear matrix layouts
enum class Matrix {
kColumnMajor, ///< leading dimension refers to stride between columns; stride along rows is 1
kRowMajor ///< leading dimension refers to stride between rows; stride along columns is 1
};
/// Mapping function for scenario in which layout is row-major or column-major but this information
/// is only available at runtime.
struct ContiguousMatrix {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
/// Enumerated type indicating canonical matrix layout
Matrix layout_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ContiguousMatrix(
Index ldm = 0,
Matrix layout = Matrix::kColumnMajor
):
stride_(ldm), layout_(layout) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ContiguousMatrix packed(
MatrixCoord const &extent,
Matrix layout = Matrix::kColumnMajor) {
Index ldm = 0;
if (layout == Matrix::kColumnMajor) {
ldm = extent.row();
}
else if (layout == Matrix::kRowMajor) {
ldm = extent.column();
}
return ContiguousMatrix(ldm, layout);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
if (layout_ == Matrix::kColumnMajor) {
return coord.row() + coord.column() * stride_[0];
}
else if (layout_ == Matrix::kRowMajor) {
return coord.row() * stride_[0] + coord.column();
}
else {
// degenerate case
return 0;
}
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
// TODO
return MatrixCoord(0, 0);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
if (layout_ == Matrix::kColumnMajor) {
return stride_[0] * extent.column();
}
else if (layout_ == Matrix::kRowMajor) {
return stride_[0] * extent.row();
}
else {
// degenerate case
return 0;
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for scenario in which both rows and columns are separated by a stride.
template <int Rank>
struct AffineRankN {
/// Logical rank of tensor
static int const kRank = Rank;
/// Rank of stride vector
static int const kStrideRank = kRank;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = Coord<kRank, Index>;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
AffineRankN(
Stride const &stride = Stride()
):
stride_(stride) { }
/// Ctor
CUTLASS_HOST_DEVICE
AffineRankN(
Coord<kRank/2, LongIndex> const &stride_m,
Coord<kRank/2, LongIndex> const &stride_n
) {
// Concatenate the strides
CUTLASS_PRAGMA_UNROLL
for (int m = 0; m < kRank/2; ++m) {
stride_[m] = stride_m[m];
}
CUTLASS_PRAGMA_UNROLL
for (int n = 0; n < kRank/2; ++n) {
stride_[n + kRank/2] = stride_n[n];
}
}
/// Ctor for N = 2
CUTLASS_HOST_DEVICE
AffineRankN(
LongIndex const &stride_m,
LongIndex const &stride_n
) {
stride_[0] = stride_m;
stride_[1] = stride_n;
}
/// Ctor for N = 2
CUTLASS_HOST_DEVICE
AffineRankN(
LongIndex const &stride
) {
stride_[0] = stride;
stride_[1] = 1;
}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static AffineRankN packed(TensorCoord const &extent) {
AffineRankN layout;
layout.stride_[kRank - 1] = 1;
CUTLASS_PRAGMA_UNROLL
for (int i = kRank - 1; i > 0; --i) {
layout.stride_[i - 1] = layout.stride_[i] * extent[i];
}
return layout;
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(TensorCoord const &coord) const {
return dot(coord, stride_);
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
TensorCoord inverse(LongIndex offset) const {
// TODO
return TensorCoord();
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(TensorCoord const &extent) const {
int idx = stride_.max_dim_index();
return extent[idx] * stride_[idx];
}
};
/// Mapping function for scenario in which both rows and columns are separated by a stride.
/// Row stride is smaller than column stride in AffineRank2ColumnMajor.
struct AffineRank2ColumnMajor {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 2;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
AffineRank2ColumnMajor(
Stride const &stride = Stride()
):
stride_(stride) { }
/// Ctor
CUTLASS_HOST_DEVICE
AffineRank2ColumnMajor(
LongIndex row_stride, ///< stride between elements in consecutive rows
LongIndex column_stride ///< stride between elements in consecutive columns
)
{ stride_[0] = row_stride; stride_[1] = column_stride;}
/// Ctor
CUTLASS_HOST_DEVICE
AffineRank2ColumnMajor(
LongIndex stride
)
{ stride_[0] = 1; stride_[1] = stride;}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static AffineRank2ColumnMajor packed(MatrixCoord const &extent) {
return AffineRank2ColumnMajor(extent.column(), 1);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
return dot(coord, stride_);
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
// TODO
return MatrixCoord(0, 0);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return extent.column() * stride_[1];
}
};
/// Mapping function for scenario in which both rows and columns are separated by a stride.
/// Column stride is smaller than row stride in AffineRank2RowMajor.
struct AffineRank2RowMajor {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 2;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
AffineRank2RowMajor(
Stride const &stride = Stride()
):
stride_(stride) { }
/// Ctor
CUTLASS_HOST_DEVICE
AffineRank2RowMajor(
LongIndex row_stride, ///< stride between elements in consecutive rows
LongIndex column_stride ///< stride between elements in consecutive columns
) { stride_[0] = row_stride; stride_[1] = column_stride;}
/// Ctor
CUTLASS_HOST_DEVICE
AffineRank2RowMajor(
LongIndex stride
) { stride_[0] = stride; stride_[1] = 1;}
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static AffineRank2RowMajor packed(MatrixCoord const &extent) {
return AffineRank2RowMajor(extent.column(), 1);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
return dot(coord, stride_);
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
// TODO
return MatrixCoord(0, 0);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return extent.row() * stride_[0];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
// Utility functions to convert stride_factor to the strides used by the Affine2 layout.
//
// stride_factor is the logical distance between two coorinates.
//
// All Coodinates used here are matrix coordinates. stride[0] and extent[0] are for the
// rows. stride[1] and extent[1] are for the columns.
template <typename Affine2Layout>
struct Affine2Layout_Factory {
CUTLASS_HOST_DEVICE
static Affine2Layout layout_factory(cutlass::Coord<2> const &extent, typename Affine2Layout::Stride stride_factor) {
return Affine2Layout::packed(extent);
}
};
template <>
struct Affine2Layout_Factory<cutlass::layout::AffineRank2ColumnMajor> {
CUTLASS_HOST_DEVICE
static cutlass::layout::AffineRank2ColumnMajor layout_factory(
cutlass::Coord<2> const &extent,
typename cutlass::layout::AffineRank2ColumnMajor::Stride stride_factor) {
return cutlass::layout::AffineRank2ColumnMajor({ stride_factor[0], stride_factor[0] * stride_factor[1] * extent[0] });
}
};
template <>
struct Affine2Layout_Factory<cutlass::layout::AffineRank2RowMajor> {
CUTLASS_HOST_DEVICE
static cutlass::layout::AffineRank2RowMajor layout_factory(
cutlass::Coord<2> const &extent,
typename cutlass::layout::AffineRank2RowMajor::Stride stride_factor) {
return cutlass::layout::AffineRank2RowMajor({ stride_factor[0] * stride_factor[1] * extent[1], stride_factor[1] });
}
};
// The base layout cutlass::layout::AffineRankN<2> is similar to AffineRank2ColumnMajor
template <>
struct Affine2Layout_Factory<cutlass::layout::AffineRankN<2>> {
CUTLASS_HOST_DEVICE
static cutlass::layout::AffineRankN<2> layout_factory(
cutlass::Coord<2> const &extent,
typename cutlass::layout::AffineRankN<2>::Stride stride_factor) {
return cutlass::layout::AffineRankN<2>({ stride_factor[0], stride_factor[0] * stride_factor[1] * extent[0] });
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Mapping function for block-linear matrices. Matrix is structured
/// as column-major arrangement of 2D tiles (that are column-major).
template <int BlockRows, int BlockColumns>
struct ColumnMajorBlockLinear {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
/// Size of a block in rows
static int const kBlockRows = BlockRows;
/// Size of a block in columns
static int const kBlockColumns = BlockColumns;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
ColumnMajorBlockLinear(Index ldm = 0): stride_(ldm) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static ColumnMajorBlockLinear packed(MatrixCoord const &extent) {
return ColumnMajorBlockLinear(extent.row() * kBlockRows * kBlockColumns);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
return
(coord.row() % kBlockRows) +
(coord.column() % kBlockColumns) * kBlockRows +
(coord.row() / kBlockRows) * kBlockRows * kBlockColumns +
(coord.column() / kBlockColumns) * stride_[0];
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
// TODO
return MatrixCoord(0, 0);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return (extent.column() + kBlockColumns - 1) / kBlockColumns * stride_[0];
}
};
/// Mapping function for block-linear matrices. Matrix is structured
/// as row-major arrangement of 2D tiles (that are row-major)
template <int BlockRows, int BlockColumns>
struct RowMajorBlockLinear {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 1;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, LongIndex>;
/// Size of a block in rows
static int const kBlockRows = BlockRows;
/// Size of a block in columns
static int const kBlockColumns = BlockColumns;
private:
//
// Data members
//
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
RowMajorBlockLinear(Index ldm = 0): stride_(ldm) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static RowMajorBlockLinear packed(MatrixCoord const &extent) {
return RowMajorBlockLinear(extent.column() * kBlockRows * kBlockColumns);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
return
(coord.column() % kBlockColumns) +
(coord.row() % kBlockRows) * kBlockColumns +
(coord.column() / kBlockColumns) * kBlockRows * kBlockColumns +
(coord.row() / kBlockRows) * stride_[0];
}
/// Inverse of layout function, mapping linear offset to logical coordinate
CUTLASS_HOST_DEVICE
MatrixCoord inverse(LongIndex offset) const {
// TODO
return MatrixCoord(0, 0);
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
return (extent.row() + kBlockRows - 1) / kBlockRows * stride_[0];
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
struct GeneralMatrix {
/// Logical rank of tensor
static int const kRank = 2;
/// Rank of stride vector
static int const kStrideRank = 2;
/// Index type used for coordinates
using Index = int32_t;
/// Long index type used for offsets
using LongIndex = int64_t;
/// Logical coordinate
using TensorCoord = MatrixCoord;
/// Stride vector
using Stride = Coord<kStrideRank, Index>;
private:
//
// Data members
//
Matrix layout_id_;
/// Stride data member
Stride stride_;
public:
//
// Methods
//
/// Ctor
CUTLASS_HOST_DEVICE
GeneralMatrix(): layout_id_(Matrix::kColumnMajor), stride_(make_Coord(0, 1)) { }
/// Ctor
CUTLASS_HOST_DEVICE
GeneralMatrix(
Matrix layout_id,
Index ldm,
Index interleave): layout_id_(layout_id), stride_(make_Coord(ldm, interleave)) { }
/// Helper returns a layout to a tightly packed tensor
CUTLASS_HOST_DEVICE
static GeneralMatrix packed(
MatrixCoord const &extent,
Matrix layout_id = Matrix::kColumnMajor,
Index interleave = 1) {
Index c;
if (layout_id == Matrix::kRowMajor) {
c = extent.column();
}
else {
c = extent.row();
}
Index ldm = c * interleave;
return GeneralMatrix(layout_id, ldm, interleave);
}
/// Returns the offset of a coordinate in linear memory.
/// Assumes coordinate has convention (row, column)
CUTLASS_HOST_DEVICE
LongIndex operator()(MatrixCoord const &coord) const {
Index c, s;
if (layout_id_ == Matrix::kRowMajor) {
c = coord.column();
s = coord.row();
}
else {
s = coord.column();
c = coord.row();
}
Index v = s / stride_[1];
Index residual = (s % stride_[1]);
return LongIndex(c) * LongIndex(stride_[1]) + LongIndex(v) * LongIndex(stride_[0]) + residual;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride stride() const {
return stride_;
}
CUTLASS_HOST_DEVICE
Matrix layout_id() const {
return layout_id_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
Stride & stride() {
return stride_;
}
CUTLASS_HOST_DEVICE
Matrix & layout_id() {
return layout_id_;
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index stride(int idx) const {
return stride_[idx];
}
/// Returns the stride of the layout
CUTLASS_HOST_DEVICE
typename Stride::Index & stride(int idx) {
return stride_[idx];
}
/// Compute the number of contiguous elements needed to store a tensor with the given size
CUTLASS_HOST_DEVICE
LongIndex capacity(MatrixCoord const &extent) const {
Index s;
if (layout_id_ == Matrix::kRowMajor) {
s = extent.row();
}
else {
s = extent.column();
}
Index v = Index((s + stride_[1] - 1) / stride_[1]);
return LongIndex(v) * LongIndex(stride_[0]);
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/// Defines transposes of matrix layouts
template <typename Layout>
struct LayoutTranspose;
/// Transpose of row-major is column-major
template <>
struct LayoutTranspose<layout::RowMajor> {
using type = layout::ColumnMajor;
};
/// Transpose of column-major is row-major
template <>
struct LayoutTranspose<layout::ColumnMajor> {
using type = layout::RowMajor;
};
/////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace layout
} // namespace cutlass
| 34,712 | C | 24.675296 | 122 | 0.664813 |
NVIDIA/warp/warp/sim/import_usd.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import re
import numpy as np
import warp as wp
def parse_usd(
source,
builder,
default_density=1.0e3,
only_load_enabled_rigid_bodies=False,
only_load_enabled_joints=True,
contact_ke=1e5,
contact_kd=250.0,
contact_kf=500.0,
contact_ka=0.0,
contact_mu=0.6,
contact_restitution=0.0,
contact_thickness=0.0,
joint_limit_ke=100.0,
joint_limit_kd=10.0,
armature=0.0,
invert_rotations=False,
verbose=False,
ignore_paths=None,
):
"""
Parses a Universal Scene Description (USD) stage containing UsdPhysics schema definitions for rigid-body articulations and adds the bodies, shapes and joints to the given ModelBuilder.
The USD description has to be either a path (file name or URL), or an existing USD stage instance that implements the `UsdStage <https://openusd.org/dev/api/class_usd_stage.html>`_ interface.
Args:
source (str | pxr.UsdStage): The file path to the USD file, or an existing USD stage instance.
builder (ModelBuilder): The :class:`ModelBuilder` to add the bodies and joints to.
default_density (float): The default density to use for bodies without a density attribute.
only_load_enabled_rigid_bodies (bool): If True, only rigid bodies which do not have `physics:rigidBodyEnabled` set to False are loaded.
only_load_enabled_joints (bool): If True, only joints which do not have `physics:jointEnabled` set to False are loaded.
contact_ke (float): The default contact stiffness to use, only considered by the Euler integrators.
contact_kd (float): The default contact damping to use, only considered by the Euler integrators.
contact_kf (float): The default friction stiffness to use, only considered by the Euler integrators.
contact_ka (float): The default adhesion distance to use, only considered by the Euler integrators.
contact_mu (float): The default friction coefficient to use if a shape has not friction coefficient defined.
contact_restitution (float): The default coefficient of restitution to use if a shape has not coefficient of restitution defined.
contact_thickness (float): The thickness to add to the shape geometry.
joint_limit_ke (float): The default stiffness to use for joint limits, only considered by the Euler integrators.
joint_limit_kd (float): The default damping to use for joint limits, only considered by the Euler integrators.
armature (float): The armature to use for the bodies.
invert_rotations (bool): If True, inverts any rotations defined in the shape transforms.
verbose (bool): If True, print additional information about the parsed USD file.
ignore_paths (List[str]): A list of regular expressions matching prim paths to ignore.
Returns:
dict: Dictionary with the following entries:
.. list-table::
:widths: 25 75
* - "fps"
- USD stage frames per second
* - "duration"
- Difference between end time code and start time code of the USD stage
* - "up_axis"
- Upper-case string of the stage's up axis ("X", "Y", or "Z")
* - "path_shape_map"
- Mapping from prim path (str) of the UsdGeom to the respective shape index in :class:`ModelBuilder`
* - "path_body_map"
- Mapping from prim path (str) of a rigid body prim (e.g. that implements the PhysicsRigidBodyAPI) to the respective body index in :class:`ModelBuilder`
* - "path_shape_scale"
- Mapping from prim path (str) of the UsdGeom to its respective 3D world scale
* - "mass_unit"
- The stage's Kilograms Per Unit (KGPU) definition (1.0 by default)
* - "linear_unit"
- The stage's Meters Per Unit (MPU) definition (1.0 by default)
Note:
This importer is experimental and only supports a subset of the USD Physics schema. Please report any issues you encounter.
"""
try:
from pxr import Usd, UsdGeom, UsdPhysics
except ImportError as e:
raise ImportError("Failed to import pxr. Please install USD (e.g. via `pip install usd-core`).") from e
if ignore_paths is None:
ignore_paths = []
def get_attribute(prim, name):
if "*" in name:
regex = name.replace("*", ".*")
for attr in prim.GetAttributes():
if re.match(regex, attr.GetName()):
return attr
else:
return prim.GetAttribute(name)
def has_attribute(prim, name):
attr = get_attribute(prim, name)
return attr.IsValid() and attr.HasAuthoredValue()
def parse_float(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
val = attr.Get()
if np.isfinite(val):
return val
return default
def parse_quat(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
val = attr.Get()
if invert_rotations:
quat = wp.quat(*val.imaginary, -val.real)
else:
quat = wp.quat(*val.imaginary, val.real)
l = wp.length(quat)
if np.isfinite(l) and l > 0.0:
return quat
return default
def parse_vec(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
val = attr.Get()
if np.isfinite(val).all():
return np.array(val, dtype=np.float32)
return default
def parse_generic(prim, name, default=None):
attr = get_attribute(prim, name)
if not attr or not attr.HasAuthoredValue():
return default
return attr.Get()
def str2axis(s: str) -> np.ndarray:
axis = np.zeros(3, dtype=np.float32)
axis["XYZ".index(s.upper())] = 1.0
return axis
if isinstance(source, str):
stage = Usd.Stage.Open(source, Usd.Stage.LoadAll)
else:
stage = source
mass_unit = 1.0
try:
if UsdPhysics.StageHasAuthoredKilogramsPerUnit(stage):
mass_unit = UsdPhysics.GetStageKilogramsPerUnit(stage)
except Exception as e:
if verbose:
print(f"Failed to get mass unit: {e}")
linear_unit = 1.0
try:
if UsdGeom.StageHasAuthoredMetersPerUnit(stage):
linear_unit = UsdGeom.GetStageMetersPerUnit(stage)
except Exception as e:
if verbose:
print(f"Failed to get linear unit: {e}")
def parse_xform(prim):
xform = UsdGeom.Xform(prim)
mat = np.array(xform.GetLocalTransformation(), dtype=np.float32)
if invert_rotations:
rot = wp.quat_from_matrix(wp.mat33(mat[:3, :3].T.flatten()))
else:
rot = wp.quat_from_matrix(wp.mat33(mat[:3, :3].flatten()))
pos = mat[3, :3] * linear_unit
scale = np.ones(3, dtype=np.float32)
for op in xform.GetOrderedXformOps():
if op.GetOpType() == UsdGeom.XformOp.TypeScale:
scale = np.array(op.Get(), dtype=np.float32)
return wp.transform(pos, rot), scale
def parse_axis(prim, type, joint_data, is_angular, axis=None):
# parse joint axis data
schemas = prim.GetAppliedSchemas()
schemas_str = "".join(schemas)
if f"DriveAPI:{type}" not in schemas_str and f"PhysicsLimitAPI:{type}" not in schemas_str:
return
drive_type = parse_generic(prim, f"drive:{type}:physics:type", "force")
if drive_type != "force":
print(f"Warning: only force drive type is supported, ignoring drive:{type} for joint {path}")
return
stiffness = parse_float(prim, f"drive:{type}:physics:stiffness", 0.0)
damping = parse_float(prim, f"drive:{type}:physics:damping", 0.0)
low = parse_float(prim, f"limit:{type}:physics:low")
high = parse_float(prim, f"limit:{type}:physics:high")
target_pos = parse_float(prim, f"drive:{type}:physics:targetPosition")
target_vel = parse_float(prim, f"drive:{type}:physics:targetVelocity")
if is_angular:
stiffness *= mass_unit * linear_unit**2
stiffness = np.deg2rad(stiffness)
damping *= mass_unit * linear_unit**2
damping = np.deg2rad(damping)
if target_pos is not None:
target_pos = np.deg2rad(target_pos)
if target_vel is not None:
target_vel = np.deg2rad(target_vel)
if low is None:
low = joint_data["lowerLimit"]
else:
low = np.deg2rad(low)
if high is None:
high = joint_data["upperLimit"]
else:
high = np.deg2rad(high)
else:
stiffness *= mass_unit
damping *= mass_unit
if target_pos is not None:
target_pos *= linear_unit
if target_vel is not None:
target_vel *= linear_unit
if low is None:
low = joint_data["lowerLimit"]
else:
low *= linear_unit
if high is None:
high = joint_data["upperLimit"]
else:
high *= linear_unit
mode = wp.sim.JOINT_MODE_FORCE
if f"DriveAPI:{type}" in schemas_str:
if target_vel is not None and target_vel != 0.0:
mode = wp.sim.JOINT_MODE_TARGET_VELOCITY
else:
mode = wp.sim.JOINT_MODE_TARGET_POSITION
if low > high:
low = (low + high) / 2
high = low
axis = wp.sim.JointAxis(
axis=(axis or joint_data["axis"]),
limit_lower=low,
limit_upper=high,
action=(target_pos or target_vel or (low + high) / 2),
target_ke=stiffness,
target_kd=damping,
mode=mode,
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
if is_angular:
joint_data["angular_axes"].append(axis)
else:
joint_data["linear_axes"].append(axis)
axis_str = "Y"
try:
axis_str = UsdGeom.GetStageUpAxis(stage)
except Exception as e:
if verbose:
print(f"Failed to parse stage up axis: {e}")
upaxis = str2axis(axis_str)
shape_types = {"Cube", "Sphere", "Mesh", "Capsule", "Plane", "Cylinder", "Cone"}
path_body_map = {}
path_shape_map = {}
path_shape_scale = {}
# maps prim path name to its world transform
path_world_poses = {}
# transform from body frame to where the actual joint child frame is
# so that the link's children will use the right parent tf for the joint
prim_joint_xforms = {}
path_collision_filters = set()
no_collision_shapes = set()
body_density = {} # mapping from body ID to defined density
# first find all joints and materials
joint_data = {} # mapping from path of child link to joint USD settings
materials = {} # mapping from material path to material USD settings
joint_parents = set() # paths of joint parents
for prim in stage.Traverse():
type_name = str(prim.GetTypeName())
path = str(prim.GetPath())
# if verbose:
# print(path, type_name)
if type_name.endswith("Joint"):
# the type name can sometimes be "DistancePhysicsJoint" or "PhysicsDistanceJoint" ...
type_name = type_name.replace("Physics", "").replace("Joint", "")
child = str(prim.GetRelationship("physics:body1").GetTargets()[0])
pos0 = parse_vec(prim, "physics:localPos0", np.zeros(3, dtype=np.float32)) * linear_unit
pos1 = parse_vec(prim, "physics:localPos1", np.zeros(3, dtype=np.float32)) * linear_unit
rot0 = parse_quat(prim, "physics:localRot0", wp.quat_identity())
rot1 = parse_quat(prim, "physics:localRot1", wp.quat_identity())
joint_data[child] = {
"type": type_name,
"name": str(prim.GetName()),
"parent_tf": wp.transform(pos0, rot0),
"child_tf": wp.transform(pos1, rot1),
"enabled": parse_generic(prim, "physics:jointEnabled", True),
"collisionEnabled": parse_generic(prim, "physics:collisionEnabled", False),
"excludeFromArticulation": parse_generic(prim, "physics:excludeFromArticulation", False),
"axis": str2axis(parse_generic(prim, "physics:axis", "X")),
"breakForce": parse_float(prim, "physics:breakForce", np.inf),
"breakTorque": parse_float(prim, "physics:breakTorque", np.inf),
"linear_axes": [],
"angular_axes": [],
}
if only_load_enabled_joints and not joint_data[child]["enabled"]:
print("Skipping disabled joint", path)
continue
# parse joint limits
lower = parse_float(prim, "physics:lowerLimit", -np.inf)
upper = parse_float(prim, "physics:upperLimit", np.inf)
if type_name == "Distance":
# if distance is negative the joint is not limited
joint_data[child]["lowerLimit"] = parse_float(prim, "physics:minDistance", -1.0) * linear_unit
joint_data[child]["upperLimit"] = parse_float(prim, "physics:maxDistance", -1.0) * linear_unit
elif type_name == "Prismatic":
joint_data[child]["lowerLimit"] = lower * linear_unit
joint_data[child]["upperLimit"] = upper * linear_unit
else:
joint_data[child]["lowerLimit"] = np.deg2rad(lower) if np.isfinite(lower) else lower
joint_data[child]["upperLimit"] = np.deg2rad(upper) if np.isfinite(upper) else upper
if joint_data[child]["lowerLimit"] > joint_data[child]["upperLimit"]:
joint_data[child]["lowerLimit"] = (
joint_data[child]["lowerLimit"] + joint_data[child]["upperLimit"]
) / 2
joint_data[child]["upperLimit"] = joint_data[child]["lowerLimit"]
parents = prim.GetRelationship("physics:body0").GetTargets()
if len(parents) > 0:
parent_path = str(parents[0])
joint_data[child]["parent"] = parent_path
joint_parents.add(parent_path)
else:
joint_data[child]["parent"] = None
# parse joint drive
parse_axis(prim, "angular", joint_data[child], is_angular=True)
parse_axis(prim, "rotX", joint_data[child], is_angular=True, axis=(1.0, 0.0, 0.0))
parse_axis(prim, "rotY", joint_data[child], is_angular=True, axis=(0.0, 1.0, 0.0))
parse_axis(prim, "rotZ", joint_data[child], is_angular=True, axis=(0.0, 0.0, 1.0))
parse_axis(prim, "linear", joint_data[child], is_angular=False)
parse_axis(prim, "transX", joint_data[child], is_angular=False, axis=(1.0, 0.0, 0.0))
parse_axis(prim, "transY", joint_data[child], is_angular=False, axis=(0.0, 1.0, 0.0))
parse_axis(prim, "transZ", joint_data[child], is_angular=False, axis=(0.0, 0.0, 1.0))
elif type_name == "Material":
material = {}
if has_attribute(prim, "physics:density"):
material["density"] = parse_float(prim, "physics:density") * mass_unit # / (linear_unit**3)
if has_attribute(prim, "physics:restitution"):
material["restitution"] = parse_float(prim, "physics:restitution", contact_restitution)
if has_attribute(prim, "physics:staticFriction"):
material["staticFriction"] = parse_float(prim, "physics:staticFriction", contact_mu)
if has_attribute(prim, "physics:dynamicFriction"):
material["dynamicFriction"] = parse_float(prim, "physics:dynamicFriction", contact_mu)
materials[path] = material
elif type_name == "PhysicsScene":
try:
scene = UsdPhysics.Scene(prim)
g_vec = scene.GetGravityDirectionAttr()
g_mag = scene.GetGravityMagnitudeAttr()
if g_mag.HasAuthoredValue() and np.isfinite(g_mag.Get()):
builder.gravity = -np.abs(g_mag.Get() * linear_unit)
if g_vec.HasAuthoredValue() and np.linalg.norm(g_vec.Get()) > 0.0:
builder.up_vector = np.array(g_vec.Get(), dtype=np.float32)
if np.any(builder.up_vector < 0.0):
builder.up_vector = -builder.up_vector
else:
builder.up_vector = upaxis
except Exception as e:
if verbose:
print(f"Failed to parse physics scene: {e}")
def parse_prim(prim, incoming_xform, incoming_scale, parent_body: int = -1):
nonlocal builder
nonlocal joint_data
nonlocal path_body_map
nonlocal path_shape_map
nonlocal path_shape_scale
nonlocal path_world_poses
nonlocal prim_joint_xforms
nonlocal path_collision_filters
nonlocal no_collision_shapes
nonlocal body_density
path = str(prim.GetPath())
for pattern in ignore_paths:
if re.match(pattern, path):
return
type_name = str(prim.GetTypeName())
if type_name.endswith("Joint") or type_name.endswith("Light") or type_name.endswith("Material"):
return
if verbose:
print(f"parse_prim {prim.GetPath()} ({type_name})")
if type_name == "PhysicsScene":
# in case the PhysicsScene has bodies as children...
for child in prim.GetChildren():
parse_prim(child, incoming_xform, incoming_scale, parent_body)
schemas = set(prim.GetAppliedSchemas())
children_refs = prim.GetChildren()
prim_joint_xforms[path] = wp.transform()
local_xform, scale = parse_xform(prim)
scale = incoming_scale * scale
xform = wp.mul(incoming_xform, local_xform)
path_world_poses[path] = xform
geo_tf = local_xform
body_id = parent_body
is_rigid_body = "PhysicsRigidBodyAPI" in schemas and parent_body == -1
create_rigid_body = is_rigid_body or path in joint_parents
if create_rigid_body:
body_id = builder.add_body(
origin=xform,
name=prim.GetName(),
armature=armature,
)
path_body_map[path] = body_id
body_density[body_id] = 0.0
parent_body = body_id
geo_tf = wp.transform()
# set up joints between rigid bodies after the children have been added
if path in joint_data:
joint = joint_data[path]
joint_params = {
"child": body_id,
"linear_axes": joint["linear_axes"],
"angular_axes": joint["angular_axes"],
"name": joint["name"],
"enabled": joint["enabled"],
"parent_xform": joint["parent_tf"],
"child_xform": joint["child_tf"],
"armature": armature,
}
parent_path = joint["parent"]
if parent_path is None:
joint_params["parent"] = -1
parent_tf = wp.transform()
else:
joint_params["parent"] = path_body_map[parent_path]
parent_tf = path_world_poses[parent_path]
# the joint to which we are connected will transform this body already
geo_tf = wp.transform()
if verbose:
print(f"Adding joint {joint['name']} between {joint['parent']} and {path}")
print(" parent_xform", joint["parent_tf"])
print(" child_xform ", joint["child_tf"])
print(" parent_tf ", parent_tf)
print(f" geo_tf at {path} = {geo_tf} (xform was {xform})")
if joint["type"] == "Revolute":
joint_params["joint_type"] = wp.sim.JOINT_REVOLUTE
if len(joint_params["angular_axes"]) == 0:
joint_params["angular_axes"].append(
wp.sim.JointAxis(
joint["axis"],
limit_lower=joint["lowerLimit"],
limit_upper=joint["upperLimit"],
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
)
elif joint["type"] == "Prismatic":
joint_params["joint_type"] = wp.sim.JOINT_PRISMATIC
if len(joint_params["linear_axes"]) == 0:
joint_params["linear_axes"].append(
wp.sim.JointAxis(
joint["axis"],
limit_lower=joint["lowerLimit"],
limit_upper=joint["upperLimit"],
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
)
elif joint["type"] == "Spherical":
joint_params["joint_type"] = wp.sim.JOINT_BALL
elif joint["type"] == "Fixed":
joint_params["joint_type"] = wp.sim.JOINT_FIXED
elif joint["type"] == "Distance":
joint_params["joint_type"] = wp.sim.JOINT_DISTANCE
# we have to add a dummy linear X axis to define the joint limits
joint_params["linear_axes"].append(
wp.sim.JointAxis(
(1.0, 0.0, 0.0),
limit_lower=joint["lowerLimit"],
limit_upper=joint["upperLimit"],
limit_ke=joint_limit_ke,
limit_kd=joint_limit_kd,
)
)
elif joint["type"] == "":
joint_params["joint_type"] = wp.sim.JOINT_D6
else:
print(f"Warning: unsupported joint type {joint['type']} for {path}")
builder.add_joint(**joint_params)
elif is_rigid_body:
builder.add_joint_free(child=body_id)
# free joint; we set joint_q/qd, not body_q/qd since eval_fk is used after model creation
builder.joint_q[-4:] = xform.q
builder.joint_q[-7:-4] = xform.p
linear_vel = parse_vec(prim, "physics:velocity", np.zeros(3, dtype=np.float32)) * linear_unit
angular_vel = parse_vec(prim, "physics:angularVelocity", np.zeros(3, dtype=np.float32)) * linear_unit
builder.joint_qd[-6:-3] = angular_vel
builder.joint_qd[-3:] = linear_vel
if verbose:
print(f"added {type_name} body {body_id} ({path}) at {xform}")
density = None
material = None
if prim.HasRelationship("material:binding:physics"):
other_paths = prim.GetRelationship("material:binding:physics").GetTargets()
if len(other_paths) > 0:
material = materials[str(other_paths[0])]
if material is not None:
if "density" in material:
density = material["density"]
if has_attribute(prim, "physics:density"):
d = parse_float(prim, "physics:density")
density = d * mass_unit # / (linear_unit**3)
# assert prim.GetAttribute('orientation').Get() == "rightHanded", "Only right-handed orientations are supported."
enabled = parse_generic(prim, "physics:rigidBodyEnabled", True)
if only_load_enabled_rigid_bodies and not enabled:
if verbose:
print("Skipping disabled rigid body", path)
return
mass = parse_float(prim, "physics:mass")
if is_rigid_body:
if density is None:
density = default_density
body_density[body_id] = density
elif density is None:
if body_id >= 0:
density = body_density[body_id]
else:
density = 0.0
com = parse_vec(prim, "physics:centerOfMass", np.zeros(3, dtype=np.float32))
i_diag = parse_vec(prim, "physics:diagonalInertia", np.zeros(3, dtype=np.float32))
i_rot = parse_quat(prim, "physics:principalAxes", wp.quat_identity())
# parse children
if type_name == "Xform":
if prim.IsInstance():
proto = prim.GetPrototype()
for child in proto.GetChildren():
parse_prim(child, xform, scale, parent_body)
else:
for child in children_refs:
parse_prim(child, xform, scale, parent_body)
elif type_name == "Scope":
for child in children_refs:
parse_prim(child, incoming_xform, incoming_scale, parent_body)
elif type_name in shape_types:
# parse shapes
shape_params = {
"ke": contact_ke,
"kd": contact_kd,
"kf": contact_kf,
"ka": contact_ka,
"mu": contact_mu,
"restitution": contact_restitution,
}
if material is not None:
if "restitution" in material:
shape_params["restitution"] = material["restitution"]
if "dynamicFriction" in material:
shape_params["mu"] = material["dynamicFriction"]
if has_attribute(prim, "doubleSided") and not prim.GetAttribute("doubleSided").Get():
print(f"Warning: treating {path} as double-sided because single-sided collisions are not supported.")
if type_name == "Cube":
size = parse_float(prim, "size", 2.0)
if has_attribute(prim, "extents"):
extents = parse_vec(prim, "extents") * scale
# TODO position geom at extents center?
# geo_pos = 0.5 * (extents[0] + extents[1])
extents = extents[1] - extents[0]
else:
extents = scale * size
shape_id = builder.add_shape_box(
body_id,
geo_tf.p,
geo_tf.q,
hx=extents[0] / 2,
hy=extents[1] / 2,
hz=extents[2] / 2,
density=density,
thickness=contact_thickness,
**shape_params,
)
elif type_name == "Sphere":
if not (scale[0] == scale[1] == scale[2]):
print("Warning: Non-uniform scaling of spheres is not supported.")
if has_attribute(prim, "extents"):
extents = parse_vec(prim, "extents") * scale
# TODO position geom at extents center?
# geo_pos = 0.5 * (extents[0] + extents[1])
extents = extents[1] - extents[0]
if not (extents[0] == extents[1] == extents[2]):
print("Warning: Non-uniform extents of spheres are not supported.")
radius = extents[0]
else:
radius = parse_float(prim, "radius", 1.0) * scale[0]
shape_id = builder.add_shape_sphere(
body_id, geo_tf.p, geo_tf.q, radius, density=density, **shape_params
)
elif type_name == "Plane":
normal_str = parse_generic(prim, "axis", "Z").upper()
geo_rot = geo_tf.q
if normal_str != "Y":
normal = str2axis(normal_str)
c = np.cross(normal, (0.0, 1.0, 0.0))
angle = np.arcsin(np.linalg.norm(c))
axis = c / np.linalg.norm(c)
geo_rot = wp.mul(geo_rot, wp.quat_from_axis_angle(axis, angle))
width = parse_float(prim, "width", 0.0) * scale[0]
length = parse_float(prim, "length", 0.0) * scale[1]
shape_id = builder.add_shape_plane(
body=body_id,
pos=geo_tf.p,
rot=geo_rot,
width=width,
length=length,
thickness=contact_thickness,
**shape_params,
)
elif type_name == "Capsule":
axis_str = parse_generic(prim, "axis", "Z").upper()
radius = parse_float(prim, "radius", 0.5) * scale[0]
half_height = parse_float(prim, "height", 2.0) / 2 * scale[1]
assert not has_attribute(prim, "extents"), "Capsule extents are not supported."
shape_id = builder.add_shape_capsule(
body_id,
geo_tf.p,
geo_tf.q,
radius,
half_height,
density=density,
up_axis="XYZ".index(axis_str),
**shape_params,
)
elif type_name == "Cylinder":
axis_str = parse_generic(prim, "axis", "Z").upper()
radius = parse_float(prim, "radius", 0.5) * scale[0]
half_height = parse_float(prim, "height", 2.0) / 2 * scale[1]
assert not has_attribute(prim, "extents"), "Cylinder extents are not supported."
shape_id = builder.add_shape_cylinder(
body_id,
geo_tf.p,
geo_tf.q,
radius,
half_height,
density=density,
up_axis="XYZ".index(axis_str),
**shape_params,
)
elif type_name == "Cone":
axis_str = parse_generic(prim, "axis", "Z").upper()
radius = parse_float(prim, "radius", 0.5) * scale[0]
half_height = parse_float(prim, "height", 2.0) / 2 * scale[1]
assert not has_attribute(prim, "extents"), "Cone extents are not supported."
shape_id = builder.add_shape_cone(
body_id,
geo_tf.p,
geo_tf.q,
radius,
half_height,
density=density,
up_axis="XYZ".index(axis_str),
**shape_params,
)
elif type_name == "Mesh":
mesh = UsdGeom.Mesh(prim)
points = np.array(mesh.GetPointsAttr().Get(), dtype=np.float32)
indices = np.array(mesh.GetFaceVertexIndicesAttr().Get(), dtype=np.float32)
counts = mesh.GetFaceVertexCountsAttr().Get()
faces = []
face_id = 0
for count in counts:
if count == 3:
faces.append(indices[face_id : face_id + 3])
elif count == 4:
faces.append(indices[face_id : face_id + 3])
faces.append(indices[[face_id, face_id + 2, face_id + 3]])
else:
# assert False, f"Error while parsing USD mesh {path}: encountered polygon with {count} vertices, but only triangles and quads are supported."
continue
face_id += count
m = wp.sim.Mesh(points, np.array(faces, dtype=np.int32).flatten())
shape_id = builder.add_shape_mesh(
body_id,
geo_tf.p,
geo_tf.q,
scale=scale,
mesh=m,
density=density,
thickness=contact_thickness,
**shape_params,
)
else:
print(f"Warning: Unsupported geometry type {type_name} at {path}.")
return
path_body_map[path] = body_id
path_shape_map[path] = shape_id
path_shape_scale[path] = scale
if prim.HasRelationship("physics:filteredPairs"):
other_paths = prim.GetRelationship("physics:filteredPairs").GetTargets()
for other_path in other_paths:
path_collision_filters.add((path, str(other_path)))
if "PhysicsCollisionAPI" not in schemas or not parse_generic(prim, "physics:collisionEnabled", True):
no_collision_shapes.add(shape_id)
else:
print(f"Warning: encountered unsupported prim type {type_name}")
# update mass properties of rigid bodies in cases where properties are defined with higher precedence
if body_id >= 0:
com = parse_vec(prim, "physics:centerOfMass")
if com is not None:
# overwrite COM
builder.body_com[body_id] = com * scale
if mass is not None and not (is_rigid_body and mass == 0.0):
mass_ratio = mass / builder.body_mass[body_id]
# mass has precedence over density, so we overwrite the mass computed from density
builder.body_mass[body_id] = mass * mass_unit
if mass > 0.0:
builder.body_inv_mass[body_id] = 1.0 / builder.body_mass[body_id]
else:
builder.body_inv_mass[body_id] = 0.0
# update inertia
builder.body_inertia[body_id] *= mass_ratio
if np.array(builder.body_inertia[body_id]).any():
builder.body_inv_inertia[body_id] = wp.inverse(builder.body_inertia[body_id])
else:
builder.body_inv_inertia[body_id] = wp.mat33(*np.zeros((3, 3), dtype=np.float32))
if np.linalg.norm(i_diag) > 0.0:
rot = np.array(wp.quat_to_matrix(i_rot), dtype=np.float32).reshape(3, 3)
inertia = rot @ np.diag(i_diag) @ rot.T
builder.body_inertia[body_id] = inertia
if inertia.any():
builder.body_inv_inertia[body_id] = wp.inverse(wp.mat33(*inertia))
else:
builder.body_inv_inertia[body_id] = wp.mat33(*np.zeros((3, 3), dtype=np.float32))
parse_prim(
stage.GetDefaultPrim(), incoming_xform=wp.transform(), incoming_scale=np.ones(3, dtype=np.float32) * linear_unit
)
shape_count = len(builder.shape_geo_type)
# apply collision filters now that we have added all shapes
for path1, path2 in path_collision_filters:
shape1 = path_shape_map[path1]
shape2 = path_shape_map[path2]
builder.shape_collision_filter_pairs.add((shape1, shape2))
# apply collision filters to all shapes that have no collision
for shape_id in no_collision_shapes:
for other_shape_id in range(shape_count):
if other_shape_id != shape_id:
builder.shape_collision_filter_pairs.add((shape_id, other_shape_id))
# return stage parameters
return {
"fps": stage.GetFramesPerSecond(),
"duration": stage.GetEndTimeCode() - stage.GetStartTimeCode(),
"up_axis": UsdGeom.GetStageUpAxis(stage).upper(),
"path_shape_map": path_shape_map,
"path_body_map": path_body_map,
"path_shape_scale": path_shape_scale,
"mass_unit": mass_unit,
"linear_unit": linear_unit,
}
def resolve_usd_from_url(url: str, target_folder_name: str = None, export_usda: bool = False):
"""
Downloads a USD file from a URL and resolves all references to other USD files to be downloaded to the given target folder.
Args:
url (str): URL to the USD file.
target_folder_name (str): Target folder name. If None, a timestamped folder will be created in the current directory.
export_usda (bool): If True, converts each downloaded USD file to USDA and saves the additional USDA file in the target folder with the same base name as the original USD file.
Returns:
str: File path to the downloaded USD file.
"""
import datetime
import os
import requests
try:
from pxr import Usd
except ImportError as e:
raise ImportError("Failed to import pxr. Please install USD (e.g. via `pip install usd-core`).") from e
response = requests.get(url, allow_redirects=True)
if response.status_code != 200:
raise RuntimeError(f"Failed to download USD file. Status code: {response.status_code}")
file = response.content
dot = os.path.extsep
base = os.path.basename(url)
url_folder = os.path.dirname(url)
base_name = dot.join(base.split(dot)[:-1])
if target_folder_name is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
target_folder_name = os.path.join(".usd_cache", f"{base_name}_{timestamp}")
os.makedirs(target_folder_name, exist_ok=True)
target_filename = os.path.join(target_folder_name, base)
with open(target_filename, "wb") as f:
f.write(file)
stage = Usd.Stage.Open(target_filename, Usd.Stage.LoadNone)
stage_str = stage.GetRootLayer().ExportToString()
print(f"Downloaded USD file to {target_filename}.")
if export_usda:
usda_filename = os.path.join(target_folder_name, base_name + ".usda")
with open(usda_filename, "w") as f:
f.write(stage_str)
print(f"Exported USDA file to {usda_filename}.")
# parse referenced USD files like `references = @./franka_collisions.usd@`
downloaded = set()
for match in re.finditer(r"references.=.@(.*?)@", stage_str):
refname = match.group(1)
if refname.startswith("./"):
refname = refname[2:]
if refname in downloaded:
continue
try:
response = requests.get(f"{url_folder}/{refname}", allow_redirects=True)
if response.status_code != 200:
print(f"Failed to download reference {refname}. Status code: {response.status_code}")
continue
file = response.content
refdir = os.path.dirname(refname)
if refdir:
os.makedirs(os.path.join(target_folder_name, refdir), exist_ok=True)
ref_filename = os.path.join(target_folder_name, refname)
if not os.path.exists(ref_filename):
with open(ref_filename, "wb") as f:
f.write(file)
downloaded.add(refname)
print(f"Downloaded USD reference {refname} to {ref_filename}.")
if export_usda:
ref_stage = Usd.Stage.Open(ref_filename, Usd.Stage.LoadNone)
ref_stage_str = ref_stage.GetRootLayer().ExportToString()
base = os.path.basename(ref_filename)
base_name = dot.join(base.split(dot)[:-1])
usda_filename = os.path.join(target_folder_name, base_name + ".usda")
with open(usda_filename, "w") as f:
f.write(ref_stage_str)
print(f"Exported USDA file to {usda_filename}.")
except Exception:
print(f"Failed to download {refname}.")
return target_filename
| 40,498 | Python | 44.606982 | 195 | 0.545953 |
NVIDIA/warp/warp/sim/integrator_featherstone.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from .articulation import (
compute_2d_rotational_dofs,
compute_3d_rotational_dofs,
eval_fk,
)
from .integrator import Integrator
from .integrator_euler import (
eval_bending_forces,
eval_joint_force,
eval_muscle_forces,
eval_particle_body_contact_forces,
eval_particle_forces,
eval_particle_ground_contact_forces,
eval_rigid_contacts,
eval_spring_forces,
eval_tetrahedral_forces,
eval_triangle_contact_forces,
eval_triangle_forces,
)
from .model import Control, Model, State
# Frank & Park definition 3.20, pg 100
@wp.func
def transform_twist(t: wp.transform, x: wp.spatial_vector):
q = wp.transform_get_rotation(t)
p = wp.transform_get_translation(t)
w = wp.spatial_top(x)
v = wp.spatial_bottom(x)
w = wp.quat_rotate(q, w)
v = wp.quat_rotate(q, v) + wp.cross(p, w)
return wp.spatial_vector(w, v)
@wp.func
def transform_wrench(t: wp.transform, x: wp.spatial_vector):
q = wp.transform_get_rotation(t)
p = wp.transform_get_translation(t)
w = wp.spatial_top(x)
v = wp.spatial_bottom(x)
v = wp.quat_rotate(q, v)
w = wp.quat_rotate(q, w) + wp.cross(p, v)
return wp.spatial_vector(w, v)
@wp.func
def spatial_adjoint(R: wp.mat33, S: wp.mat33):
# T = [R 0]
# [S R]
# fmt: off
return wp.spatial_matrix(
R[0, 0], R[0, 1], R[0, 2], 0.0, 0.0, 0.0,
R[1, 0], R[1, 1], R[1, 2], 0.0, 0.0, 0.0,
R[2, 0], R[2, 1], R[2, 2], 0.0, 0.0, 0.0,
S[0, 0], S[0, 1], S[0, 2], R[0, 0], R[0, 1], R[0, 2],
S[1, 0], S[1, 1], S[1, 2], R[1, 0], R[1, 1], R[1, 2],
S[2, 0], S[2, 1], S[2, 2], R[2, 0], R[2, 1], R[2, 2],
)
# fmt: on
@wp.kernel
def compute_spatial_inertia(
body_inertia: wp.array(dtype=wp.mat33),
body_mass: wp.array(dtype=float),
# outputs
body_I_m: wp.array(dtype=wp.spatial_matrix),
):
tid = wp.tid()
I = body_inertia[tid]
m = body_mass[tid]
# fmt: off
body_I_m[tid] = wp.spatial_matrix(
I[0, 0], I[0, 1], I[0, 2], 0.0, 0.0, 0.0,
I[1, 0], I[1, 1], I[1, 2], 0.0, 0.0, 0.0,
I[2, 0], I[2, 1], I[2, 2], 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, m, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, m, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, m,
)
# fmt: on
@wp.kernel
def compute_com_transforms(
body_com: wp.array(dtype=wp.vec3),
# outputs
body_X_com: wp.array(dtype=wp.transform),
):
tid = wp.tid()
com = body_com[tid]
body_X_com[tid] = wp.transform(com, wp.quat_identity())
# computes adj_t^-T*I*adj_t^-1 (tensor change of coordinates), Frank & Park, section 8.2.3, pg 290
@wp.func
def spatial_transform_inertia(t: wp.transform, I: wp.spatial_matrix):
t_inv = wp.transform_inverse(t)
q = wp.transform_get_rotation(t_inv)
p = wp.transform_get_translation(t_inv)
r1 = wp.quat_rotate(q, wp.vec3(1.0, 0.0, 0.0))
r2 = wp.quat_rotate(q, wp.vec3(0.0, 1.0, 0.0))
r3 = wp.quat_rotate(q, wp.vec3(0.0, 0.0, 1.0))
R = wp.mat33(r1, r2, r3)
S = wp.skew(p) @ R
T = spatial_adjoint(R, S)
return wp.mul(wp.mul(wp.transpose(T), I), T)
# compute transform across a joint
@wp.func
def jcalc_transform(
type: int,
joint_axis: wp.array(dtype=wp.vec3),
axis_start: int,
lin_axis_count: int,
ang_axis_count: int,
joint_q: wp.array(dtype=float),
start: int,
):
if type == wp.sim.JOINT_PRISMATIC:
q = joint_q[start]
axis = joint_axis[axis_start]
X_jc = wp.transform(axis * q, wp.quat_identity())
return X_jc
if type == wp.sim.JOINT_REVOLUTE:
q = joint_q[start]
axis = joint_axis[axis_start]
X_jc = wp.transform(wp.vec3(), wp.quat_from_axis_angle(axis, q))
return X_jc
if type == wp.sim.JOINT_BALL:
qx = joint_q[start + 0]
qy = joint_q[start + 1]
qz = joint_q[start + 2]
qw = joint_q[start + 3]
X_jc = wp.transform(wp.vec3(), wp.quat(qx, qy, qz, qw))
return X_jc
if type == wp.sim.JOINT_FIXED:
X_jc = wp.transform_identity()
return X_jc
if type == wp.sim.JOINT_FREE or type == wp.sim.JOINT_DISTANCE:
px = joint_q[start + 0]
py = joint_q[start + 1]
pz = joint_q[start + 2]
qx = joint_q[start + 3]
qy = joint_q[start + 4]
qz = joint_q[start + 5]
qw = joint_q[start + 6]
X_jc = wp.transform(wp.vec3(px, py, pz), wp.quat(qx, qy, qz, qw))
return X_jc
if type == wp.sim.JOINT_COMPOUND:
rot, _ = compute_3d_rotational_dofs(
joint_axis[axis_start],
joint_axis[axis_start + 1],
joint_axis[axis_start + 2],
joint_q[start + 0],
joint_q[start + 1],
joint_q[start + 2],
0.0,
0.0,
0.0,
)
X_jc = wp.transform(wp.vec3(), rot)
return X_jc
if type == wp.sim.JOINT_UNIVERSAL:
rot, _ = compute_2d_rotational_dofs(
joint_axis[axis_start],
joint_axis[axis_start + 1],
joint_q[start + 0],
joint_q[start + 1],
0.0,
0.0,
)
X_jc = wp.transform(wp.vec3(), rot)
return X_jc
if type == wp.sim.JOINT_D6:
pos = wp.vec3(0.0)
rot = wp.quat_identity()
# unroll for loop to ensure joint actions remain differentiable
# (since differentiating through a for loop that updates a local variable is not supported)
if lin_axis_count > 0:
axis = joint_axis[axis_start + 0]
pos += axis * joint_q[start + 0]
if lin_axis_count > 1:
axis = joint_axis[axis_start + 1]
pos += axis * joint_q[start + 1]
if lin_axis_count > 2:
axis = joint_axis[axis_start + 2]
pos += axis * joint_q[start + 2]
ia = axis_start + lin_axis_count
iq = start + lin_axis_count
if ang_axis_count == 1:
axis = joint_axis[ia]
rot = wp.quat_from_axis_angle(axis, joint_q[iq])
if ang_axis_count == 2:
rot, _ = compute_2d_rotational_dofs(
joint_axis[ia + 0],
joint_axis[ia + 1],
joint_q[iq + 0],
joint_q[iq + 1],
0.0,
0.0,
)
if ang_axis_count == 3:
rot, _ = compute_3d_rotational_dofs(
joint_axis[ia + 0],
joint_axis[ia + 1],
joint_axis[ia + 2],
joint_q[iq + 0],
joint_q[iq + 1],
joint_q[iq + 2],
0.0,
0.0,
0.0,
)
X_jc = wp.transform(pos, rot)
return X_jc
# default case
return wp.transform_identity()
# compute motion subspace and velocity for a joint
@wp.func
def jcalc_motion(
type: int,
joint_axis: wp.array(dtype=wp.vec3),
axis_start: int,
lin_axis_count: int,
ang_axis_count: int,
X_sc: wp.transform,
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
q_start: int,
qd_start: int,
# outputs
joint_S_s: wp.array(dtype=wp.spatial_vector),
):
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
S_s = transform_twist(X_sc, wp.spatial_vector(wp.vec3(), axis))
v_j_s = S_s * joint_qd[qd_start]
joint_S_s[qd_start] = S_s
return v_j_s
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
S_s = transform_twist(X_sc, wp.spatial_vector(axis, wp.vec3()))
v_j_s = S_s * joint_qd[qd_start]
joint_S_s[qd_start] = S_s
return v_j_s
if type == wp.sim.JOINT_UNIVERSAL:
axis_0 = joint_axis[axis_start + 0]
axis_1 = joint_axis[axis_start + 1]
q_off = wp.quat_from_matrix(wp.mat33(axis_0, axis_1, wp.cross(axis_0, axis_1)))
local_0 = wp.quat_rotate(q_off, wp.vec3(1.0, 0.0, 0.0))
local_1 = wp.quat_rotate(q_off, wp.vec3(0.0, 1.0, 0.0))
axis_0 = local_0
q_0 = wp.quat_from_axis_angle(axis_0, joint_q[q_start + 0])
axis_1 = wp.quat_rotate(q_0, local_1)
S_0 = transform_twist(X_sc, wp.spatial_vector(axis_0, wp.vec3()))
S_1 = transform_twist(X_sc, wp.spatial_vector(axis_1, wp.vec3()))
joint_S_s[qd_start + 0] = S_0
joint_S_s[qd_start + 1] = S_1
return S_0 * joint_qd[qd_start + 0] + S_1 * joint_qd[qd_start + 1]
if type == wp.sim.JOINT_COMPOUND:
axis_0 = joint_axis[axis_start + 0]
axis_1 = joint_axis[axis_start + 1]
axis_2 = joint_axis[axis_start + 2]
q_off = wp.quat_from_matrix(wp.mat33(axis_0, axis_1, axis_2))
local_0 = wp.quat_rotate(q_off, wp.vec3(1.0, 0.0, 0.0))
local_1 = wp.quat_rotate(q_off, wp.vec3(0.0, 1.0, 0.0))
local_2 = wp.quat_rotate(q_off, wp.vec3(0.0, 0.0, 1.0))
axis_0 = local_0
q_0 = wp.quat_from_axis_angle(axis_0, joint_q[q_start + 0])
axis_1 = wp.quat_rotate(q_0, local_1)
q_1 = wp.quat_from_axis_angle(axis_1, joint_q[q_start + 1])
axis_2 = wp.quat_rotate(q_1 * q_0, local_2)
S_0 = transform_twist(X_sc, wp.spatial_vector(axis_0, wp.vec3()))
S_1 = transform_twist(X_sc, wp.spatial_vector(axis_1, wp.vec3()))
S_2 = transform_twist(X_sc, wp.spatial_vector(axis_2, wp.vec3()))
joint_S_s[qd_start + 0] = S_0
joint_S_s[qd_start + 1] = S_1
joint_S_s[qd_start + 2] = S_2
return S_0 * joint_qd[qd_start + 0] + S_1 * joint_qd[qd_start + 1] + S_2 * joint_qd[qd_start + 2]
if type == wp.sim.JOINT_D6:
v_j_s = wp.spatial_vector()
if lin_axis_count > 0:
axis = joint_axis[axis_start + 0]
S_s = transform_twist(X_sc, wp.spatial_vector(wp.vec3(), axis))
v_j_s += S_s * joint_qd[qd_start + 0]
joint_S_s[qd_start + 0] = S_s
if lin_axis_count > 1:
axis = joint_axis[axis_start + 1]
S_s = transform_twist(X_sc, wp.spatial_vector(wp.vec3(), axis))
v_j_s += S_s * joint_qd[qd_start + 1]
joint_S_s[qd_start + 1] = S_s
if lin_axis_count > 2:
axis = joint_axis[axis_start + 2]
S_s = transform_twist(X_sc, wp.spatial_vector(wp.vec3(), axis))
v_j_s += S_s * joint_qd[qd_start + 2]
joint_S_s[qd_start + 2] = S_s
if ang_axis_count > 0:
axis = joint_axis[axis_start + lin_axis_count + 0]
S_s = transform_twist(X_sc, wp.spatial_vector(axis, wp.vec3()))
v_j_s += S_s * joint_qd[qd_start + lin_axis_count + 0]
joint_S_s[qd_start + lin_axis_count + 0] = S_s
if ang_axis_count > 1:
axis = joint_axis[axis_start + lin_axis_count + 1]
S_s = transform_twist(X_sc, wp.spatial_vector(axis, wp.vec3()))
v_j_s += S_s * joint_qd[qd_start + lin_axis_count + 1]
joint_S_s[qd_start + lin_axis_count + 1] = S_s
if ang_axis_count > 2:
axis = joint_axis[axis_start + lin_axis_count + 2]
S_s = transform_twist(X_sc, wp.spatial_vector(axis, wp.vec3()))
v_j_s += S_s * joint_qd[qd_start + lin_axis_count + 2]
joint_S_s[qd_start + lin_axis_count + 2] = S_s
return v_j_s
if type == wp.sim.JOINT_BALL:
S_0 = transform_twist(X_sc, wp.spatial_vector(1.0, 0.0, 0.0, 0.0, 0.0, 0.0))
S_1 = transform_twist(X_sc, wp.spatial_vector(0.0, 1.0, 0.0, 0.0, 0.0, 0.0))
S_2 = transform_twist(X_sc, wp.spatial_vector(0.0, 0.0, 1.0, 0.0, 0.0, 0.0))
joint_S_s[qd_start + 0] = S_0
joint_S_s[qd_start + 1] = S_1
joint_S_s[qd_start + 2] = S_2
return S_0 * joint_qd[qd_start + 0] + S_1 * joint_qd[qd_start + 1] + S_2 * joint_qd[qd_start + 2]
if type == wp.sim.JOINT_FIXED:
return wp.spatial_vector()
if type == wp.sim.JOINT_FREE or type == wp.sim.JOINT_DISTANCE:
v_j_s = transform_twist(
X_sc,
wp.spatial_vector(
joint_qd[qd_start + 0],
joint_qd[qd_start + 1],
joint_qd[qd_start + 2],
joint_qd[qd_start + 3],
joint_qd[qd_start + 4],
joint_qd[qd_start + 5],
),
)
joint_S_s[qd_start + 0] = transform_twist(X_sc, wp.spatial_vector(1.0, 0.0, 0.0, 0.0, 0.0, 0.0))
joint_S_s[qd_start + 1] = transform_twist(X_sc, wp.spatial_vector(0.0, 1.0, 0.0, 0.0, 0.0, 0.0))
joint_S_s[qd_start + 2] = transform_twist(X_sc, wp.spatial_vector(0.0, 0.0, 1.0, 0.0, 0.0, 0.0))
joint_S_s[qd_start + 3] = transform_twist(X_sc, wp.spatial_vector(0.0, 0.0, 0.0, 1.0, 0.0, 0.0))
joint_S_s[qd_start + 4] = transform_twist(X_sc, wp.spatial_vector(0.0, 0.0, 0.0, 0.0, 1.0, 0.0))
joint_S_s[qd_start + 5] = transform_twist(X_sc, wp.spatial_vector(0.0, 0.0, 0.0, 0.0, 0.0, 1.0))
return v_j_s
wp.printf("jcalc_motion not implemented for joint type %d\n", type)
# default case
return wp.spatial_vector()
# computes joint space forces/torques in tau
@wp.func
def jcalc_tau(
type: int,
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_limit_ke: wp.array(dtype=float),
joint_limit_kd: wp.array(dtype=float),
joint_S_s: wp.array(dtype=wp.spatial_vector),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_act: wp.array(dtype=float),
joint_axis_mode: wp.array(dtype=int),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
coord_start: int,
dof_start: int,
axis_start: int,
lin_axis_count: int,
ang_axis_count: int,
body_f_s: wp.spatial_vector,
# outputs
tau: wp.array(dtype=float),
):
if type == wp.sim.JOINT_PRISMATIC or type == wp.sim.JOINT_REVOLUTE:
S_s = joint_S_s[dof_start]
q = joint_q[coord_start]
qd = joint_qd[dof_start]
act = joint_act[axis_start]
lower = joint_limit_lower[axis_start]
upper = joint_limit_upper[axis_start]
limit_ke = joint_limit_ke[axis_start]
limit_kd = joint_limit_kd[axis_start]
target_ke = joint_target_ke[axis_start]
target_kd = joint_target_kd[axis_start]
mode = joint_axis_mode[axis_start]
# total torque / force on the joint
t = -wp.dot(S_s, body_f_s) + eval_joint_force(
q, qd, act, target_ke, target_kd, lower, upper, limit_ke, limit_kd, mode
)
tau[dof_start] = t
return
if type == wp.sim.JOINT_BALL:
# target_ke = joint_target_ke[axis_start]
# target_kd = joint_target_kd[axis_start]
for i in range(3):
S_s = joint_S_s[dof_start + i]
# w = joint_qd[dof_start + i]
# r = joint_q[coord_start + i]
tau[dof_start + i] = -wp.dot(S_s, body_f_s) # - w * target_kd - r * target_ke
return
if type == wp.sim.JOINT_FREE or type == wp.sim.JOINT_DISTANCE:
for i in range(6):
S_s = joint_S_s[dof_start + i]
tau[dof_start + i] = -wp.dot(S_s, body_f_s)
return
if type == wp.sim.JOINT_COMPOUND or type == wp.sim.JOINT_UNIVERSAL or type == wp.sim.JOINT_D6:
axis_count = lin_axis_count + ang_axis_count
for i in range(axis_count):
S_s = joint_S_s[dof_start + i]
q = joint_q[coord_start + i]
qd = joint_qd[dof_start + i]
act = joint_act[axis_start + i]
lower = joint_limit_lower[axis_start + i]
upper = joint_limit_upper[axis_start + i]
limit_ke = joint_limit_ke[axis_start + i]
limit_kd = joint_limit_kd[axis_start + i]
target_ke = joint_target_ke[axis_start + i]
target_kd = joint_target_kd[axis_start + i]
mode = joint_axis_mode[axis_start + i]
f = eval_joint_force(q, qd, act, target_ke, target_kd, lower, upper, limit_ke, limit_kd, mode)
# total torque / force on the joint
t = -wp.dot(S_s, body_f_s) + f
tau[dof_start + i] = t
return
@wp.func
def jcalc_integrate(
type: int,
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_qdd: wp.array(dtype=float),
coord_start: int,
dof_start: int,
lin_axis_count: int,
ang_axis_count: int,
dt: float,
# outputs
joint_q_new: wp.array(dtype=float),
joint_qd_new: wp.array(dtype=float),
):
if type == wp.sim.JOINT_FIXED:
return
# prismatic / revolute
if type == wp.sim.JOINT_PRISMATIC or type == wp.sim.JOINT_REVOLUTE:
qdd = joint_qdd[dof_start]
qd = joint_qd[dof_start]
q = joint_q[coord_start]
qd_new = qd + qdd * dt
q_new = q + qd_new * dt
joint_qd_new[dof_start] = qd_new
joint_q_new[coord_start] = q_new
return
# ball
if type == wp.sim.JOINT_BALL:
m_j = wp.vec3(joint_qdd[dof_start + 0], joint_qdd[dof_start + 1], joint_qdd[dof_start + 2])
w_j = wp.vec3(joint_qd[dof_start + 0], joint_qd[dof_start + 1], joint_qd[dof_start + 2])
r_j = wp.quat(
joint_q[coord_start + 0], joint_q[coord_start + 1], joint_q[coord_start + 2], joint_q[coord_start + 3]
)
# symplectic Euler
w_j_new = w_j + m_j * dt
drdt_j = wp.quat(w_j_new, 0.0) * r_j * 0.5
# new orientation (normalized)
r_j_new = wp.normalize(r_j + drdt_j * dt)
# update joint coords
joint_q_new[coord_start + 0] = r_j_new[0]
joint_q_new[coord_start + 1] = r_j_new[1]
joint_q_new[coord_start + 2] = r_j_new[2]
joint_q_new[coord_start + 3] = r_j_new[3]
# update joint vel
joint_qd_new[dof_start + 0] = w_j_new[0]
joint_qd_new[dof_start + 1] = w_j_new[1]
joint_qd_new[dof_start + 2] = w_j_new[2]
return
# free joint
if type == wp.sim.JOINT_FREE or type == wp.sim.JOINT_DISTANCE:
# dofs: qd = (omega_x, omega_y, omega_z, vel_x, vel_y, vel_z)
# coords: q = (trans_x, trans_y, trans_z, quat_x, quat_y, quat_z, quat_w)
# angular and linear acceleration
m_s = wp.vec3(joint_qdd[dof_start + 0], joint_qdd[dof_start + 1], joint_qdd[dof_start + 2])
a_s = wp.vec3(joint_qdd[dof_start + 3], joint_qdd[dof_start + 4], joint_qdd[dof_start + 5])
# angular and linear velocity
w_s = wp.vec3(joint_qd[dof_start + 0], joint_qd[dof_start + 1], joint_qd[dof_start + 2])
v_s = wp.vec3(joint_qd[dof_start + 3], joint_qd[dof_start + 4], joint_qd[dof_start + 5])
# symplectic Euler
w_s = w_s + m_s * dt
v_s = v_s + a_s * dt
# translation of origin
p_s = wp.vec3(joint_q[coord_start + 0], joint_q[coord_start + 1], joint_q[coord_start + 2])
# linear vel of origin (note q/qd switch order of linear angular elements)
# note we are converting the body twist in the space frame (w_s, v_s) to compute center of mass velcity
dpdt_s = v_s + wp.cross(w_s, p_s)
# quat and quat derivative
r_s = wp.quat(
joint_q[coord_start + 3], joint_q[coord_start + 4], joint_q[coord_start + 5], joint_q[coord_start + 6]
)
drdt_s = wp.quat(w_s, 0.0) * r_s * 0.5
# new orientation (normalized)
p_s_new = p_s + dpdt_s * dt
r_s_new = wp.normalize(r_s + drdt_s * dt)
# update transform
joint_q_new[coord_start + 0] = p_s_new[0]
joint_q_new[coord_start + 1] = p_s_new[1]
joint_q_new[coord_start + 2] = p_s_new[2]
joint_q_new[coord_start + 3] = r_s_new[0]
joint_q_new[coord_start + 4] = r_s_new[1]
joint_q_new[coord_start + 5] = r_s_new[2]
joint_q_new[coord_start + 6] = r_s_new[3]
# update joint_twist
joint_qd_new[dof_start + 0] = w_s[0]
joint_qd_new[dof_start + 1] = w_s[1]
joint_qd_new[dof_start + 2] = w_s[2]
joint_qd_new[dof_start + 3] = v_s[0]
joint_qd_new[dof_start + 4] = v_s[1]
joint_qd_new[dof_start + 5] = v_s[2]
return
# other joint types (compound, universal, D6)
if type == wp.sim.JOINT_COMPOUND or type == wp.sim.JOINT_UNIVERSAL or type == wp.sim.JOINT_D6:
axis_count = lin_axis_count + ang_axis_count
for i in range(axis_count):
qdd = joint_qdd[dof_start + i]
qd = joint_qd[dof_start + i]
q = joint_q[coord_start + i]
qd_new = qd + qdd * dt
q_new = q + qd_new * dt
joint_qd_new[dof_start + i] = qd_new
joint_q_new[coord_start + i] = q_new
return
@wp.func
def compute_link_transform(
i: int,
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_q_start: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
body_X_com: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
# outputs
body_q: wp.array(dtype=wp.transform),
body_q_com: wp.array(dtype=wp.transform),
):
# parent transform
parent = joint_parent[i]
child = joint_child[i]
# parent transform in spatial coordinates
X_pj = joint_X_p[i]
X_cj = joint_X_c[i]
# parent anchor frame in world space
X_wpj = X_pj
if parent >= 0:
X_wp = body_q[parent]
X_wpj = X_wp * X_wpj
type = joint_type[i]
axis_start = joint_axis_start[i]
lin_axis_count = joint_axis_dim[i, 0]
ang_axis_count = joint_axis_dim[i, 1]
coord_start = joint_q_start[i]
# compute transform across joint
X_j = jcalc_transform(type, joint_axis, axis_start, lin_axis_count, ang_axis_count, joint_q, coord_start)
# transform from world to joint anchor frame at child body
X_wcj = X_wpj * X_j
# transform from world to child body frame
X_wc = X_wcj * wp.transform_inverse(X_cj)
# compute transform of center of mass
X_cm = body_X_com[child]
X_sm = X_wc * X_cm
# store geometry transforms
body_q[child] = X_wc
body_q_com[child] = X_sm
@wp.kernel
def eval_rigid_fk(
articulation_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_q_start: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
body_X_com: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
# outputs
body_q: wp.array(dtype=wp.transform),
body_q_com: wp.array(dtype=wp.transform),
):
# one thread per-articulation
index = wp.tid()
start = articulation_start[index]
end = articulation_start[index + 1]
for i in range(start, end):
compute_link_transform(
i,
joint_type,
joint_parent,
joint_child,
joint_q_start,
joint_q,
joint_X_p,
joint_X_c,
body_X_com,
joint_axis,
joint_axis_start,
joint_axis_dim,
body_q,
body_q_com,
)
@wp.func
def spatial_cross(a: wp.spatial_vector, b: wp.spatial_vector):
w_a = wp.spatial_top(a)
v_a = wp.spatial_bottom(a)
w_b = wp.spatial_top(b)
v_b = wp.spatial_bottom(b)
w = wp.cross(w_a, w_b)
v = wp.cross(w_a, v_b) + wp.cross(v_a, w_b)
return wp.spatial_vector(w, v)
@wp.func
def spatial_cross_dual(a: wp.spatial_vector, b: wp.spatial_vector):
w_a = wp.spatial_top(a)
v_a = wp.spatial_bottom(a)
w_b = wp.spatial_top(b)
v_b = wp.spatial_bottom(b)
w = wp.cross(w_a, w_b) + wp.cross(v_a, v_b)
v = wp.cross(w_a, v_b)
return wp.spatial_vector(w, v)
@wp.func
def dense_index(stride: int, i: int, j: int):
return i * stride + j
@wp.func
def compute_link_velocity(
i: int,
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
body_I_m: wp.array(dtype=wp.spatial_matrix),
body_q: wp.array(dtype=wp.transform),
body_q_com: wp.array(dtype=wp.transform),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
gravity: wp.vec3,
# outputs
joint_S_s: wp.array(dtype=wp.spatial_vector),
body_I_s: wp.array(dtype=wp.spatial_matrix),
body_v_s: wp.array(dtype=wp.spatial_vector),
body_f_s: wp.array(dtype=wp.spatial_vector),
body_a_s: wp.array(dtype=wp.spatial_vector),
):
type = joint_type[i]
child = joint_child[i]
parent = joint_parent[i]
q_start = joint_q_start[i]
qd_start = joint_qd_start[i]
X_pj = joint_X_p[i]
# X_cj = joint_X_c[i]
# parent anchor frame in world space
X_wpj = X_pj
if parent >= 0:
X_wp = body_q[parent]
X_wpj = X_wp * X_wpj
# compute motion subspace and velocity across the joint (also stores S_s to global memory)
axis_start = joint_axis_start[i]
lin_axis_count = joint_axis_dim[i, 0]
ang_axis_count = joint_axis_dim[i, 1]
v_j_s = jcalc_motion(
type,
joint_axis,
axis_start,
lin_axis_count,
ang_axis_count,
X_wpj,
joint_q,
joint_qd,
q_start,
qd_start,
joint_S_s,
)
# parent velocity
v_parent_s = wp.spatial_vector()
a_parent_s = wp.spatial_vector()
if parent >= 0:
v_parent_s = body_v_s[parent]
a_parent_s = body_a_s[parent]
# body velocity, acceleration
v_s = v_parent_s + v_j_s
a_s = a_parent_s + spatial_cross(v_s, v_j_s) # + joint_S_s[i]*self.joint_qdd[i]
# compute body forces
X_sm = body_q_com[child]
I_m = body_I_m[child]
# gravity and external forces (expressed in frame aligned with s but centered at body mass)
m = I_m[3, 3]
f_g = m * gravity
r_com = wp.transform_get_translation(X_sm)
f_g_s = wp.spatial_vector(wp.cross(r_com, f_g), f_g)
# body forces
I_s = spatial_transform_inertia(X_sm, I_m)
f_b_s = I_s * a_s + spatial_cross_dual(v_s, I_s * v_s)
body_v_s[child] = v_s
body_a_s[child] = a_s
body_f_s[child] = f_b_s - f_g_s
body_I_s[child] = I_s
# Inverse dynamics via Recursive Newton-Euler algorithm (Featherstone Table 5.1)
@wp.kernel
def eval_rigid_id(
articulation_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
body_I_m: wp.array(dtype=wp.spatial_matrix),
body_q: wp.array(dtype=wp.transform),
body_q_com: wp.array(dtype=wp.transform),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
gravity: wp.vec3,
# outputs
joint_S_s: wp.array(dtype=wp.spatial_vector),
body_I_s: wp.array(dtype=wp.spatial_matrix),
body_v_s: wp.array(dtype=wp.spatial_vector),
body_f_s: wp.array(dtype=wp.spatial_vector),
body_a_s: wp.array(dtype=wp.spatial_vector),
):
# one thread per-articulation
index = wp.tid()
start = articulation_start[index]
end = articulation_start[index + 1]
# compute link velocities and coriolis forces
for i in range(start, end):
compute_link_velocity(
i,
joint_type,
joint_parent,
joint_child,
joint_q_start,
joint_qd_start,
joint_q,
joint_qd,
joint_axis,
joint_axis_start,
joint_axis_dim,
body_I_m,
body_q,
body_q_com,
joint_X_p,
joint_X_c,
gravity,
joint_S_s,
body_I_s,
body_v_s,
body_f_s,
body_a_s,
)
@wp.kernel
def eval_rigid_tau(
articulation_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis_mode: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_act: wp.array(dtype=float),
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
joint_limit_ke: wp.array(dtype=float),
joint_limit_kd: wp.array(dtype=float),
joint_S_s: wp.array(dtype=wp.spatial_vector),
body_fb_s: wp.array(dtype=wp.spatial_vector),
body_f_ext: wp.array(dtype=wp.spatial_vector),
# outputs
body_ft_s: wp.array(dtype=wp.spatial_vector),
tau: wp.array(dtype=float),
):
# one thread per-articulation
index = wp.tid()
start = articulation_start[index]
end = articulation_start[index + 1]
count = end - start
# compute joint forces
for offset in range(count):
# for backwards traversal
i = end - offset - 1
type = joint_type[i]
parent = joint_parent[i]
child = joint_child[i]
dof_start = joint_qd_start[i]
coord_start = joint_q_start[i]
axis_start = joint_axis_start[i]
lin_axis_count = joint_axis_dim[i, 0]
ang_axis_count = joint_axis_dim[i, 1]
# total forces on body
f_b_s = body_fb_s[child]
f_t_s = body_ft_s[child]
f_ext = body_f_ext[child]
f_s = f_b_s + f_t_s + f_ext
# compute joint-space forces, writes out tau
jcalc_tau(
type,
joint_target_ke,
joint_target_kd,
joint_limit_ke,
joint_limit_kd,
joint_S_s,
joint_q,
joint_qd,
joint_act,
joint_axis_mode,
joint_limit_lower,
joint_limit_upper,
coord_start,
dof_start,
axis_start,
lin_axis_count,
ang_axis_count,
f_s,
tau,
)
# update parent forces, todo: check that this is valid for the backwards pass
if parent >= 0:
wp.atomic_add(body_ft_s, parent, f_s)
# builds spatial Jacobian J which is an (joint_count*6)x(dof_count) matrix
@wp.kernel
def eval_rigid_jacobian(
articulation_start: wp.array(dtype=int),
articulation_J_start: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_S_s: wp.array(dtype=wp.spatial_vector),
# outputs
J: wp.array(dtype=float),
):
# one thread per-articulation
index = wp.tid()
joint_start = articulation_start[index]
joint_end = articulation_start[index + 1]
joint_count = joint_end - joint_start
J_offset = articulation_J_start[index]
articulation_dof_start = joint_qd_start[joint_start]
articulation_dof_end = joint_qd_start[joint_end]
articulation_dof_count = articulation_dof_end - articulation_dof_start
for i in range(joint_count):
row_start = i * 6
j = joint_start + i
while j != -1:
joint_dof_start = joint_qd_start[j]
joint_dof_end = joint_qd_start[j + 1]
joint_dof_count = joint_dof_end - joint_dof_start
# fill out each row of the Jacobian walking up the tree
for dof in range(joint_dof_count):
col = (joint_dof_start - articulation_dof_start) + dof
S = joint_S_s[joint_dof_start + dof]
for k in range(6):
J[J_offset + dense_index(articulation_dof_count, row_start + k, col)] = S[k]
j = joint_parent[j]
@wp.func
def spatial_mass(
body_I_s: wp.array(dtype=wp.spatial_matrix),
joint_start: int,
joint_count: int,
M_start: int,
# outputs
M: wp.array(dtype=float),
):
stride = joint_count * 6
for l in range(joint_count):
I = body_I_s[joint_start + l]
for i in range(6):
for j in range(6):
M[M_start + dense_index(stride, l * 6 + i, l * 6 + j)] = I[i, j]
@wp.kernel
def eval_rigid_mass(
articulation_start: wp.array(dtype=int),
articulation_M_start: wp.array(dtype=int),
body_I_s: wp.array(dtype=wp.spatial_matrix),
# outputs
M: wp.array(dtype=float),
):
# one thread per-articulation
index = wp.tid()
joint_start = articulation_start[index]
joint_end = articulation_start[index + 1]
joint_count = joint_end - joint_start
M_offset = articulation_M_start[index]
spatial_mass(body_I_s, joint_start, joint_count, M_offset, M)
@wp.func
def dense_gemm(
m: int,
n: int,
p: int,
transpose_A: bool,
transpose_B: bool,
add_to_C: bool,
A_start: int,
B_start: int,
C_start: int,
A: wp.array(dtype=float),
B: wp.array(dtype=float),
# outputs
C: wp.array(dtype=float),
):
# multiply a `m x p` matrix A by a `p x n` matrix B to produce a `m x n` matrix C
for i in range(m):
for j in range(n):
sum = float(0.0)
for k in range(p):
if transpose_A:
a_i = k * m + i
else:
a_i = i * p + k
if transpose_B:
b_j = j * p + k
else:
b_j = k * n + j
sum += A[A_start + a_i] * B[B_start + b_j]
if add_to_C:
C[C_start + i * n + j] += sum
else:
C[C_start + i * n + j] = sum
# @wp.func_grad(dense_gemm)
# def adj_dense_gemm(
# m: int,
# n: int,
# p: int,
# transpose_A: bool,
# transpose_B: bool,
# add_to_C: bool,
# A_start: int,
# B_start: int,
# C_start: int,
# A: wp.array(dtype=float),
# B: wp.array(dtype=float),
# # outputs
# C: wp.array(dtype=float),
# ):
# add_to_C = True
# if transpose_A:
# dense_gemm(p, m, n, False, True, add_to_C, A_start, B_start, C_start, B, wp.adjoint[C], wp.adjoint[A])
# dense_gemm(p, n, m, False, False, add_to_C, A_start, B_start, C_start, A, wp.adjoint[C], wp.adjoint[B])
# else:
# dense_gemm(
# m, p, n, False, not transpose_B, add_to_C, A_start, B_start, C_start, wp.adjoint[C], B, wp.adjoint[A]
# )
# dense_gemm(p, n, m, True, False, add_to_C, A_start, B_start, C_start, A, wp.adjoint[C], wp.adjoint[B])
@wp.kernel
def eval_dense_gemm_batched(
m: wp.array(dtype=int),
n: wp.array(dtype=int),
p: wp.array(dtype=int),
transpose_A: bool,
transpose_B: bool,
A_start: wp.array(dtype=int),
B_start: wp.array(dtype=int),
C_start: wp.array(dtype=int),
A: wp.array(dtype=float),
B: wp.array(dtype=float),
C: wp.array(dtype=float),
):
# on the CPU each thread computes the whole matrix multiply
# on the GPU each block computes the multiply with one output per-thread
batch = wp.tid() # /kNumThreadsPerBlock;
add_to_C = False
dense_gemm(
m[batch],
n[batch],
p[batch],
transpose_A,
transpose_B,
add_to_C,
A_start[batch],
B_start[batch],
C_start[batch],
A,
B,
C,
)
@wp.func
def dense_cholesky(
n: int,
A: wp.array(dtype=float),
R: wp.array(dtype=float),
A_start: int,
R_start: int,
# outputs
L: wp.array(dtype=float),
):
# compute the Cholesky factorization of A = L L^T with diagonal regularization R
for j in range(n):
s = A[A_start + dense_index(n, j, j)] + R[R_start + j]
for k in range(j):
r = L[A_start + dense_index(n, j, k)]
s -= r * r
s = wp.sqrt(s)
invS = 1.0 / s
L[A_start + dense_index(n, j, j)] = s
for i in range(j + 1, n):
s = A[A_start + dense_index(n, i, j)]
for k in range(j):
s -= L[A_start + dense_index(n, i, k)] * L[A_start + dense_index(n, j, k)]
L[A_start + dense_index(n, i, j)] = s * invS
@wp.func_grad(dense_cholesky)
def adj_dense_cholesky(
n: int,
A: wp.array(dtype=float),
R: wp.array(dtype=float),
A_start: int,
R_start: int,
# outputs
L: wp.array(dtype=float),
):
# nop, use dense_solve to differentiate through (A^-1)b = x
pass
@wp.kernel
def eval_dense_cholesky_batched(
A_starts: wp.array(dtype=int),
A_dim: wp.array(dtype=int),
A: wp.array(dtype=float),
R: wp.array(dtype=float),
L: wp.array(dtype=float),
):
batch = wp.tid()
n = A_dim[batch]
A_start = A_starts[batch]
R_start = n * batch
dense_cholesky(n, A, R, A_start, R_start, L)
@wp.func
def dense_subs(
n: int,
L_start: int,
b_start: int,
L: wp.array(dtype=float),
b: wp.array(dtype=float),
# outputs
x: wp.array(dtype=float),
):
# Solves (L L^T) x = b for x given the Cholesky factor L
# forward substitution solves the lower triangular system L y = b for y
for i in range(n):
s = b[b_start + i]
for j in range(i):
s -= L[L_start + dense_index(n, i, j)] * x[b_start + j]
x[b_start + i] = s / L[L_start + dense_index(n, i, i)]
# backward substitution solves the upper triangular system L^T x = y for x
for i in range(n - 1, -1, -1):
s = x[b_start + i]
for j in range(i + 1, n):
s -= L[L_start + dense_index(n, j, i)] * x[b_start + j]
x[b_start + i] = s / L[L_start + dense_index(n, i, i)]
@wp.func
def dense_solve(
n: int,
L_start: int,
b_start: int,
L: wp.array(dtype=float),
b: wp.array(dtype=float),
# outputs
x: wp.array(dtype=float),
tmp: wp.array(dtype=float),
):
# helper function to include tmp argument for backward pass
dense_subs(n, L_start, b_start, L, b, x)
@wp.func_grad(dense_solve)
def adj_dense_solve(
n: int,
L_start: int,
b_start: int,
L: wp.array(dtype=float),
b: wp.array(dtype=float),
# outputs
x: wp.array(dtype=float),
tmp: wp.array(dtype=float),
):
if not tmp or not wp.adjoint[x] or not wp.adjoint[L]:
return
for i in range(n):
tmp[b_start + i] = 0.0
dense_subs(n, L_start, b_start, L, wp.adjoint[x], tmp)
for i in range(n):
wp.adjoint[b][b_start + i] += tmp[b_start + i]
# A* = -adj_b*x^T
for i in range(n):
for j in range(n):
wp.adjoint[L][L_start + dense_index(n, i, j)] += -tmp[b_start + i] * x[b_start + j]
@wp.kernel
def eval_dense_solve_batched(
L_start: wp.array(dtype=int),
L_dim: wp.array(dtype=int),
b_start: wp.array(dtype=int),
L: wp.array(dtype=float),
b: wp.array(dtype=float),
# outputs
x: wp.array(dtype=float),
tmp: wp.array(dtype=float),
):
batch = wp.tid()
dense_solve(L_dim[batch], L_start[batch], b_start[batch], L, b, x, tmp)
@wp.kernel
def integrate_generalized_joints(
joint_type: wp.array(dtype=int),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_qdd: wp.array(dtype=float),
dt: float,
# outputs
joint_q_new: wp.array(dtype=float),
joint_qd_new: wp.array(dtype=float),
):
# one thread per-articulation
index = wp.tid()
type = joint_type[index]
coord_start = joint_q_start[index]
dof_start = joint_qd_start[index]
lin_axis_count = joint_axis_dim[index, 0]
ang_axis_count = joint_axis_dim[index, 1]
jcalc_integrate(
type,
joint_q,
joint_qd,
joint_qdd,
coord_start,
dof_start,
lin_axis_count,
ang_axis_count,
dt,
joint_q_new,
joint_qd_new,
)
class FeatherstoneIntegrator(Integrator):
"""A semi-implicit integrator using symplectic Euler that operates
on reduced (also called generalized) coordinates to simulate articulated rigid body dynamics
based on Featherstone's composite rigid body algorithm (CRBA).
See: Featherstone, Roy. Rigid Body Dynamics Algorithms. Springer US, 2014.
Instead of maximal coordinates :attr:`State.body_q` (rigid body positions) and :attr:`State.body_qd`
(rigid body velocities) as is the case :class:`SemiImplicitIntegrator`, :class:`FeatherstoneIntegrator`
uses :attr:`State.joint_q` and :attr:`State.joint_qd` to represent the positions and velocities of
joints without allowing any redundant degrees of freedom.
After constructing :class:`Model` and :class:`State` objects this time-integrator
may be used to advance the simulation state forward in time.
Note:
Unlike :class:`SemiImplicitIntegrator` and :class:`XPBDIntegrator`, :class:`FeatherstoneIntegrator` does not simulate rigid bodies with nonzero mass as floating bodies if they are not connected through any joints. Floating-base systems require an explicit free joint with which the body is connected to the world, see :meth:`ModelBuilder.add_joint_free`.
Semi-implicit time integration is a variational integrator that
preserves energy, however it not unconditionally stable, and requires a time-step
small enough to support the required stiffness and damping forces.
See: https://en.wikipedia.org/wiki/Semi-implicit_Euler_method
Example
-------
.. code-block:: python
integrator = wp.FeatherstoneIntegrator(model)
# simulation loop
for i in range(100):
state = integrator.simulate(model, state_in, state_out, dt)
Note:
The :class:`FeatherstoneIntegrator` requires the :class:`Model` to be passed in as a constructor argument.
"""
def __init__(self, model, angular_damping=0.05, update_mass_matrix_every=1):
"""
Args:
model (Model): the model to be simulated.
angular_damping (float, optional): Angular damping factor. Defaults to 0.05.
update_mass_matrix_every (int, optional): How often to update the mass matrix (every n-th time the :meth:`simulate` function gets called). Defaults to 1.
"""
self.angular_damping = angular_damping
self.update_mass_matrix_every = update_mass_matrix_every
self.compute_articulation_indices(model)
self.allocate_model_aux_vars(model)
self._step = 0
def compute_articulation_indices(self, model):
# calculate total size and offsets of Jacobian and mass matrices for entire system
if model.joint_count:
self.J_size = 0
self.M_size = 0
self.H_size = 0
articulation_J_start = []
articulation_M_start = []
articulation_H_start = []
articulation_M_rows = []
articulation_H_rows = []
articulation_J_rows = []
articulation_J_cols = []
articulation_dof_start = []
articulation_coord_start = []
articulation_start = model.articulation_start.numpy()
joint_q_start = model.joint_q_start.numpy()
joint_qd_start = model.joint_qd_start.numpy()
for i in range(model.articulation_count):
first_joint = articulation_start[i]
last_joint = articulation_start[i + 1]
first_coord = joint_q_start[first_joint]
first_dof = joint_qd_start[first_joint]
last_dof = joint_qd_start[last_joint]
joint_count = last_joint - first_joint
dof_count = last_dof - first_dof
articulation_J_start.append(self.J_size)
articulation_M_start.append(self.M_size)
articulation_H_start.append(self.H_size)
articulation_dof_start.append(first_dof)
articulation_coord_start.append(first_coord)
# bit of data duplication here, but will leave it as such for clarity
articulation_M_rows.append(joint_count * 6)
articulation_H_rows.append(dof_count)
articulation_J_rows.append(joint_count * 6)
articulation_J_cols.append(dof_count)
self.J_size += 6 * joint_count * dof_count
self.M_size += 6 * joint_count * 6 * joint_count
self.H_size += dof_count * dof_count
# matrix offsets for batched gemm
self.articulation_J_start = wp.array(articulation_J_start, dtype=wp.int32, device=model.device)
self.articulation_M_start = wp.array(articulation_M_start, dtype=wp.int32, device=model.device)
self.articulation_H_start = wp.array(articulation_H_start, dtype=wp.int32, device=model.device)
self.articulation_M_rows = wp.array(articulation_M_rows, dtype=wp.int32, device=model.device)
self.articulation_H_rows = wp.array(articulation_H_rows, dtype=wp.int32, device=model.device)
self.articulation_J_rows = wp.array(articulation_J_rows, dtype=wp.int32, device=model.device)
self.articulation_J_cols = wp.array(articulation_J_cols, dtype=wp.int32, device=model.device)
self.articulation_dof_start = wp.array(articulation_dof_start, dtype=wp.int32, device=model.device)
self.articulation_coord_start = wp.array(articulation_coord_start, dtype=wp.int32, device=model.device)
def allocate_model_aux_vars(self, model):
# allocate mass, Jacobian matrices, and other auxiliary variables pertaining to the model
if model.joint_count:
# system matrices
self.M = wp.zeros((self.M_size,), dtype=wp.float32, device=model.device, requires_grad=model.requires_grad)
self.J = wp.zeros((self.J_size,), dtype=wp.float32, device=model.device, requires_grad=model.requires_grad)
self.P = wp.empty_like(self.J, requires_grad=model.requires_grad)
self.H = wp.empty((self.H_size,), dtype=wp.float32, device=model.device, requires_grad=model.requires_grad)
# zero since only upper triangle is set which can trigger NaN detection
self.L = wp.zeros_like(self.H)
if model.body_count:
# TODO use requires_grad here?
self.body_I_m = wp.empty(
(model.body_count,), dtype=wp.spatial_matrix, device=model.device, requires_grad=model.requires_grad
)
wp.launch(
compute_spatial_inertia,
model.body_count,
inputs=[model.body_inertia, model.body_mass],
outputs=[self.body_I_m],
device=model.device,
)
self.body_X_com = wp.empty(
(model.body_count,), dtype=wp.transform, device=model.device, requires_grad=model.requires_grad
)
wp.launch(
compute_com_transforms,
model.body_count,
inputs=[model.body_com],
outputs=[self.body_X_com],
device=model.device,
)
def allocate_state_aux_vars(self, model, target, requires_grad):
# allocate auxiliary variables that vary with state
if model.body_count:
# joints
target.joint_qdd = wp.zeros_like(model.joint_qd, requires_grad=requires_grad)
target.joint_tau = wp.empty_like(model.joint_qd, requires_grad=requires_grad)
if requires_grad:
# used in the custom grad implementation of eval_dense_solve_batched
target.joint_solve_tmp = wp.zeros_like(model.joint_qd, requires_grad=True)
else:
target.joint_solve_tmp = None
target.joint_S_s = wp.empty(
(model.joint_dof_count,),
dtype=wp.spatial_vector,
device=model.device,
requires_grad=requires_grad,
)
# derived rigid body data (maximal coordinates)
target.body_q_com = wp.empty_like(model.body_q, requires_grad=requires_grad)
target.body_I_s = wp.empty(
(model.body_count,), dtype=wp.spatial_matrix, device=model.device, requires_grad=requires_grad
)
target.body_v_s = wp.empty(
(model.body_count,), dtype=wp.spatial_vector, device=model.device, requires_grad=requires_grad
)
target.body_a_s = wp.empty(
(model.body_count,), dtype=wp.spatial_vector, device=model.device, requires_grad=requires_grad
)
target.body_f_s = wp.zeros(
(model.body_count,), dtype=wp.spatial_vector, device=model.device, requires_grad=requires_grad
)
target.body_ft_s = wp.zeros(
(model.body_count,), dtype=wp.spatial_vector, device=model.device, requires_grad=requires_grad
)
target._featherstone_augmented = True
def simulate(self, model: Model, state_in: State, state_out: State, dt: float, control: Control = None):
requires_grad = state_in.requires_grad
# optionally create dynamical auxiliary variables
if requires_grad:
state_aug = state_out
else:
state_aug = self
if not getattr(state_aug, "_featherstone_augmented", False):
self.allocate_state_aux_vars(model, state_aug, requires_grad)
if control is None:
control = model.control(clone_variables=False)
with wp.ScopedTimer("simulate", False):
particle_f = None
body_f = None
if state_in.particle_count:
particle_f = state_in.particle_f
if state_in.body_count:
body_f = state_in.body_f
# damped springs
eval_spring_forces(model, state_in, particle_f)
# triangle elastic and lift/drag forces
eval_triangle_forces(model, state_in, control, particle_f)
# triangle/triangle contacts
eval_triangle_contact_forces(model, state_in, particle_f)
# triangle bending
eval_bending_forces(model, state_in, particle_f)
# tetrahedral FEM
eval_tetrahedral_forces(model, state_in, control, particle_f)
# particle-particle interactions
eval_particle_forces(model, state_in, particle_f)
# particle ground contacts
eval_particle_ground_contact_forces(model, state_in, particle_f)
# particle shape contact
eval_particle_body_contact_forces(model, state_in, particle_f, body_f)
# muscles
if False:
eval_muscle_forces(model, state_in, control, body_f)
# ----------------------------
# articulations
if model.joint_count:
# evaluate body transforms
wp.launch(
eval_rigid_fk,
dim=model.articulation_count,
inputs=[
model.articulation_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_q_start,
state_in.joint_q,
model.joint_X_p,
model.joint_X_c,
self.body_X_com,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
],
outputs=[state_in.body_q, state_aug.body_q_com],
device=model.device,
)
# print("body_X_sc:")
# print(state_in.body_q.numpy())
# evaluate joint inertias, motion vectors, and forces
state_aug.body_f_s.zero_()
wp.launch(
eval_rigid_id,
dim=model.articulation_count,
inputs=[
model.articulation_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_q_start,
model.joint_qd_start,
state_in.joint_q,
state_in.joint_qd,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
self.body_I_m,
state_in.body_q,
state_aug.body_q_com,
model.joint_X_p,
model.joint_X_c,
model.gravity,
],
outputs=[
state_aug.joint_S_s,
state_aug.body_I_s,
state_aug.body_v_s,
state_aug.body_f_s,
state_aug.body_a_s,
],
device=model.device,
)
if model.rigid_contact_max and (
model.ground and model.shape_ground_contact_pair_count or model.shape_contact_pair_count
):
wp.launch(
kernel=eval_rigid_contacts,
dim=model.rigid_contact_max,
inputs=[
state_in.body_q,
state_aug.body_v_s,
model.body_com,
model.shape_materials,
model.shape_geo,
model.shape_body,
model.rigid_contact_count,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_normal,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
True,
],
outputs=[body_f],
device=model.device,
)
# if model.rigid_contact_count.numpy()[0] > 0:
# print(body_f.numpy())
if model.articulation_count:
# evaluate joint torques
state_aug.body_ft_s.zero_()
wp.launch(
eval_rigid_tau,
dim=model.articulation_count,
inputs=[
model.articulation_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_q_start,
model.joint_qd_start,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_axis_mode,
state_in.joint_q,
state_in.joint_qd,
control.joint_act,
model.joint_target_ke,
model.joint_target_kd,
model.joint_limit_lower,
model.joint_limit_upper,
model.joint_limit_ke,
model.joint_limit_kd,
state_aug.joint_S_s,
state_aug.body_f_s,
body_f,
],
outputs=[
state_aug.body_ft_s,
state_aug.joint_tau,
],
device=model.device,
)
# print("joint_tau:")
# print(state_aug.joint_tau.numpy())
# print("body_q:")
# print(state_in.body_q.numpy())
# print("body_qd:")
# print(state_in.body_qd.numpy())
if self._step % self.update_mass_matrix_every == 0:
# build J
wp.launch(
eval_rigid_jacobian,
dim=model.articulation_count,
inputs=[
model.articulation_start,
self.articulation_J_start,
model.joint_parent,
model.joint_qd_start,
state_aug.joint_S_s,
],
outputs=[self.J],
device=model.device,
)
# build M
wp.launch(
eval_rigid_mass,
dim=model.articulation_count,
inputs=[
model.articulation_start,
self.articulation_M_start,
state_aug.body_I_s,
],
outputs=[self.M],
device=model.device,
)
# form P = M*J
wp.launch(
eval_dense_gemm_batched,
dim=model.articulation_count,
inputs=[
self.articulation_M_rows,
self.articulation_J_cols,
self.articulation_J_rows,
False,
False,
self.articulation_M_start,
self.articulation_J_start,
# P start is the same as J start since it has the same dims as J
self.articulation_J_start,
self.M,
self.J,
],
outputs=[self.P],
device=model.device,
)
# form H = J^T*P
wp.launch(
eval_dense_gemm_batched,
dim=model.articulation_count,
inputs=[
self.articulation_J_cols,
self.articulation_J_cols,
# P rows is the same as J rows
self.articulation_J_rows,
True,
False,
self.articulation_J_start,
# P start is the same as J start since it has the same dims as J
self.articulation_J_start,
self.articulation_H_start,
self.J,
self.P,
],
outputs=[self.H],
device=model.device,
)
# compute decomposition
wp.launch(
eval_dense_cholesky_batched,
dim=model.articulation_count,
inputs=[
self.articulation_H_start,
self.articulation_H_rows,
self.H,
model.joint_armature,
],
outputs=[self.L],
device=model.device,
)
# print("joint_act:")
# print(control.joint_act.numpy())
# print("joint_tau:")
# print(state_aug.joint_tau.numpy())
# print("H:")
# print(self.H.numpy())
# print("L:")
# print(self.L.numpy())
# solve for qdd
state_aug.joint_qdd.zero_()
wp.launch(
eval_dense_solve_batched,
dim=model.articulation_count,
inputs=[
self.articulation_H_start,
self.articulation_H_rows,
self.articulation_dof_start,
self.L,
state_aug.joint_tau,
],
outputs=[
state_aug.joint_qdd,
state_aug.joint_solve_tmp,
],
device=model.device,
)
# if wp.context.runtime.tape:
# wp.context.runtime.tape.record_func(
# backward=lambda: adj_matmul(
# a, b, c, a.grad, b.grad, c.grad, d.grad, alpha, beta, allow_tf32x3_arith, device
# ),
# arrays=[a, b, c, d],
# )
# print("joint_qdd:")
# print(state_aug.joint_qdd.numpy())
# print("\n\n")
# -------------------------------------
# integrate bodies
if model.joint_count:
wp.launch(
kernel=integrate_generalized_joints,
dim=model.joint_count,
inputs=[
model.joint_type,
model.joint_q_start,
model.joint_qd_start,
model.joint_axis_dim,
state_in.joint_q,
state_in.joint_qd,
state_aug.joint_qdd,
dt,
],
outputs=[state_out.joint_q, state_out.joint_qd],
device=model.device,
)
# update maximal coordinates
eval_fk(model, state_out.joint_q, state_out.joint_qd, None, state_out)
self.integrate_particles(model, state_in, state_out, dt)
self._step += 1
return state_out
| 64,584 | Python | 32.796442 | 362 | 0.522033 |
NVIDIA/warp/warp/sim/import_snu.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
import xml.etree.ElementTree as ET
import numpy as np
import warp as wp
# SNU file format parser
class MuscleUnit:
def __init__(self):
self.name = ""
self.bones = []
self.points = []
class Skeleton:
def __init__(self, root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0):
self.parse_skeleton(skeleton_file, builder, filter, root_xform, armature)
self.parse_muscles(muscle_file, builder)
def parse_skeleton(self, filename, builder, filter, root_xform, armature):
file = ET.parse(filename)
root = file.getroot()
self.node_map = {} # map node names to link indices
self.xform_map = {} # map node names to parent transforms
self.mesh_map = {} # map mesh names to link indices objects
self.coord_start = builder.joint_coord_count
self.dof_start = builder.joint_dof_count
type_map = {
"Ball": wp.sim.JOINT_BALL,
"Revolute": wp.sim.JOINT_REVOLUTE,
"Prismatic": wp.sim.JOINT_PRISMATIC,
"Free": wp.sim.JOINT_FREE,
"Fixed": wp.sim.JOINT_FIXED,
}
builder.add_articulation()
for child in root:
if child.tag == "Node":
body = child.find("Body")
joint = child.find("Joint")
name = child.attrib["name"]
parent = child.attrib["parent"]
parent_X_s = wp.transform_identity()
if parent in self.node_map:
parent_link = self.node_map[parent]
parent_X_s = self.xform_map[parent]
else:
parent_link = -1
body_xform = body.find("Transformation")
joint_xform = joint.find("Transformation")
body_mesh = body.attrib["obj"]
body_size = np.fromstring(body.attrib["size"], sep=" ")
# body_type = body.attrib["type"]
# body_mass = body.attrib["mass"]
body_R_s = np.fromstring(body_xform.attrib["linear"], sep=" ").reshape((3, 3))
body_t_s = np.fromstring(body_xform.attrib["translation"], sep=" ")
joint_R_s = np.fromstring(joint_xform.attrib["linear"], sep=" ").reshape((3, 3))
joint_t_s = np.fromstring(joint_xform.attrib["translation"], sep=" ")
joint_type = type_map[joint.attrib["type"]]
joint_lower = np.array([-1.0e3])
joint_upper = np.array([1.0e3])
try:
joint_lower = np.fromstring(joint.attrib["lower"], sep=" ")
joint_upper = np.fromstring(joint.attrib["upper"], sep=" ")
except Exception:
pass
if "axis" in joint.attrib:
joint_axis = np.fromstring(joint.attrib["axis"], sep=" ")
else:
joint_axis = np.array((0.0, 0.0, 0.0))
body_X_s = wp.transform(body_t_s, wp.quat_from_matrix(body_R_s))
joint_X_s = wp.transform(joint_t_s, wp.quat_from_matrix(joint_R_s))
mesh_base = os.path.splitext(body_mesh)[0]
# mesh_file = mesh_base + ".usd"
# -----------------------------------
# one time conversion, put meshes into local body space (and meter units)
# stage = Usd.Stage.Open("./assets/snu/OBJ/" + mesh_file)
# geom = UsdGeom.Mesh.Get(stage, "/" + mesh_base + "_obj/defaultobject/defaultobject")
# body_X_bs = wp.transform_inverse(body_X_s)
# joint_X_bs = wp.transform_inverse(joint_X_s)
# points = geom.GetPointsAttr().Get()
# for i in range(len(points)):
# p = wp.transform_point(joint_X_bs, points[i]*0.01)
# points[i] = Gf.Vec3f(p.tolist()) # cm -> meters
# geom.GetPointsAttr().Set(points)
# extent = UsdGeom.Boundable.ComputeExtentFromPlugins(geom, 0.0)
# geom.GetExtentAttr().Set(extent)
# stage.Save()
# --------------------------------------
link = -1
if len(filter) == 0 or name in filter:
joint_X_p = wp.transform_multiply(wp.transform_inverse(parent_X_s), joint_X_s)
body_X_c = wp.transform_multiply(wp.transform_inverse(joint_X_s), body_X_s)
if parent_link == -1:
joint_X_p = wp.transform_identity()
# add link
link = builder.add_body(
parent=parent_link,
origin=wp.transform_multiply(root_xform, joint_X_s),
joint_xform=joint_X_p,
joint_axis=joint_axis,
joint_type=joint_type,
joint_target_ke=5.0,
joint_target_kd=2.0,
joint_limit_lower=joint_lower[0],
joint_limit_upper=joint_upper[0],
joint_limit_ke=1.0e3,
joint_limit_kd=1.0e2,
joint_armature=armature,
)
# add shape
builder.add_shape_box(
body=link,
pos=body_X_c.p,
rot=body_X_c.q,
hx=body_size[0] * 0.5,
hy=body_size[1] * 0.5,
hz=body_size[2] * 0.5,
ke=1.0e3 * 5.0,
kd=1.0e2 * 2.0,
kf=1.0e3,
mu=0.5,
)
# add lookup in name->link map
# save parent transform
self.xform_map[name] = joint_X_s
self.node_map[name] = link
self.mesh_map[mesh_base] = link
def parse_muscles(self, filename, builder):
# list of MuscleUnits
muscles = []
file = ET.parse(filename)
root = file.getroot()
self.muscle_start = len(builder.muscle_activation)
for child in root:
if child.tag == "Unit":
unit_name = child.attrib["name"]
unit_f0 = float(child.attrib["f0"])
unit_lm = float(child.attrib["lm"])
unit_lt = float(child.attrib["lt"])
unit_lmax = float(child.attrib["lmax"])
unit_pen = float(child.attrib["pen_angle"])
m = MuscleUnit()
m.name = unit_name
incomplete = False
for waypoint in child.iter("Waypoint"):
way_bone = waypoint.attrib["body"]
way_link = self.node_map[way_bone]
way_loc = np.fromstring(waypoint.attrib["p"], sep=" ", dtype=np.float32)
if way_link == -1:
incomplete = True
break
# transform loc to joint local space
joint_X_s = self.xform_map[way_bone]
way_loc = wp.transform_point(wp.transform_inverse(joint_X_s), way_loc)
m.bones.append(way_link)
m.points.append(way_loc)
if not incomplete:
muscles.append(m)
builder.add_muscle(
m.bones, m.points, f0=unit_f0, lm=unit_lm, lt=unit_lt, lmax=unit_lmax, pen=unit_pen
)
self.muscles = muscles
def parse_snu(root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0):
return Skeleton(root_xform, skeleton_file, muscle_file, builder, filter, armature=0.0)
| 8,339 | Python | 36.737556 | 107 | 0.491786 |
NVIDIA/warp/warp/sim/import_mjcf.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import math
import os
import re
import xml.etree.ElementTree as ET
import numpy as np
import warp as wp
def parse_mjcf(
mjcf_filename,
builder,
xform=None,
density=1000.0,
stiffness=0.0,
damping=0.0,
contact_ke=1000.0,
contact_kd=100.0,
contact_kf=100.0,
contact_ka=0.0,
contact_mu=0.5,
contact_restitution=0.5,
contact_thickness=0.0,
limit_ke=100.0,
limit_kd=10.0,
scale=1.0,
armature=0.0,
armature_scale=1.0,
parse_meshes=True,
enable_self_collisions=False,
up_axis="Z",
ignore_classes=None,
collapse_fixed_joints=False,
):
"""
Parses MuJoCo XML (MJCF) file and adds the bodies and joints to the given ModelBuilder.
Args:
mjcf_filename (str): The filename of the MuJoCo file to parse.
builder (ModelBuilder): The :class:`ModelBuilder` to add the bodies and joints to.
xform (:ref:`transform <transform>`): The transform to apply to the imported mechanism.
density (float): The density of the shapes in kg/m^3 which will be used to calculate the body mass and inertia.
stiffness (float): The stiffness of the joints.
damping (float): The damping of the joints.
contact_ke (float): The stiffness of the shape contacts.
contact_kd (float): The damping of the shape contacts.
contact_kf (float): The friction stiffness of the shape contacts.
contact_ka (float): The adhesion distance of the shape contacts.
contact_mu (float): The friction coefficient of the shape contacts.
contact_restitution (float): The restitution coefficient of the shape contacts.
contact_thickness (float): The thickness to add to the shape geometry.
limit_ke (float): The stiffness of the joint limits.
limit_kd (float): The damping of the joint limits.
scale (float): The scaling factor to apply to the imported mechanism.
armature (float): Default joint armature to use if `armature` has not been defined for a joint in the MJCF.
armature_scale (float): Scaling factor to apply to the MJCF-defined joint armature values.
parse_meshes (bool): Whether geometries of type `"mesh"` should be parsed. If False, geometries of type `"mesh"` are ignored.
enable_self_collisions (bool): If True, self-collisions are enabled.
up_axis (str): The up axis of the mechanism. Can be either `"X"`, `"Y"` or `"Z"`. The default is `"Z"`.
ignore_classes (List[str]): A list of regular expressions. Bodies and joints with a class matching one of the regular expressions will be ignored.
collapse_fixed_joints (bool): If True, fixed joints are removed and the respective bodies are merged.
Note:
The inertia and masses of the bodies are calculated from the shape geometry and the given density. The values defined in the MJCF are not respected at the moment.
The handling of advanced features, such as MJCF classes, is still experimental.
"""
if xform is None:
xform = wp.transform()
if ignore_classes is None:
ignore_classes = []
mjcf_dirname = os.path.dirname(mjcf_filename)
file = ET.parse(mjcf_filename)
root = file.getroot()
contact_vars = {
"ke": contact_ke,
"kd": contact_kd,
"kf": contact_kf,
"ka": contact_ka,
"mu": contact_mu,
"restitution": contact_restitution,
"thickness": contact_thickness,
}
use_degrees = True # angles are in degrees by default
euler_seq = [1, 2, 3] # XYZ by default
compiler = root.find("compiler")
if compiler is not None:
use_degrees = compiler.attrib.get("angle", "degree").lower() == "degree"
euler_seq = ["xyz".index(c) + 1 for c in compiler.attrib.get("eulerseq", "xyz").lower()]
mesh_dir = compiler.attrib.get("meshdir", ".")
mesh_assets = {}
for asset in root.findall("asset"):
for mesh in asset.findall("mesh"):
if "file" in mesh.attrib:
fname = os.path.join(mesh_dir, mesh.attrib["file"])
# handle stl relative paths
if not os.path.isabs(fname):
fname = os.path.abspath(os.path.join(mjcf_dirname, fname))
if "name" in mesh.attrib:
mesh_assets[mesh.attrib["name"]] = fname
else:
name = ".".join(os.path.basename(fname).split(".")[:-1])
mesh_assets[name] = fname
class_parent = {}
class_children = {}
class_defaults = {"__all__": {}}
def get_class(element):
return element.get("class", "__all__")
def parse_default(node, parent):
nonlocal class_parent
nonlocal class_children
nonlocal class_defaults
class_name = "__all__"
if "class" in node.attrib:
class_name = node.attrib["class"]
class_parent[class_name] = parent
parent = parent or "__all__"
if parent not in class_children:
class_children[parent] = []
class_children[parent].append(class_name)
if class_name not in class_defaults:
class_defaults[class_name] = {}
for child in node:
if child.tag == "default":
parse_default(child, node.get("class"))
else:
class_defaults[class_name][child.tag] = child.attrib
for default in root.findall("default"):
parse_default(default, None)
def merge_attrib(default_attrib: dict, incoming_attrib: dict):
attrib = default_attrib.copy()
attrib.update(incoming_attrib)
return attrib
if isinstance(up_axis, str):
up_axis = "XYZ".index(up_axis.upper())
sqh = np.sqrt(0.5)
if up_axis == 0:
xform = wp.transform(xform.p, wp.quat(0.0, 0.0, -sqh, sqh) * xform.q)
elif up_axis == 2:
xform = wp.transform(xform.p, wp.quat(sqh, 0.0, 0.0, -sqh) * xform.q)
# do not apply scaling to the root transform
xform = wp.transform(np.array(xform.p) / scale, xform.q)
def parse_float(attrib, key, default):
if key in attrib:
return float(attrib[key])
else:
return default
def parse_vec(attrib, key, default):
if key in attrib:
out = np.fromstring(attrib[key], sep=" ", dtype=np.float32)
else:
out = np.array(default, dtype=np.float32)
length = len(out)
if length == 1:
return wp.vec(len(default), wp.float32)(out[0], out[0], out[0])
return wp.vec(length, wp.float32)(out)
def parse_orientation(attrib):
if "quat" in attrib:
wxyz = np.fromstring(attrib["quat"], sep=" ")
return wp.normalize(wp.quat(*wxyz[1:], wxyz[0]))
if "euler" in attrib:
euler = np.fromstring(attrib["euler"], sep=" ")
if use_degrees:
euler *= np.pi / 180
return wp.quat_from_euler(euler, *euler_seq)
if "axisangle" in attrib:
axisangle = np.fromstring(attrib["axisangle"], sep=" ")
angle = axisangle[3]
if use_degrees:
angle *= np.pi / 180
axis = wp.normalize(wp.vec3(*axisangle[:3]))
return wp.quat_from_axis_angle(axis, angle)
if "xyaxes" in attrib:
xyaxes = np.fromstring(attrib["xyaxes"], sep=" ")
xaxis = wp.normalize(wp.vec3(*xyaxes[:3]))
zaxis = wp.normalize(wp.vec3(*xyaxes[3:]))
yaxis = wp.normalize(wp.cross(zaxis, xaxis))
rot_matrix = np.array([xaxis, yaxis, zaxis]).T
return wp.quat_from_matrix(rot_matrix)
if "zaxis" in attrib:
zaxis = np.fromstring(attrib["zaxis"], sep=" ")
zaxis = wp.normalize(wp.vec3(*zaxis))
xaxis = wp.normalize(wp.cross(wp.vec3(0, 0, 1), zaxis))
yaxis = wp.normalize(wp.cross(zaxis, xaxis))
rot_matrix = np.array([xaxis, yaxis, zaxis]).T
return wp.quat_from_matrix(rot_matrix)
return wp.quat_identity()
def parse_mesh(geom):
import trimesh
faces = []
vertices = []
stl_file = mesh_assets[geom["mesh"]]
m = trimesh.load(stl_file)
for v in m.vertices:
vertices.append(np.array(v) * scale)
for f in m.faces:
faces.append(int(f[0]))
faces.append(int(f[1]))
faces.append(int(f[2]))
return wp.sim.Mesh(vertices, faces), m.scale
def parse_body(body, parent, incoming_defaults: dict):
body_class = body.get("childclass")
if body_class is None:
defaults = incoming_defaults
else:
for pattern in ignore_classes:
if re.match(pattern, body_class):
return
defaults = merge_attrib(incoming_defaults, class_defaults[body_class])
if "body" in defaults:
body_attrib = merge_attrib(defaults["body"], body.attrib)
else:
body_attrib = body.attrib
body_name = body_attrib["name"]
body_pos = parse_vec(body_attrib, "pos", (0.0, 0.0, 0.0))
body_ori = parse_orientation(body_attrib)
if parent == -1:
body_pos = wp.transform_point(xform, body_pos)
body_ori = xform.q * body_ori
body_pos *= scale
joint_armature = []
joint_name = []
joint_pos = []
linear_axes = []
angular_axes = []
joint_type = None
freejoint_tags = body.findall("freejoint")
if len(freejoint_tags) > 0:
joint_type = wp.sim.JOINT_FREE
joint_name.append(freejoint_tags[0].attrib.get("name", f"{body_name}_freejoint"))
else:
joints = body.findall("joint")
for _i, joint in enumerate(joints):
if "joint" in defaults:
joint_attrib = merge_attrib(defaults["joint"], joint.attrib)
else:
joint_attrib = joint.attrib
# default to hinge if not specified
joint_type_str = joint_attrib.get("type", "hinge")
joint_name.append(joint_attrib["name"])
joint_pos.append(parse_vec(joint_attrib, "pos", (0.0, 0.0, 0.0)) * scale)
joint_range = parse_vec(joint_attrib, "range", (-3.0, 3.0))
joint_armature.append(parse_float(joint_attrib, "armature", armature) * armature_scale)
if joint_type_str == "free":
joint_type = wp.sim.JOINT_FREE
break
if joint_type_str == "fixed":
joint_type = wp.sim.JOINT_FIXED
break
is_angular = joint_type_str == "hinge"
mode = wp.sim.JOINT_MODE_FORCE
if stiffness > 0.0 or "stiffness" in joint_attrib:
mode = wp.sim.JOINT_MODE_TARGET_POSITION
axis_vec = parse_vec(joint_attrib, "axis", (0.0, 0.0, 0.0))
ax = wp.sim.model.JointAxis(
axis=axis_vec,
limit_lower=(np.deg2rad(joint_range[0]) if is_angular and use_degrees else joint_range[0]),
limit_upper=(np.deg2rad(joint_range[1]) if is_angular and use_degrees else joint_range[1]),
target_ke=parse_float(joint_attrib, "stiffness", stiffness),
target_kd=parse_float(joint_attrib, "damping", damping),
limit_ke=limit_ke,
limit_kd=limit_kd,
mode=mode,
)
if is_angular:
angular_axes.append(ax)
else:
linear_axes.append(ax)
link = builder.add_body(
origin=wp.transform(body_pos, body_ori), # will be evaluated in fk()
armature=joint_armature[0] if len(joint_armature) > 0 else armature,
name=body_name,
)
if joint_type is None:
if len(linear_axes) == 0:
if len(angular_axes) == 0:
joint_type = wp.sim.JOINT_FIXED
elif len(angular_axes) == 1:
joint_type = wp.sim.JOINT_REVOLUTE
elif len(angular_axes) == 2:
joint_type = wp.sim.JOINT_UNIVERSAL
elif len(angular_axes) == 3:
joint_type = wp.sim.JOINT_COMPOUND
elif len(linear_axes) == 1 and len(angular_axes) == 0:
joint_type = wp.sim.JOINT_PRISMATIC
else:
joint_type = wp.sim.JOINT_D6
joint_pos = joint_pos[0] if len(joint_pos) > 0 else (0.0, 0.0, 0.0)
builder.add_joint(
joint_type,
parent,
link,
linear_axes,
angular_axes,
name="_".join(joint_name),
parent_xform=wp.transform(body_pos + joint_pos, body_ori),
child_xform=wp.transform(joint_pos, wp.quat_identity()),
armature=joint_armature[0] if len(joint_armature) > 0 else armature,
)
# -----------------
# add shapes
for geo_count, geom in enumerate(body.findall("geom")):
geom_defaults = defaults
if "class" in geom.attrib:
geom_class = geom.attrib["class"]
ignore_geom = False
for pattern in ignore_classes:
if re.match(pattern, geom_class):
ignore_geom = True
break
if ignore_geom:
continue
if geom_class in class_defaults:
geom_defaults = merge_attrib(defaults, class_defaults[geom_class])
if "geom" in geom_defaults:
geom_attrib = merge_attrib(geom_defaults["geom"], geom.attrib)
else:
geom_attrib = geom.attrib
geom_name = geom_attrib.get("name", f"{body_name}_geom_{geo_count}")
geom_type = geom_attrib.get("type", "sphere")
if "mesh" in geom_attrib:
geom_type = "mesh"
geom_size = parse_vec(geom_attrib, "size", [1.0, 1.0, 1.0]) * scale
geom_pos = parse_vec(geom_attrib, "pos", (0.0, 0.0, 0.0)) * scale
geom_rot = parse_orientation(geom_attrib)
geom_density = parse_float(geom_attrib, "density", density)
if geom_type == "sphere":
builder.add_shape_sphere(
link,
pos=geom_pos,
rot=geom_rot,
radius=geom_size[0],
density=geom_density,
**contact_vars,
)
elif geom_type == "box":
builder.add_shape_box(
link,
pos=geom_pos,
rot=geom_rot,
hx=geom_size[0],
hy=geom_size[1],
hz=geom_size[2],
density=geom_density,
**contact_vars,
)
elif geom_type == "mesh" and parse_meshes:
mesh, _ = parse_mesh(geom_attrib)
if "mesh" in defaults:
mesh_scale = parse_vec(defaults["mesh"], "scale", [1.0, 1.0, 1.0])
else:
mesh_scale = [1.0, 1.0, 1.0]
# as per the Mujoco XML reference, ignore geom size attribute
assert len(geom_size) == 3, "need to specify size for mesh geom"
builder.add_shape_mesh(
body=link,
pos=geom_pos,
rot=geom_rot,
mesh=mesh,
scale=mesh_scale,
density=density,
**contact_vars,
)
elif geom_type in {"capsule", "cylinder"}:
if "fromto" in geom_attrib:
geom_fromto = parse_vec(geom_attrib, "fromto", (0.0, 0.0, 0.0, 1.0, 0.0, 0.0))
start = wp.vec3(geom_fromto[0:3]) * scale
end = wp.vec3(geom_fromto[3:6]) * scale
# compute rotation to align the Warp capsule (along x-axis), with mjcf fromto direction
axis = wp.normalize(end - start)
angle = math.acos(wp.dot(axis, wp.vec3(0.0, 1.0, 0.0)))
axis = wp.normalize(wp.cross(axis, wp.vec3(0.0, 1.0, 0.0)))
geom_pos = (start + end) * 0.5
geom_rot = wp.quat_from_axis_angle(axis, -angle)
geom_radius = geom_size[0]
geom_height = wp.length(end - start) * 0.5
geom_up_axis = 1
else:
geom_radius = geom_size[0]
geom_height = geom_size[1]
geom_up_axis = up_axis
if geom_type == "cylinder":
builder.add_shape_cylinder(
link,
pos=geom_pos,
rot=geom_rot,
radius=geom_radius,
half_height=geom_height,
density=density,
up_axis=geom_up_axis,
**contact_vars,
)
else:
builder.add_shape_capsule(
link,
pos=geom_pos,
rot=geom_rot,
radius=geom_radius,
half_height=geom_height,
density=density,
up_axis=geom_up_axis,
**contact_vars,
)
else:
print(f"MJCF parsing shape {geom_name} issue: geom type {geom_type} is unsupported")
# -----------------
# recurse
for child in body.findall("body"):
parse_body(child, link, defaults)
# -----------------
# start articulation
start_shape_count = len(builder.shape_geo_type)
builder.add_articulation()
world = root.find("worldbody")
world_class = get_class(world)
world_defaults = merge_attrib(class_defaults["__all__"], class_defaults.get(world_class, {}))
for body in world.findall("body"):
parse_body(body, -1, world_defaults)
end_shape_count = len(builder.shape_geo_type)
if not enable_self_collisions:
for i in range(start_shape_count, end_shape_count):
for j in range(i + 1, end_shape_count):
builder.shape_collision_filter_pairs.add((i, j))
if collapse_fixed_joints:
builder.collapse_fixed_joints()
| 19,306 | Python | 38.402041 | 170 | 0.532995 |
NVIDIA/warp/warp/sim/integrator_xpbd.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from .integrator import Integrator
from .model import (
JOINT_MODE_FORCE,
JOINT_MODE_TARGET_POSITION,
JOINT_MODE_TARGET_VELOCITY,
PARTICLE_FLAG_ACTIVE,
Control,
Model,
ModelShapeMaterials,
State,
)
from .utils import vec_abs, vec_leaky_max, vec_leaky_min, vec_max, vec_min, velocity_at_point
@wp.kernel
def solve_particle_ground_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
ke: float,
kd: float,
kf: float,
mu: float,
ground: wp.array(dtype=float),
dt: float,
relaxation: float,
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
wi = invmass[tid]
if wi == 0.0:
return
x = particle_x[tid]
v = particle_v[tid]
n = wp.vec3(ground[0], ground[1], ground[2])
c = wp.min(wp.dot(n, x) + ground[3] - particle_radius[tid], 0.0)
if c > 0.0:
return
# normal
lambda_n = c
delta_n = n * lambda_n
# friction
vn = wp.dot(n, v)
vt = v - n * vn
lambda_f = wp.max(mu * lambda_n, 0.0 - wp.length(vt) * dt)
delta_f = wp.normalize(vt) * lambda_f
wp.atomic_add(delta, tid, (delta_f - delta_n) * relaxation)
@wp.kernel
def apply_particle_shape_restitution(
particle_x_new: wp.array(dtype=wp.vec3),
particle_v_new: wp.array(dtype=wp.vec3),
particle_x_old: wp.array(dtype=wp.vec3),
particle_v_old: wp.array(dtype=wp.vec3),
particle_invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
shape_body: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
particle_ka: float,
restitution: float,
contact_count: wp.array(dtype=int),
contact_particle: wp.array(dtype=int),
contact_shape: wp.array(dtype=int),
contact_body_pos: wp.array(dtype=wp.vec3),
contact_body_vel: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_max: int,
dt: float,
relaxation: float,
particle_v_out: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
count = min(contact_max, contact_count[0])
if tid >= count:
return
shape_index = contact_shape[tid]
body_index = shape_body[shape_index]
particle_index = contact_particle[tid]
if (particle_flags[particle_index] & PARTICLE_FLAG_ACTIVE) == 0:
return
# x_new = particle_x_new[particle_index]
v_new = particle_v_new[particle_index]
px = particle_x_old[particle_index]
v_old = particle_v_old[particle_index]
X_wb = wp.transform_identity()
# X_com = wp.vec3()
if body_index >= 0:
X_wb = body_q[body_index]
# X_com = body_com[body_index]
# body position in world space
bx = wp.transform_point(X_wb, contact_body_pos[tid])
# r = bx - wp.transform_point(X_wb, X_com)
n = contact_normal[tid]
c = wp.dot(n, px - bx) - particle_radius[particle_index]
if c > particle_ka:
return
rel_vel_old = wp.dot(n, v_old)
rel_vel_new = wp.dot(n, v_new)
if rel_vel_old < 0.0:
# dv = -n * wp.max(-rel_vel_new + wp.max(-restitution * rel_vel_old, 0.0), 0.0)
dv = n * (-rel_vel_new + wp.max(-restitution * rel_vel_old, 0.0))
# compute inverse masses
# w1 = particle_invmass[particle_index]
# w2 = 0.0
# if body_index >= 0:
# angular = wp.cross(r, n)
# q = wp.transform_get_rotation(X_wb)
# rot_angular = wp.quat_rotate_inv(q, angular)
# I_inv = body_I_inv[body_index]
# w2 = body_m_inv[body_index] + wp.dot(rot_angular, I_inv * rot_angular)
# denom = w1 + w2
# if denom == 0.0:
# return
wp.atomic_add(particle_v_out, tid, dv)
@wp.kernel
def apply_particle_ground_restitution(
particle_x_new: wp.array(dtype=wp.vec3),
particle_v_new: wp.array(dtype=wp.vec3),
particle_x_old: wp.array(dtype=wp.vec3),
particle_v_old: wp.array(dtype=wp.vec3),
particle_invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
particle_ka: float,
restitution: float,
ground: wp.array(dtype=float),
dt: float,
relaxation: float,
particle_v_out: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
wi = particle_invmass[tid]
if wi == 0.0:
return
x = particle_x_old[tid]
v_old = particle_v_old[tid]
v_new = particle_v_new[tid]
n = wp.vec3(ground[0], ground[1], ground[2])
c = wp.dot(n, x) + ground[3] - particle_radius[tid]
if c > particle_ka:
return
vn = wp.dot(n, v_old)
vn_new = wp.dot(n, v_new)
if vn < 0.0:
dv = n * (-vn_new + wp.max(-restitution * vn, 0.0))
wp.atomic_add(particle_v_out, tid, dv)
@wp.kernel
def solve_particle_shape_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
shape_body: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
particle_mu: float,
particle_ka: float,
contact_count: wp.array(dtype=int),
contact_particle: wp.array(dtype=int),
contact_shape: wp.array(dtype=int),
contact_body_pos: wp.array(dtype=wp.vec3),
contact_body_vel: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_max: int,
dt: float,
relaxation: float,
# outputs
delta: wp.array(dtype=wp.vec3),
body_delta: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
count = min(contact_max, contact_count[0])
if tid >= count:
return
shape_index = contact_shape[tid]
body_index = shape_body[shape_index]
particle_index = contact_particle[tid]
if (particle_flags[particle_index] & PARTICLE_FLAG_ACTIVE) == 0:
return
px = particle_x[particle_index]
pv = particle_v[particle_index]
X_wb = wp.transform_identity()
X_com = wp.vec3()
if body_index >= 0:
X_wb = body_q[body_index]
X_com = body_com[body_index]
# body position in world space
bx = wp.transform_point(X_wb, contact_body_pos[tid])
r = bx - wp.transform_point(X_wb, X_com)
n = contact_normal[tid]
c = wp.dot(n, px - bx) - particle_radius[particle_index]
if c > particle_ka:
return
# take average material properties of shape and particle parameters
mu = 0.5 * (particle_mu + shape_materials.mu[shape_index])
# body velocity
body_v_s = wp.spatial_vector()
if body_index >= 0:
body_v_s = body_qd[body_index]
body_w = wp.spatial_top(body_v_s)
body_v = wp.spatial_bottom(body_v_s)
# compute the body velocity at the particle position
bv = body_v + wp.cross(body_w, r) + wp.transform_vector(X_wb, contact_body_vel[tid])
# relative velocity
v = pv - bv
# normal
lambda_n = c
delta_n = n * lambda_n
# friction
vn = wp.dot(n, v)
vt = v - n * vn
# compute inverse masses
w1 = particle_invmass[particle_index]
w2 = 0.0
if body_index >= 0:
angular = wp.cross(r, n)
q = wp.transform_get_rotation(X_wb)
rot_angular = wp.quat_rotate_inv(q, angular)
I_inv = body_I_inv[body_index]
w2 = body_m_inv[body_index] + wp.dot(rot_angular, I_inv * rot_angular)
denom = w1 + w2
if denom == 0.0:
return
lambda_f = wp.max(mu * lambda_n, -wp.length(vt) * dt)
delta_f = wp.normalize(vt) * lambda_f
delta_total = (delta_f - delta_n) / denom * relaxation
wp.atomic_add(delta, particle_index, w1 * delta_total)
if body_index >= 0:
delta_t = wp.cross(r, delta_total)
wp.atomic_sub(body_delta, body_index, wp.spatial_vector(delta_t, delta_total))
@wp.kernel
def solve_particle_particle_contacts(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_invmass: wp.array(dtype=float),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
k_mu: float,
k_cohesion: float,
max_radius: float,
dt: float,
relaxation: float,
# outputs
deltas: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
if i == -1:
# hash grid has not been built yet
return
if (particle_flags[i] & PARTICLE_FLAG_ACTIVE) == 0:
return
x = particle_x[i]
v = particle_v[i]
radius = particle_radius[i]
w1 = particle_invmass[i]
# particle contact
query = wp.hash_grid_query(grid, x, radius + max_radius + k_cohesion)
index = int(0)
delta = wp.vec3(0.0)
while wp.hash_grid_query_next(query, index):
if (particle_flags[index] & PARTICLE_FLAG_ACTIVE) != 0 and index != i:
# compute distance to point
n = x - particle_x[index]
d = wp.length(n)
err = d - radius - particle_radius[index]
# compute inverse masses
w2 = particle_invmass[index]
denom = w1 + w2
if err <= k_cohesion and denom > 0.0:
n = n / d
vrel = v - particle_v[index]
# normal
lambda_n = err
delta_n = n * lambda_n
# friction
vn = wp.dot(n, vrel)
vt = v - n * vn
lambda_f = wp.max(k_mu * lambda_n, -wp.length(vt) * dt)
delta_f = wp.normalize(vt) * lambda_f
delta += (delta_f - delta_n) / denom
wp.atomic_add(deltas, i, delta * w1 * relaxation)
@wp.kernel
def solve_springs(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
spring_indices: wp.array(dtype=int),
spring_rest_lengths: wp.array(dtype=float),
spring_stiffness: wp.array(dtype=float),
spring_damping: wp.array(dtype=float),
dt: float,
lambdas: wp.array(dtype=float),
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = spring_indices[tid * 2 + 0]
j = spring_indices[tid * 2 + 1]
ke = spring_stiffness[tid]
kd = spring_damping[tid]
rest = spring_rest_lengths[tid]
xi = x[i]
xj = x[j]
vi = v[i]
vj = v[j]
xij = xi - xj
vij = vi - vj
l = wp.length(xij)
if l == 0.0:
return
n = xij / l
c = l - rest
grad_c_xi = n
grad_c_xj = -1.0 * n
wi = invmass[i]
wj = invmass[j]
denom = wi + wj
# Note strict inequality for damping -- 0 damping is ok
if denom <= 0.0 or ke <= 0.0 or kd < 0.0:
return
alpha = 1.0 / (ke * dt * dt)
gamma = kd / (ke * dt)
grad_c_dot_v = dt * wp.dot(grad_c_xi, vij) # Note: dt because from the paper we want x_i - x^n, not v...
dlambda = -1.0 * (c + alpha * lambdas[tid] + gamma * grad_c_dot_v) / ((1.0 + gamma) * denom + alpha)
dxi = wi * dlambda * grad_c_xi
dxj = wj * dlambda * grad_c_xj
lambdas[tid] = lambdas[tid] + dlambda
wp.atomic_add(delta, i, dxi)
wp.atomic_add(delta, j, dxj)
@wp.kernel
def bending_constraint(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
invmass: wp.array(dtype=float),
indices: wp.array2d(dtype=int),
rest: wp.array(dtype=float),
bending_properties: wp.array2d(dtype=float),
dt: float,
lambdas: wp.array(dtype=float),
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
eps = 1.0e-6
ke = bending_properties[tid, 0]
kd = bending_properties[tid, 1]
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
if i == -1 or j == -1 or k == -1 or l == -1:
return
rest_angle = rest[tid]
x1 = x[i]
x2 = x[j]
x3 = x[k]
x4 = x[l]
v1 = v[i]
v2 = v[j]
v3 = v[k]
v4 = v[l]
w1 = invmass[i]
w2 = invmass[j]
w3 = invmass[k]
w4 = invmass[l]
n1 = wp.cross(x3 - x1, x4 - x1) # normal to face 1
n2 = wp.cross(x4 - x2, x3 - x2) # normal to face 2
n1_length = wp.length(n1)
n2_length = wp.length(n2)
if n1_length < eps or n2_length < eps:
return
n1 /= n1_length
n2 /= n2_length
cos_theta = wp.dot(n1, n2)
e = x4 - x3
e_hat = wp.normalize(e)
e_length = wp.length(e)
derivative_flip = wp.sign(wp.dot(wp.cross(n1, n2), e))
derivative_flip *= -1.0
angle = wp.acos(cos_theta)
grad_x1 = n1 * e_length * derivative_flip
grad_x2 = n2 * e_length * derivative_flip
grad_x3 = (n1 * wp.dot(x1 - x4, e_hat) + n2 * wp.dot(x2 - x4, e_hat)) * derivative_flip
grad_x4 = (n1 * wp.dot(x3 - x1, e_hat) + n2 * wp.dot(x3 - x2, e_hat)) * derivative_flip
c = angle - rest_angle
denominator = (
w1 * wp.length_sq(grad_x1)
+ w2 * wp.length_sq(grad_x2)
+ w3 * wp.length_sq(grad_x3)
+ w4 * wp.length_sq(grad_x4)
)
# Note strict inequality for damping -- 0 damping is ok
if denominator <= 0.0 or ke <= 0.0 or kd < 0.0:
return
alpha = 1.0 / (ke * dt * dt)
gamma = kd / (ke * dt)
grad_dot_v = dt * (wp.dot(grad_x1, v1) + wp.dot(grad_x2, v2) + wp.dot(grad_x3, v3) + wp.dot(grad_x4, v4))
dlambda = -1.0 * (c + alpha * lambdas[tid] + gamma * grad_dot_v) / ((1.0 + gamma) * denominator + alpha)
delta0 = w1 * dlambda * grad_x1
delta1 = w2 * dlambda * grad_x2
delta2 = w3 * dlambda * grad_x3
delta3 = w4 * dlambda * grad_x4
lambdas[tid] = lambdas[tid] + dlambda
wp.atomic_add(delta, i, delta0)
wp.atomic_add(delta, j, delta1)
wp.atomic_add(delta, k, delta2)
wp.atomic_add(delta, l, delta3)
@wp.kernel
def solve_tetrahedra(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
inv_mass: wp.array(dtype=float),
indices: wp.array(dtype=int, ndim=2),
rest_matrix: wp.array(dtype=wp.mat33),
activation: wp.array(dtype=float),
materials: wp.array(dtype=float, ndim=2),
dt: float,
relaxation: float,
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
# act = activation[tid]
# k_mu = materials[tid, 0]
# k_lambda = materials[tid, 1]
# k_damp = materials[tid, 2]
x0 = x[i]
x1 = x[j]
x2 = x[k]
x3 = x[l]
# v0 = v[i]
# v1 = v[j]
# v2 = v[k]
# v3 = v[l]
w0 = inv_mass[i]
w1 = inv_mass[j]
w2 = inv_mass[k]
w3 = inv_mass[l]
x10 = x1 - x0
x20 = x2 - x0
x30 = x3 - x0
Ds = wp.mat33(x10, x20, x30)
Dm = rest_matrix[tid]
inv_QT = wp.transpose(Dm)
inv_rest_volume = wp.determinant(Dm) * 6.0
# F = Xs*Xm^-1
F = Ds * Dm
f1 = wp.vec3(F[0, 0], F[1, 0], F[2, 0])
f2 = wp.vec3(F[0, 1], F[1, 1], F[2, 1])
f3 = wp.vec3(F[0, 2], F[1, 2], F[2, 2])
tr = wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3)
C = float(0.0)
dC = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
compliance = float(0.0)
stretching_compliance = relaxation
volume_compliance = relaxation
num_terms = 2
for term in range(0, num_terms):
if term == 0:
# deviatoric, stable
C = tr - 3.0
dC = F * 2.0
compliance = stretching_compliance
elif term == 1:
# volume conservation
C = wp.determinant(F) - 1.0
dC = wp.mat33(wp.cross(f2, f3), wp.cross(f3, f1), wp.cross(f1, f2))
compliance = volume_compliance
if C != 0.0:
dP = dC * inv_QT
grad1 = wp.vec3(dP[0][0], dP[1][0], dP[2][0])
grad2 = wp.vec3(dP[0][1], dP[1][1], dP[2][1])
grad3 = wp.vec3(dP[0][2], dP[1][2], dP[2][2])
grad0 = -grad1 - grad2 - grad3
w = (
wp.dot(grad0, grad0) * w0
+ wp.dot(grad1, grad1) * w1
+ wp.dot(grad2, grad2) * w2
+ wp.dot(grad3, grad3) * w3
)
if w > 0.0:
alpha = compliance / dt / dt
if inv_rest_volume > 0.0:
alpha *= inv_rest_volume
dlambda = -C / (w + alpha)
wp.atomic_add(delta, i, w0 * dlambda * grad0)
wp.atomic_add(delta, j, w1 * dlambda * grad1)
wp.atomic_add(delta, k, w2 * dlambda * grad2)
wp.atomic_add(delta, l, w3 * dlambda * grad3)
# wp.atomic_add(particle.num_corr, id0, 1)
# wp.atomic_add(particle.num_corr, id1, 1)
# wp.atomic_add(particle.num_corr, id2, 1)
# wp.atomic_add(particle.num_corr, id3, 1)
# C_Spherical
# r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
# r_s_inv = 1.0/r_s
# C = r_s - wp.sqrt(3.0)
# dCdx = F*wp.transpose(Dm)*r_s_inv
# alpha = 1.0
# C_D
# r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
# C = r_s*r_s - 3.0
# dCdx = F*wp.transpose(Dm)*2.0
# alpha = 1.0
# grad1 = wp.vec3(dCdx[0, 0], dCdx[1, 0], dCdx[2, 0])
# grad2 = wp.vec3(dCdx[0, 1], dCdx[1, 1], dCdx[2, 1])
# grad3 = wp.vec3(dCdx[0, 2], dCdx[1, 2], dCdx[2, 2])
# grad0 = (grad1 + grad2 + grad3) * (0.0 - 1.0)
# denom = (
# wp.dot(grad0, grad0) * w0 + wp.dot(grad1, grad1) * w1 + wp.dot(grad2, grad2) * w2 + wp.dot(grad3, grad3) * w3
# )
# multiplier = C / (denom + 1.0 / (k_mu * dt * dt * rest_volume))
# delta0 = grad0 * multiplier
# delta1 = grad1 * multiplier
# delta2 = grad2 * multiplier
# delta3 = grad3 * multiplier
# # hydrostatic part
# J = wp.determinant(F)
# C_vol = J - alpha
# # dCdx = wp.mat33(wp.cross(f2, f3), wp.cross(f3, f1), wp.cross(f1, f2))*wp.transpose(Dm)
# # grad1 = wp.vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# # grad2 = wp.vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# # grad3 = wp.vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# # grad0 = (grad1 + grad2 + grad3)*(0.0 - 1.0)
# s = inv_rest_volume / 6.0
# grad1 = wp.cross(x20, x30) * s
# grad2 = wp.cross(x30, x10) * s
# grad3 = wp.cross(x10, x20) * s
# grad0 = -(grad1 + grad2 + grad3)
# denom = (
# wp.dot(grad0, grad0) * w0 + wp.dot(grad1, grad1) * w1 + wp.dot(grad2, grad2) * w2 + wp.dot(grad3, grad3) * w3
# )
# multiplier = C_vol / (denom + 1.0 / (k_lambda * dt * dt * rest_volume))
# delta0 += grad0 * multiplier
# delta1 += grad1 * multiplier
# delta2 += grad2 * multiplier
# delta3 += grad3 * multiplier
# # # apply forces
# # wp.atomic_sub(delta, i, delta0 * w0 * relaxation)
# # wp.atomic_sub(delta, j, delta1 * w1 * relaxation)
# # wp.atomic_sub(delta, k, delta2 * w2 * relaxation)
# # wp.atomic_sub(delta, l, delta3 * w3 * relaxation)
@wp.kernel
def solve_tetrahedra2(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
inv_mass: wp.array(dtype=float),
indices: wp.array(dtype=int, ndim=2),
pose: wp.array(dtype=wp.mat33),
activation: wp.array(dtype=float),
materials: wp.array(dtype=float, ndim=2),
dt: float,
relaxation: float,
delta: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
# act = activation[tid]
k_mu = materials[tid, 0]
k_lambda = materials[tid, 1]
# k_damp = materials[tid, 2]
x0 = x[i]
x1 = x[j]
x2 = x[k]
x3 = x[l]
# v0 = v[i]
# v1 = v[j]
# v2 = v[k]
# v3 = v[l]
w0 = inv_mass[i]
w1 = inv_mass[j]
w2 = inv_mass[k]
w3 = inv_mass[l]
x10 = x1 - x0
x20 = x2 - x0
x30 = x3 - x0
Ds = wp.mat33(x10, x20, x30)
Dm = pose[tid]
inv_rest_volume = wp.determinant(Dm) * 6.0
rest_volume = 1.0 / inv_rest_volume
# F = Xs*Xm^-1
F = Ds * Dm
f1 = wp.vec3(F[0, 0], F[1, 0], F[2, 0])
f2 = wp.vec3(F[0, 1], F[1, 1], F[2, 1])
f3 = wp.vec3(F[0, 2], F[1, 2], F[2, 2])
# C_sqrt
# tr = wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3)
# r_s = wp.sqrt(abs(tr - 3.0))
# C = r_s
# if (r_s == 0.0):
# return
# if (tr < 3.0):
# r_s = 0.0 - r_s
# dCdx = F*wp.transpose(Dm)*(1.0/r_s)
# alpha = 1.0 + k_mu / k_lambda
# C_Neo
r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
if r_s == 0.0:
return
# tr = wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3)
# if (tr < 3.0):
# r_s = -r_s
r_s_inv = 1.0 / r_s
C = r_s
dCdx = F * wp.transpose(Dm) * r_s_inv
alpha = 1.0 + k_mu / k_lambda
# C_Spherical
# r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
# r_s_inv = 1.0/r_s
# C = r_s - wp.sqrt(3.0)
# dCdx = F*wp.transpose(Dm)*r_s_inv
# alpha = 1.0
# C_D
# r_s = wp.sqrt(wp.dot(f1, f1) + wp.dot(f2, f2) + wp.dot(f3, f3))
# C = r_s*r_s - 3.0
# dCdx = F*wp.transpose(Dm)*2.0
# alpha = 1.0
grad1 = wp.vec3(dCdx[0, 0], dCdx[1, 0], dCdx[2, 0])
grad2 = wp.vec3(dCdx[0, 1], dCdx[1, 1], dCdx[2, 1])
grad3 = wp.vec3(dCdx[0, 2], dCdx[1, 2], dCdx[2, 2])
grad0 = (grad1 + grad2 + grad3) * (0.0 - 1.0)
denom = (
wp.dot(grad0, grad0) * w0 + wp.dot(grad1, grad1) * w1 + wp.dot(grad2, grad2) * w2 + wp.dot(grad3, grad3) * w3
)
multiplier = C / (denom + 1.0 / (k_mu * dt * dt * rest_volume))
delta0 = grad0 * multiplier
delta1 = grad1 * multiplier
delta2 = grad2 * multiplier
delta3 = grad3 * multiplier
# hydrostatic part
J = wp.determinant(F)
C_vol = J - alpha
# dCdx = wp.mat33(wp.cross(f2, f3), wp.cross(f3, f1), wp.cross(f1, f2))*wp.transpose(Dm)
# grad1 = wp.vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = wp.vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = wp.vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# grad0 = (grad1 + grad2 + grad3)*(0.0 - 1.0)
s = inv_rest_volume / 6.0
grad1 = wp.cross(x20, x30) * s
grad2 = wp.cross(x30, x10) * s
grad3 = wp.cross(x10, x20) * s
grad0 = -(grad1 + grad2 + grad3)
denom = (
wp.dot(grad0, grad0) * w0 + wp.dot(grad1, grad1) * w1 + wp.dot(grad2, grad2) * w2 + wp.dot(grad3, grad3) * w3
)
multiplier = C_vol / (denom + 1.0 / (k_lambda * dt * dt * rest_volume))
delta0 += grad0 * multiplier
delta1 += grad1 * multiplier
delta2 += grad2 * multiplier
delta3 += grad3 * multiplier
# apply forces
wp.atomic_sub(delta, i, delta0 * w0 * relaxation)
wp.atomic_sub(delta, j, delta1 * w1 * relaxation)
wp.atomic_sub(delta, k, delta2 * w2 * relaxation)
wp.atomic_sub(delta, l, delta3 * w3 * relaxation)
@wp.kernel
def apply_particle_deltas(
x_orig: wp.array(dtype=wp.vec3),
x_pred: wp.array(dtype=wp.vec3),
particle_flags: wp.array(dtype=wp.uint32),
delta: wp.array(dtype=wp.vec3),
dt: float,
v_max: float,
x_out: wp.array(dtype=wp.vec3),
v_out: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
x0 = x_orig[tid]
xp = x_pred[tid]
# constraint deltas
d = delta[tid]
x_new = xp + d
v_new = (x_new - x0) / dt
# enforce velocity limit to prevent instability
v_new_mag = wp.length(v_new)
if v_new_mag > v_max:
v_new *= v_max / v_new_mag
x_out[tid] = x_new
v_out[tid] = v_new
@wp.kernel
def apply_body_deltas(
q_in: wp.array(dtype=wp.transform),
qd_in: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_I: wp.array(dtype=wp.mat33),
body_inv_m: wp.array(dtype=float),
body_inv_I: wp.array(dtype=wp.mat33),
deltas: wp.array(dtype=wp.spatial_vector),
constraint_inv_weights: wp.array(dtype=float),
dt: float,
# outputs
q_out: wp.array(dtype=wp.transform),
qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
inv_m = body_inv_m[tid]
if inv_m == 0.0:
q_out[tid] = q_in[tid]
qd_out[tid] = qd_in[tid]
return
inv_I = body_inv_I[tid]
tf = q_in[tid]
delta = deltas[tid]
p0 = wp.transform_get_translation(tf)
q0 = wp.transform_get_rotation(tf)
weight = 1.0
if constraint_inv_weights:
inv_weight = constraint_inv_weights[tid]
if inv_weight > 0.0:
weight = 1.0 / inv_weight
dp = wp.spatial_bottom(delta) * (inv_m * weight)
dq = wp.spatial_top(delta) * weight
dq = wp.quat_rotate(q0, inv_I * wp.quat_rotate_inv(q0, dq))
# update orientation
q1 = q0 + 0.5 * wp.quat(dq * dt, 0.0) * q0
q1 = wp.normalize(q1)
# update position
com = body_com[tid]
x_com = p0 + wp.quat_rotate(q0, com)
p1 = x_com + dp * dt
p1 -= wp.quat_rotate(q1, com)
q_out[tid] = wp.transform(p1, q1)
v0 = wp.spatial_bottom(qd_in[tid])
w0 = wp.spatial_top(qd_in[tid])
# update linear and angular velocity
v1 = v0 + dp
# angular part (compute in body frame)
wb = wp.quat_rotate_inv(q0, w0 + dq)
tb = -wp.cross(wb, body_I[tid] * wb) # coriolis forces
w1 = wp.quat_rotate(q0, wb + inv_I * tb * dt)
# XXX this improves gradient stability
if wp.length(v1) < 1e-4:
v1 = wp.vec3(0.0)
if wp.length(w1) < 1e-4:
w1 = wp.vec3(0.0)
qd_out[tid] = wp.spatial_vector(w1, v1)
@wp.kernel
def apply_body_delta_velocities(
deltas: wp.array(dtype=wp.spatial_vector),
qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
wp.atomic_add(qd_out, tid, deltas[tid])
@wp.kernel
def apply_joint_torques(
body_q: wp.array(dtype=wp.transform),
body_com: wp.array(dtype=wp.vec3),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_mode: wp.array(dtype=int),
joint_act: wp.array(dtype=float),
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
if type == wp.sim.JOINT_FIXED:
return
if type == wp.sim.JOINT_FREE:
return
if type == wp.sim.JOINT_DISTANCE:
return
if type == wp.sim.JOINT_BALL:
return
# rigid body indices of the child and parent
id_c = joint_child[tid]
id_p = joint_parent[tid]
X_pj = joint_X_p[tid]
# X_cj = joint_X_c[tid]
X_wp = X_pj
pose_p = X_pj
com_p = wp.vec3(0.0)
# parent transform and moment arm
if id_p >= 0:
pose_p = body_q[id_p]
X_wp = pose_p * X_wp
com_p = body_com[id_p]
r_p = wp.transform_get_translation(X_wp) - wp.transform_point(pose_p, com_p)
# child transform and moment arm
pose_c = body_q[id_c]
X_wc = pose_c
com_c = body_com[id_c]
r_c = wp.transform_get_translation(X_wc) - wp.transform_point(pose_c, com_c)
# # local joint rotations
# q_p = wp.transform_get_rotation(X_wp)
# q_c = wp.transform_get_rotation(X_wc)
# joint properties (for 1D joints)
# q_start = joint_q_start[tid]
qd_start = joint_qd_start[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
# total force/torque on the parent
t_total = wp.vec3()
f_total = wp.vec3()
# handle angular constraints
if type == wp.sim.JOINT_REVOLUTE:
mode = joint_axis_mode[axis_start]
if mode == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start]
act = joint_act[qd_start]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
elif type == wp.sim.JOINT_PRISMATIC:
mode = joint_axis_mode[axis_start]
if mode == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start]
act = joint_act[qd_start]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
elif type == wp.sim.JOINT_COMPOUND:
# q_off = wp.transform_get_rotation(X_cj)
# q_pc = wp.quat_inverse(q_off)*wp.quat_inverse(q_p)*q_c*q_off
# # decompose to a compound rotation each axis
# angles = quat_decompose(q_pc)
# # reconstruct rotation axes
# axis_0 = wp.vec3(1.0, 0.0, 0.0)
# q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
# axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
# q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
# axis_2 = wp.quat_rotate(q_1*q_0, wp.vec3(0.0, 0.0, 1.0))
# q_w = q_p*q_off
# t_total += joint_act[qd_start+0] * wp.quat_rotate(q_w, axis_0)
# t_total += joint_act[qd_start+1] * wp.quat_rotate(q_w, axis_1)
# t_total += joint_act[qd_start+2] * wp.quat_rotate(q_w, axis_2)
if joint_axis_mode[axis_start + 0] == wp.sim.JOINT_MODE_FORCE:
axis_0 = joint_axis[axis_start + 0]
t_total += joint_act[qd_start + 0] * wp.transform_vector(X_wp, axis_0)
if joint_axis_mode[axis_start + 1] == wp.sim.JOINT_MODE_FORCE:
axis_1 = joint_axis[axis_start + 1]
t_total += joint_act[qd_start + 1] * wp.transform_vector(X_wp, axis_1)
if joint_axis_mode[axis_start + 2] == wp.sim.JOINT_MODE_FORCE:
axis_2 = joint_axis[axis_start + 2]
t_total += joint_act[qd_start + 2] * wp.transform_vector(X_wp, axis_2)
elif type == wp.sim.JOINT_UNIVERSAL:
# q_off = wp.transform_get_rotation(X_cj)
# q_pc = wp.quat_inverse(q_off)*wp.quat_inverse(q_p)*q_c*q_off
# # decompose to a compound rotation each axis
# angles = quat_decompose(q_pc)
# # reconstruct rotation axes
# axis_0 = wp.vec3(1.0, 0.0, 0.0)
# q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
# axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
# q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
# axis_2 = wp.quat_rotate(q_1*q_0, wp.vec3(0.0, 0.0, 1.0))
# q_w = q_p*q_off
# free axes
# t_total += joint_act[qd_start+0] * wp.quat_rotate(q_w, axis_0)
# t_total += joint_act[qd_start+1] * wp.quat_rotate(q_w, axis_1)
if joint_axis_mode[axis_start + 0] == wp.sim.JOINT_MODE_FORCE:
axis_0 = joint_axis[axis_start + 0]
t_total += joint_act[qd_start + 0] * wp.transform_vector(X_wp, axis_0)
if joint_axis_mode[axis_start + 1] == wp.sim.JOINT_MODE_FORCE:
axis_1 = joint_axis[axis_start + 1]
t_total += joint_act[qd_start + 1] * wp.transform_vector(X_wp, axis_1)
elif type == wp.sim.JOINT_D6:
# unroll for loop to ensure joint actions remain differentiable
# (since differentiating through a dynamic for loop that updates a local variable is not supported)
if lin_axis_count > 0:
if joint_axis_mode[axis_start + 0] == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start + 0]
act = joint_act[qd_start + 0]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
if lin_axis_count > 1:
if joint_axis_mode[axis_start + 1] == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start + 1]
act = joint_act[qd_start + 1]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
if lin_axis_count > 2:
if joint_axis_mode[axis_start + 2] == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start + 2]
act = joint_act[qd_start + 2]
a_p = wp.transform_vector(X_wp, axis)
f_total += act * a_p
if ang_axis_count > 0:
if joint_axis_mode[axis_start + lin_axis_count + 0] == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start + lin_axis_count + 0]
act = joint_act[qd_start + lin_axis_count + 0]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
if ang_axis_count > 1:
if joint_axis_mode[axis_start + lin_axis_count + 1] == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start + lin_axis_count + 1]
act = joint_act[qd_start + lin_axis_count + 1]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
if ang_axis_count > 2:
if joint_axis_mode[axis_start + lin_axis_count + 2] == wp.sim.JOINT_MODE_FORCE:
axis = joint_axis[axis_start + lin_axis_count + 2]
act = joint_act[qd_start + lin_axis_count + 2]
a_p = wp.transform_vector(X_wp, axis)
t_total += act * a_p
else:
print("joint type not handled in apply_joint_torques")
# write forces
if id_p >= 0:
wp.atomic_sub(body_f, id_p, wp.spatial_vector(t_total + wp.cross(r_p, f_total), f_total))
wp.atomic_add(body_f, id_c, wp.spatial_vector(t_total + wp.cross(r_c, f_total), f_total))
@wp.func
def update_joint_axis_mode(mode: wp.int32, axis: wp.vec3, input_axis_mode: wp.vec3i):
# update the 3D axis mode flags given the axis vector and mode of this axis
mode_x = wp.max(wp.int32(wp.nonzero(axis[0])) * mode, input_axis_mode[0])
mode_y = wp.max(wp.int32(wp.nonzero(axis[1])) * mode, input_axis_mode[1])
mode_z = wp.max(wp.int32(wp.nonzero(axis[2])) * mode, input_axis_mode[2])
return wp.vec3i(mode_x, mode_y, mode_z)
@wp.func
def update_joint_axis_limits(axis: wp.vec3, limit_lower: float, limit_upper: float, input_limits: wp.spatial_vector):
# update the 3D linear/angular limits (spatial_vector [lower, upper]) given the axis vector and limits
lo_temp = axis * limit_lower
up_temp = axis * limit_upper
lo = vec_min(lo_temp, up_temp)
up = vec_max(lo_temp, up_temp)
input_lower = wp.spatial_top(input_limits)
input_upper = wp.spatial_bottom(input_limits)
lower = vec_min(input_lower, lo)
upper = vec_max(input_upper, up)
return wp.spatial_vector(lower, upper)
@wp.func
def update_joint_axis_target_ke_kd(
axis: wp.vec3, target: float, target_ke: float, target_kd: float, input_target_ke_kd: wp.mat33
):
# update the 3D linear/angular target, target_ke, and target_kd (mat33 [target, ke, kd]) given the axis vector and target, target_ke, target_kd
axis_target = input_target_ke_kd[0]
axis_ke = input_target_ke_kd[1]
axis_kd = input_target_ke_kd[2]
stiffness = axis * target_ke
axis_target += stiffness * target # weighted target (to be normalized later by sum of target_ke)
axis_ke += vec_abs(stiffness)
axis_kd += vec_abs(axis * target_kd)
return wp.mat33(
axis_target[0],
axis_target[1],
axis_target[2],
axis_ke[0],
axis_ke[1],
axis_ke[2],
axis_kd[0],
axis_kd[1],
axis_kd[2],
)
@wp.func
def compute_linear_correction_3d(
dx: wp.vec3,
r1: wp.vec3,
r2: wp.vec3,
tf1: wp.transform,
tf2: wp.transform,
m_inv1: float,
m_inv2: float,
I_inv1: wp.mat33,
I_inv2: wp.mat33,
lambda_in: float,
compliance: float,
damping: float,
dt: float,
) -> float:
c = wp.length(dx)
if c == 0.0:
# print("c == 0.0 in positional correction")
return 0.0
n = wp.normalize(dx)
q1 = wp.transform_get_rotation(tf1)
q2 = wp.transform_get_rotation(tf2)
# Eq. 2-3 (make sure to project into the frame of the body)
r1xn = wp.quat_rotate_inv(q1, wp.cross(r1, n))
r2xn = wp.quat_rotate_inv(q2, wp.cross(r2, n))
w1 = m_inv1 + wp.dot(r1xn, I_inv1 * r1xn)
w2 = m_inv2 + wp.dot(r2xn, I_inv2 * r2xn)
w = w1 + w2
if w == 0.0:
return 0.0
alpha = compliance
gamma = compliance * damping
# Eq. 4-5
d_lambda = -c - alpha * lambda_in
# TODO consider damping for velocity correction?
# delta_lambda = -(err + alpha * lambda_in + gamma * derr)
if w + alpha > 0.0:
d_lambda /= w * (dt + gamma) + alpha / dt
return d_lambda
@wp.func
def compute_angular_correction_3d(
corr: wp.vec3,
q1: wp.quat,
q2: wp.quat,
m_inv1: float,
m_inv2: float,
I_inv1: wp.mat33,
I_inv2: wp.mat33,
alpha_tilde: float,
# lambda_prev: float,
relaxation: float,
dt: float,
):
# compute and apply the correction impulse for an angular constraint
theta = wp.length(corr)
if theta == 0.0:
return 0.0
n = wp.normalize(corr)
# project variables to body rest frame as they are in local matrix
n1 = wp.quat_rotate_inv(q1, n)
n2 = wp.quat_rotate_inv(q2, n)
# Eq. 11-12
w1 = wp.dot(n1, I_inv1 * n1)
w2 = wp.dot(n2, I_inv2 * n2)
w = w1 + w2
if w == 0.0:
return 0.0
# Eq. 13-14
lambda_prev = 0.0
d_lambda = (-theta - alpha_tilde * lambda_prev) / (w * dt + alpha_tilde / dt)
# TODO consider lambda_prev?
# p = d_lambda * n * relaxation
# Eq. 15-16
return d_lambda
@wp.kernel
def solve_simple_body_joints(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_inv_m: wp.array(dtype=float),
body_inv_I: wp.array(dtype=wp.mat33),
joint_type: wp.array(dtype=int),
joint_enabled: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis_mode: wp.array(dtype=int),
joint_axis: wp.array(dtype=wp.vec3),
joint_target: wp.array(dtype=float),
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_linear_compliance: wp.array(dtype=float),
joint_angular_compliance: wp.array(dtype=float),
angular_relaxation: float,
linear_relaxation: float,
dt: float,
deltas: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
if joint_enabled[tid] == 0:
return
if type == wp.sim.JOINT_FREE:
return
if type == wp.sim.JOINT_COMPOUND:
return
if type == wp.sim.JOINT_UNIVERSAL:
return
if type == wp.sim.JOINT_DISTANCE:
return
if type == wp.sim.JOINT_D6:
return
# rigid body indices of the child and parent
id_c = joint_child[tid]
id_p = joint_parent[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
m_inv_p = 0.0
I_inv_p = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
pose_p = X_pj
com_p = wp.vec3(0.0)
# parent transform and moment arm
if id_p >= 0:
pose_p = body_q[id_p]
X_wp = pose_p * X_wp
com_p = body_com[id_p]
m_inv_p = body_inv_m[id_p]
I_inv_p = body_inv_I[id_p]
r_p = wp.transform_get_translation(X_wp) - wp.transform_point(pose_p, com_p)
# child transform and moment arm
pose_c = body_q[id_c]
X_wc = pose_c * X_cj
com_c = body_com[id_c]
m_inv_c = body_inv_m[id_c]
I_inv_c = body_inv_I[id_c]
r_c = wp.transform_get_translation(X_wc) - wp.transform_point(pose_c, com_c)
if m_inv_p == 0.0 and m_inv_c == 0.0:
# connection between two immovable bodies
return
# accumulate constraint deltas
lin_delta_p = wp.vec3(0.0)
ang_delta_p = wp.vec3(0.0)
lin_delta_c = wp.vec3(0.0)
ang_delta_c = wp.vec3(0.0)
# rel_pose = wp.transform_inverse(X_wp) * X_wc
# rel_p = wp.transform_get_translation(rel_pose)
# joint connection points
# x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
# linear_compliance = joint_linear_compliance[tid]
angular_compliance = joint_angular_compliance[tid]
damping = 0.0
axis_start = joint_axis_start[tid]
# mode = joint_axis_mode[axis_start]
# local joint rotations
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
inertial_q_p = wp.transform_get_rotation(pose_p)
inertial_q_c = wp.transform_get_rotation(pose_c)
# joint properties (for 1D joints)
axis = joint_axis[axis_start]
if type == wp.sim.JOINT_FIXED:
limit_lower = 0.0
limit_upper = 0.0
else:
limit_lower = joint_limit_lower[axis_start]
limit_upper = joint_limit_upper[axis_start]
# linear_alpha_tilde = linear_compliance / dt / dt
angular_alpha_tilde = angular_compliance / dt / dt
# prevent division by zero
# linear_alpha_tilde = wp.max(linear_alpha_tilde, 1e-6)
# angular_alpha_tilde = wp.max(angular_alpha_tilde, 1e-6)
# accumulate constraint deltas
lin_delta_p = wp.vec3(0.0)
ang_delta_p = wp.vec3(0.0)
lin_delta_c = wp.vec3(0.0)
ang_delta_c = wp.vec3(0.0)
# handle angular constraints
if type == wp.sim.JOINT_REVOLUTE:
# align joint axes
a_p = wp.quat_rotate(q_p, axis)
a_c = wp.quat_rotate(q_c, axis)
# Eq. 20
corr = wp.cross(a_p, a_c)
ncorr = wp.normalize(corr)
angular_relaxation = 0.2
# angular_correction(
# corr, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c,
# angular_alpha_tilde, angular_relaxation, deltas, id_p, id_c)
lambda_n = compute_angular_correction_3d(
corr, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c, angular_alpha_tilde, damping, dt
)
lambda_n *= angular_relaxation
ang_delta_p -= lambda_n * ncorr
ang_delta_c += lambda_n * ncorr
# limit joint angles (Alg. 3)
pi = 3.14159265359
two_pi = 2.0 * pi
if limit_lower > -two_pi or limit_upper < two_pi:
# find a perpendicular vector to joint axis
a = axis
# https://math.stackexchange.com/a/3582461
g = wp.sign(a[2])
h = a[2] + g
b = wp.vec3(g - a[0] * a[0] / h, -a[0] * a[1] / h, -a[0])
c = wp.normalize(wp.cross(a, b))
# b = c # TODO verify
# joint axis
n = wp.quat_rotate(q_p, a)
# the axes n1 and n2 are aligned with the two bodies
n1 = wp.quat_rotate(q_p, b)
n2 = wp.quat_rotate(q_c, b)
phi = wp.asin(wp.dot(wp.cross(n1, n2), n))
# print("phi")
# print(phi)
if wp.dot(n1, n2) < 0.0:
phi = pi - phi
if phi > pi:
phi -= two_pi
if phi < -pi:
phi += two_pi
if phi < limit_lower or phi > limit_upper:
phi = wp.clamp(phi, limit_lower, limit_upper)
# print("clamped phi")
# print(phi)
# rot = wp.quat(phi, n[0], n[1], n[2])
# rot = wp.quat(n, phi)
rot = wp.quat_from_axis_angle(n, phi)
n1 = wp.quat_rotate(rot, n1)
corr = wp.cross(n1, n2)
# print("corr")
# print(corr)
# TODO expose
# angular_alpha_tilde = 0.0001 / dt / dt
# angular_relaxation = 0.5
# TODO fix this constraint
# angular_correction(
# corr, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c,
# angular_alpha_tilde, angular_relaxation, deltas, id_p, id_c)
lambda_n = compute_angular_correction_3d(
corr,
inertial_q_p,
inertial_q_c,
m_inv_p,
m_inv_c,
I_inv_p,
I_inv_c,
angular_alpha_tilde,
damping,
dt,
)
lambda_n *= angular_relaxation
ncorr = wp.normalize(corr)
ang_delta_p -= lambda_n * ncorr
ang_delta_c += lambda_n * ncorr
# handle joint targets
target_ke = joint_target_ke[axis_start]
# target_kd = joint_target_kd[axis_start]
target = joint_target[axis_start]
if target_ke > 0.0:
# find a perpendicular vector to joint axis
a = axis
# https://math.stackexchange.com/a/3582461
g = wp.sign(a[2])
h = a[2] + g
b = wp.vec3(g - a[0] * a[0] / h, -a[0] * a[1] / h, -a[0])
c = wp.normalize(wp.cross(a, b))
b = c
q = wp.quat_from_axis_angle(a_p, target)
b_target = wp.quat_rotate(q, wp.quat_rotate(q_p, b))
b2 = wp.quat_rotate(q_c, b)
# Eq. 21
d_target = wp.cross(b_target, b2)
target_compliance = 1.0 / target_ke # / dt / dt
# angular_correction(
# d_target, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c,
# target_compliance, angular_relaxation, deltas, id_p, id_c)
lambda_n = compute_angular_correction_3d(
d_target, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c, target_compliance, damping, dt
)
lambda_n *= angular_relaxation
ncorr = wp.normalize(d_target)
# TODO fix
ang_delta_p -= lambda_n * ncorr
ang_delta_c += lambda_n * ncorr
if (type == wp.sim.JOINT_FIXED) or (type == wp.sim.JOINT_PRISMATIC):
# align the mutual orientations of the two bodies
# Eq. 18-19
q = q_p * wp.quat_inverse(q_c)
corr = -2.0 * wp.vec3(q[0], q[1], q[2])
# angular_correction(
# -corr, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c,
# angular_alpha_tilde, angular_relaxation, deltas, id_p, id_c)
lambda_n = compute_angular_correction_3d(
corr, inertial_q_p, inertial_q_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c, angular_alpha_tilde, damping, dt
)
lambda_n *= angular_relaxation
ncorr = wp.normalize(corr)
ang_delta_p -= lambda_n * ncorr
ang_delta_c += lambda_n * ncorr
# handle positional constraints
# joint connection points
x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
# compute error between the joint attachment points on both bodies
# delta x is the difference of point r_2 minus point r_1 (Fig. 3)
dx = x_c - x_p
# rotate the error vector into the joint frame
q_dx = q_p
# q_dx = q_c
# q_dx = wp.transform_get_rotation(pose_p)
dx = wp.quat_rotate_inv(q_dx, dx)
lower_pos_limits = wp.vec3(0.0)
upper_pos_limits = wp.vec3(0.0)
if type == wp.sim.JOINT_PRISMATIC:
lower_pos_limits = axis * limit_lower
upper_pos_limits = axis * limit_upper
# compute linear constraint violations
corr = wp.vec3(0.0)
zero = wp.vec3(0.0)
corr -= vec_leaky_min(zero, upper_pos_limits - dx)
corr -= vec_leaky_max(zero, lower_pos_limits - dx)
# if (type == wp.sim.JOINT_PRISMATIC):
# if mode == JOINT_MODE_TARGET_POSITION:
# target = wp.clamp(target, limit_lower, limit_upper)
# if target_ke > 0.0:
# err = dx - target * axis
# compliance = 1.0 / target_ke
# damping = axis_damping[dim]
# elif mode == JOINT_MODE_TARGET_VELOCITY:
# if target_ke > 0.0:
# err = (derr - target) * dt
# compliance = 1.0 / target_ke
# damping = axis_damping[dim]
# rotate correction vector into world frame
corr = wp.quat_rotate(q_dx, corr)
lambda_in = 0.0
linear_alpha = joint_linear_compliance[tid]
lambda_n = compute_linear_correction_3d(
corr, r_p, r_c, pose_p, pose_c, m_inv_p, m_inv_c, I_inv_p, I_inv_c, lambda_in, linear_alpha, damping, dt
)
lambda_n *= linear_relaxation
n = wp.normalize(corr)
lin_delta_p -= n * lambda_n
lin_delta_c += n * lambda_n
ang_delta_p -= wp.cross(r_p, n) * lambda_n
ang_delta_c += wp.cross(r_c, n) * lambda_n
if id_p >= 0:
wp.atomic_add(deltas, id_p, wp.spatial_vector(ang_delta_p, lin_delta_p))
if id_c >= 0:
wp.atomic_add(deltas, id_c, wp.spatial_vector(ang_delta_c, lin_delta_c))
@wp.kernel
def solve_body_joints(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_inv_m: wp.array(dtype=float),
body_inv_I: wp.array(dtype=wp.mat33),
joint_type: wp.array(dtype=int),
joint_enabled: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis_mode: wp.array(dtype=int),
joint_axis: wp.array(dtype=wp.vec3),
joint_act: wp.array(dtype=float),
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_linear_compliance: wp.array(dtype=float),
joint_angular_compliance: wp.array(dtype=float),
angular_relaxation: float,
linear_relaxation: float,
dt: float,
deltas: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
if joint_enabled[tid] == 0:
return
if type == wp.sim.JOINT_FREE:
return
# if type == wp.sim.JOINT_FIXED:
# return
# if type == wp.sim.JOINT_REVOLUTE:
# return
# if type == wp.sim.JOINT_PRISMATIC:
# return
# if type == wp.sim.JOINT_BALL:
# return
# rigid body indices of the child and parent
id_c = joint_child[tid]
id_p = joint_parent[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
m_inv_p = 0.0
I_inv_p = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
pose_p = X_pj
com_p = wp.vec3(0.0)
vel_p = wp.vec3(0.0)
omega_p = wp.vec3(0.0)
# parent transform and moment arm
if id_p >= 0:
pose_p = body_q[id_p]
X_wp = pose_p * X_wp
com_p = body_com[id_p]
m_inv_p = body_inv_m[id_p]
I_inv_p = body_inv_I[id_p]
vel_p = wp.spatial_bottom(body_qd[id_p])
omega_p = wp.spatial_top(body_qd[id_p])
# child transform and moment arm
pose_c = body_q[id_c]
X_wc = pose_c * X_cj
com_c = body_com[id_c]
m_inv_c = body_inv_m[id_c]
I_inv_c = body_inv_I[id_c]
vel_c = wp.spatial_bottom(body_qd[id_c])
omega_c = wp.spatial_top(body_qd[id_c])
if m_inv_p == 0.0 and m_inv_c == 0.0:
# connection between two immovable bodies
return
# accumulate constraint deltas
lin_delta_p = wp.vec3(0.0)
ang_delta_p = wp.vec3(0.0)
lin_delta_c = wp.vec3(0.0)
ang_delta_c = wp.vec3(0.0)
rel_pose = wp.transform_inverse(X_wp) * X_wc
rel_p = wp.transform_get_translation(rel_pose)
# joint connection points
# x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
linear_compliance = joint_linear_compliance[tid]
angular_compliance = joint_angular_compliance[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
world_com_p = wp.transform_point(pose_p, com_p)
world_com_c = wp.transform_point(pose_c, com_c)
# handle positional constraints
if type == wp.sim.JOINT_DISTANCE:
r_p = wp.transform_get_translation(X_wp) - world_com_p
r_c = wp.transform_get_translation(X_wc) - world_com_c
lower = joint_limit_lower[axis_start]
upper = joint_limit_upper[axis_start]
if lower < 0.0 and upper < 0.0:
# no limits
return
d = wp.length(rel_p)
err = 0.0
if lower >= 0.0 and d < lower:
err = d - lower
# use a more descriptive direction vector for the constraint
# in case the joint parent and child anchors are very close
rel_p = err * wp.normalize(world_com_c - world_com_p)
elif upper >= 0.0 and d > upper:
err = d - upper
if wp.abs(err) > 1e-9:
# compute gradients
linear_c = rel_p
linear_p = -linear_c
r_c = x_c - world_com_c
angular_p = -wp.cross(r_p, linear_c)
angular_c = wp.cross(r_c, linear_c)
# constraint time derivative
derr = (
wp.dot(linear_p, vel_p)
+ wp.dot(linear_c, vel_c)
+ wp.dot(angular_p, omega_p)
+ wp.dot(angular_c, omega_c)
)
lambda_in = 0.0
compliance = linear_compliance
ke = joint_target_ke[axis_start]
if ke > 0.0:
compliance = 1.0 / ke
damping = joint_target_kd[axis_start]
d_lambda = compute_positional_correction(
err,
derr,
pose_p,
pose_c,
m_inv_p,
m_inv_c,
I_inv_p,
I_inv_c,
linear_p,
linear_c,
angular_p,
angular_c,
lambda_in,
compliance,
damping,
dt,
)
lin_delta_p += linear_p * (d_lambda * linear_relaxation)
ang_delta_p += angular_p * (d_lambda * angular_relaxation)
lin_delta_c += linear_c * (d_lambda * linear_relaxation)
ang_delta_c += angular_c * (d_lambda * angular_relaxation)
else:
# compute joint target, stiffness, damping
ke_sum = float(0.0)
axis_limits = wp.spatial_vector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
axis_mode = wp.vec3i(0, 0, 0)
axis_target_ke_kd = wp.mat33(0.0)
# avoid a for loop here since local variables would need to be modified which is not yet differentiable
if lin_axis_count > 0:
axis = joint_axis[axis_start]
lo_temp = axis * joint_limit_lower[axis_start]
up_temp = axis * joint_limit_upper[axis_start]
axis_limits = wp.spatial_vector(vec_min(lo_temp, up_temp), vec_max(lo_temp, up_temp))
mode = joint_axis_mode[axis_start]
if mode != JOINT_MODE_FORCE: # position or velocity target
ke = joint_target_ke[axis_start]
kd = joint_target_kd[axis_start]
target = joint_act[axis_start]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if lin_axis_count > 1:
axis_idx = axis_start + 1
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_FORCE: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_act[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if lin_axis_count > 2:
axis_idx = axis_start + 2
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_FORCE: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_act[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
axis_target = axis_target_ke_kd[0]
axis_stiffness = axis_target_ke_kd[1]
axis_damping = axis_target_ke_kd[2]
if ke_sum > 0.0:
axis_target /= ke_sum
axis_limits_lower = wp.spatial_top(axis_limits)
axis_limits_upper = wp.spatial_bottom(axis_limits)
frame_p = wp.quat_to_matrix(wp.transform_get_rotation(X_wp))
# note that x_c appearing in both is correct
r_p = x_c - world_com_p
r_c = x_c - wp.transform_point(pose_c, com_c)
# for loop will be unrolled, so we can modify local variables
for dim in range(3):
e = rel_p[dim]
mode = axis_mode[dim]
# compute gradients
linear_c = wp.vec3(frame_p[0, dim], frame_p[1, dim], frame_p[2, dim])
linear_p = -linear_c
angular_p = -wp.cross(r_p, linear_c)
angular_c = wp.cross(r_c, linear_c)
# constraint time derivative
derr = (
wp.dot(linear_p, vel_p)
+ wp.dot(linear_c, vel_c)
+ wp.dot(angular_p, omega_p)
+ wp.dot(angular_c, omega_c)
)
err = 0.0
compliance = linear_compliance
damping = 0.0
# consider joint limits irrespective of axis mode
lower = axis_limits_lower[dim]
upper = axis_limits_upper[dim]
if e < lower:
err = e - lower
elif e > upper:
err = e - upper
else:
target = axis_target[dim]
if mode == JOINT_MODE_TARGET_POSITION:
target = wp.clamp(target, lower, upper)
if axis_stiffness[dim] > 0.0:
err = e - target
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
elif mode == JOINT_MODE_TARGET_VELOCITY:
if axis_stiffness[dim] > 0.0:
err = (derr - target) * dt
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
derr = 0.0
if wp.abs(err) > 1e-9:
lambda_in = 0.0
d_lambda = compute_positional_correction(
err,
derr,
pose_p,
pose_c,
m_inv_p,
m_inv_c,
I_inv_p,
I_inv_c,
linear_p,
linear_c,
angular_p,
angular_c,
lambda_in,
compliance,
damping,
dt,
)
lin_delta_p += linear_p * (d_lambda * linear_relaxation)
ang_delta_p += angular_p * (d_lambda * angular_relaxation)
lin_delta_c += linear_c * (d_lambda * linear_relaxation)
ang_delta_c += angular_c * (d_lambda * angular_relaxation)
if (
type == wp.sim.JOINT_FIXED
or type == wp.sim.JOINT_PRISMATIC
or type == wp.sim.JOINT_REVOLUTE
or type == wp.sim.JOINT_UNIVERSAL
or type == wp.sim.JOINT_COMPOUND
or type == wp.sim.JOINT_D6
):
# handle angular constraints
# local joint rotations
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
# make quats lie in same hemisphere
if wp.dot(q_p, q_c) < 0.0:
q_c *= -1.0
rel_q = wp.quat_inverse(q_p) * q_c
qtwist = wp.normalize(wp.quat(rel_q[0], 0.0, 0.0, rel_q[3]))
qswing = rel_q * wp.quat_inverse(qtwist)
# decompose to a compound rotation each axis
s = wp.sqrt(rel_q[0] * rel_q[0] + rel_q[3] * rel_q[3])
invs = 1.0 / s
invscube = invs * invs * invs
# handle axis-angle joints
# rescale twist from quaternion space to angular
err_0 = 2.0 * wp.asin(wp.clamp(qtwist[0], -1.0, 1.0))
err_1 = qswing[1]
err_2 = qswing[2]
# analytic gradients of swing-twist decomposition
grad_0 = wp.quat(invs - rel_q[0] * rel_q[0] * invscube, 0.0, 0.0, -(rel_q[3] * rel_q[0]) * invscube)
grad_1 = wp.quat(
-rel_q[3] * (rel_q[3] * rel_q[2] + rel_q[0] * rel_q[1]) * invscube,
rel_q[3] * invs,
-rel_q[0] * invs,
rel_q[0] * (rel_q[3] * rel_q[2] + rel_q[0] * rel_q[1]) * invscube,
)
grad_2 = wp.quat(
rel_q[3] * (rel_q[3] * rel_q[1] - rel_q[0] * rel_q[2]) * invscube,
rel_q[0] * invs,
rel_q[3] * invs,
rel_q[0] * (rel_q[2] * rel_q[0] - rel_q[3] * rel_q[1]) * invscube,
)
grad_0 *= 2.0 / wp.abs(qtwist[3])
# grad_0 *= 2.0 / wp.sqrt(1.0-qtwist[0]*qtwist[0]) # derivative of asin(x) = 1/sqrt(1-x^2)
# rescale swing
swing_sq = qswing[3] * qswing[3]
# if swing axis magnitude close to zero vector, just treat in quaternion space
angularEps = 1.0e-4
if swing_sq + angularEps < 1.0:
d = wp.sqrt(1.0 - qswing[3] * qswing[3])
theta = 2.0 * wp.acos(wp.clamp(qswing[3], -1.0, 1.0))
scale = theta / d
err_1 *= scale
err_2 *= scale
grad_1 *= scale
grad_2 *= scale
errs = wp.vec3(err_0, err_1, err_2)
grad_x = wp.vec3(grad_0[0], grad_1[0], grad_2[0])
grad_y = wp.vec3(grad_0[1], grad_1[1], grad_2[1])
grad_z = wp.vec3(grad_0[2], grad_1[2], grad_2[2])
grad_w = wp.vec3(grad_0[3], grad_1[3], grad_2[3])
# compute joint target, stiffness, damping
ke_sum = float(0.0)
axis_limits = wp.spatial_vector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
axis_mode = wp.vec3i(0, 0, 0)
axis_target_ke_kd = wp.mat33(0.0)
# avoid a for loop here since local variables would need to be modified which is not yet differentiable
if ang_axis_count > 0:
axis_idx = axis_start + lin_axis_count
axis = joint_axis[axis_idx]
lo_temp = axis * joint_limit_lower[axis_idx]
up_temp = axis * joint_limit_upper[axis_idx]
axis_limits = wp.spatial_vector(vec_min(lo_temp, up_temp), vec_max(lo_temp, up_temp))
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_FORCE: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_act[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if ang_axis_count > 1:
axis_idx = axis_start + lin_axis_count + 1
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_FORCE: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_act[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
if ang_axis_count > 2:
axis_idx = axis_start + lin_axis_count + 2
axis = joint_axis[axis_idx]
lower = joint_limit_lower[axis_idx]
upper = joint_limit_upper[axis_idx]
axis_limits = update_joint_axis_limits(axis, lower, upper, axis_limits)
mode = joint_axis_mode[axis_idx]
if mode != JOINT_MODE_FORCE: # position or velocity target
ke = joint_target_ke[axis_idx]
kd = joint_target_kd[axis_idx]
target = joint_act[axis_idx]
axis_mode = update_joint_axis_mode(mode, axis, axis_mode)
axis_target_ke_kd = update_joint_axis_target_ke_kd(axis, target, ke, kd, axis_target_ke_kd)
ke_sum += ke
axis_target = axis_target_ke_kd[0]
axis_stiffness = axis_target_ke_kd[1]
axis_damping = axis_target_ke_kd[2]
if ke_sum > 0.0:
axis_target /= ke_sum
axis_limits_lower = wp.spatial_top(axis_limits)
axis_limits_upper = wp.spatial_bottom(axis_limits)
# if type == wp.sim.JOINT_D6:
# wp.printf("axis_target: %f %f %f\t axis_stiffness: %f %f %f\t axis_damping: %f %f %f\t axis_limits_lower: %f %f %f \t axis_limits_upper: %f %f %f\n",
# axis_target[0], axis_target[1], axis_target[2],
# axis_stiffness[0], axis_stiffness[1], axis_stiffness[2],
# axis_damping[0], axis_damping[1], axis_damping[2],
# axis_limits_lower[0], axis_limits_lower[1], axis_limits_lower[2],
# axis_limits_upper[0], axis_limits_upper[1], axis_limits_upper[2])
# # wp.printf("wp.sqrt(1.0-qtwist[0]*qtwist[0]) = %f\n", wp.sqrt(1.0-qtwist[0]*qtwist[0]))
for dim in range(3):
e = errs[dim]
mode = axis_mode[dim]
# analytic gradients of swing-twist decomposition
grad = wp.quat(grad_x[dim], grad_y[dim], grad_z[dim], grad_w[dim])
quat_c = 0.5 * q_p * grad * wp.quat_inverse(q_c)
angular_c = wp.vec3(quat_c[0], quat_c[1], quat_c[2])
angular_p = -angular_c
# time derivative of the constraint
derr = wp.dot(angular_p, omega_p) + wp.dot(angular_c, omega_c)
err = 0.0
compliance = angular_compliance
damping = 0.0
# consider joint limits irrespective of mode
lower = axis_limits_lower[dim]
upper = axis_limits_upper[dim]
if e < lower:
err = e - lower
elif e > upper:
err = e - upper
else:
target = axis_target[dim]
if mode == JOINT_MODE_TARGET_POSITION:
target = wp.clamp(target, lower, upper)
if axis_stiffness[dim] > 0.0:
err = e - target
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
elif mode == JOINT_MODE_TARGET_VELOCITY:
if axis_stiffness[dim] > 0.0:
err = (derr - target) * dt
compliance = 1.0 / axis_stiffness[dim]
damping = axis_damping[dim]
derr = 0.0
d_lambda = (
compute_angular_correction(
err, derr, pose_p, pose_c, I_inv_p, I_inv_c, angular_p, angular_c, 0.0, compliance, damping, dt
)
* angular_relaxation
)
# update deltas
ang_delta_p += angular_p * d_lambda
ang_delta_c += angular_c * d_lambda
if id_p >= 0:
wp.atomic_add(deltas, id_p, wp.spatial_vector(ang_delta_p, lin_delta_p))
if id_c >= 0:
wp.atomic_add(deltas, id_c, wp.spatial_vector(ang_delta_c, lin_delta_c))
@wp.func
def compute_contact_constraint_delta(
err: float,
tf_a: wp.transform,
tf_b: wp.transform,
m_inv_a: float,
m_inv_b: float,
I_inv_a: wp.mat33,
I_inv_b: wp.mat33,
linear_a: wp.vec3,
linear_b: wp.vec3,
angular_a: wp.vec3,
angular_b: wp.vec3,
relaxation: float,
dt: float,
) -> float:
denom = 0.0
denom += wp.length_sq(linear_a) * m_inv_a
denom += wp.length_sq(linear_b) * m_inv_b
q1 = wp.transform_get_rotation(tf_a)
q2 = wp.transform_get_rotation(tf_b)
# Eq. 2-3 (make sure to project into the frame of the body)
rot_angular_a = wp.quat_rotate_inv(q1, angular_a)
rot_angular_b = wp.quat_rotate_inv(q2, angular_b)
denom += wp.dot(rot_angular_a, I_inv_a * rot_angular_a)
denom += wp.dot(rot_angular_b, I_inv_b * rot_angular_b)
delta_lambda = -err
if denom > 0.0:
delta_lambda /= dt * denom
return delta_lambda * relaxation
@wp.func
def compute_positional_correction(
err: float,
derr: float,
tf_a: wp.transform,
tf_b: wp.transform,
m_inv_a: float,
m_inv_b: float,
I_inv_a: wp.mat33,
I_inv_b: wp.mat33,
linear_a: wp.vec3,
linear_b: wp.vec3,
angular_a: wp.vec3,
angular_b: wp.vec3,
lambda_in: float,
compliance: float,
damping: float,
dt: float,
) -> float:
denom = 0.0
denom += wp.length_sq(linear_a) * m_inv_a
denom += wp.length_sq(linear_b) * m_inv_b
q1 = wp.transform_get_rotation(tf_a)
q2 = wp.transform_get_rotation(tf_b)
# Eq. 2-3 (make sure to project into the frame of the body)
rot_angular_a = wp.quat_rotate_inv(q1, angular_a)
rot_angular_b = wp.quat_rotate_inv(q2, angular_b)
denom += wp.dot(rot_angular_a, I_inv_a * rot_angular_a)
denom += wp.dot(rot_angular_b, I_inv_b * rot_angular_b)
alpha = compliance
gamma = compliance * damping
delta_lambda = -(err + alpha * lambda_in + gamma * derr)
if denom + alpha > 0.0:
delta_lambda /= (dt + gamma) * denom + alpha / dt
return delta_lambda
@wp.func
def compute_angular_correction(
err: float,
derr: float,
tf_a: wp.transform,
tf_b: wp.transform,
I_inv_a: wp.mat33,
I_inv_b: wp.mat33,
angular_a: wp.vec3,
angular_b: wp.vec3,
lambda_in: float,
compliance: float,
damping: float,
dt: float,
) -> float:
denom = 0.0
q1 = wp.transform_get_rotation(tf_a)
q2 = wp.transform_get_rotation(tf_b)
# Eq. 2-3 (make sure to project into the frame of the body)
rot_angular_a = wp.quat_rotate_inv(q1, angular_a)
rot_angular_b = wp.quat_rotate_inv(q2, angular_b)
denom += wp.dot(rot_angular_a, I_inv_a * rot_angular_a)
denom += wp.dot(rot_angular_b, I_inv_b * rot_angular_b)
alpha = compliance
gamma = compliance * damping
delta_lambda = -(err + alpha * lambda_in + gamma * derr)
if denom + alpha > 0.0:
delta_lambda /= (dt + gamma) * denom + alpha / dt
return delta_lambda
@wp.kernel
def solve_body_contact_positions(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
shape_body: wp.array(dtype=int),
contact_count: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_offset0: wp.array(dtype=wp.vec3),
contact_offset1: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_thickness: wp.array(dtype=float),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
relaxation: float,
dt: float,
contact_torsional_friction: float,
contact_rolling_friction: float,
# outputs
deltas: wp.array(dtype=wp.spatial_vector),
contact_inv_weight: wp.array(dtype=float),
):
tid = wp.tid()
count = contact_count[0]
if tid >= count:
return
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a == shape_b:
return
body_a = -1
if shape_a >= 0:
body_a = shape_body[shape_a]
body_b = -1
if shape_b >= 0:
body_b = shape_body[shape_b]
if body_a == body_b:
return
# find body to world transform
X_wb_a = wp.transform_identity()
X_wb_b = wp.transform_identity()
if body_a >= 0:
X_wb_a = body_q[body_a]
if body_b >= 0:
X_wb_b = body_q[body_b]
# compute body position in world space
bx_a = wp.transform_point(X_wb_a, contact_point0[tid])
bx_b = wp.transform_point(X_wb_b, contact_point1[tid])
thickness = contact_thickness[tid]
n = -contact_normal[tid]
d = wp.dot(n, bx_b - bx_a) - thickness
if d >= 0.0:
return
m_inv_a = 0.0
m_inv_b = 0.0
I_inv_a = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
I_inv_b = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
# center of mass in body frame
com_a = wp.vec3(0.0)
com_b = wp.vec3(0.0)
# body to world transform
X_wb_a = wp.transform_identity()
X_wb_b = wp.transform_identity()
# angular velocities
omega_a = wp.vec3(0.0)
omega_b = wp.vec3(0.0)
# contact offset in body frame
offset_a = contact_offset0[tid]
offset_b = contact_offset1[tid]
if body_a >= 0:
X_wb_a = body_q[body_a]
com_a = body_com[body_a]
m_inv_a = body_m_inv[body_a]
I_inv_a = body_I_inv[body_a]
omega_a = wp.spatial_top(body_qd[body_a])
if body_b >= 0:
X_wb_b = body_q[body_b]
com_b = body_com[body_b]
m_inv_b = body_m_inv[body_b]
I_inv_b = body_I_inv[body_b]
omega_b = wp.spatial_top(body_qd[body_b])
# use average contact material properties
mat_nonzero = 0
mu = 0.0
if shape_a >= 0:
mat_nonzero += 1
mu += shape_materials.mu[shape_a]
if shape_b >= 0:
mat_nonzero += 1
mu += shape_materials.mu[shape_b]
if mat_nonzero > 0:
mu /= float(mat_nonzero)
r_a = bx_a - wp.transform_point(X_wb_a, com_a)
r_b = bx_b - wp.transform_point(X_wb_b, com_b)
angular_a = -wp.cross(r_a, n)
angular_b = wp.cross(r_b, n)
if contact_inv_weight:
if body_a >= 0:
wp.atomic_add(contact_inv_weight, body_a, 1.0)
if body_b >= 0:
wp.atomic_add(contact_inv_weight, body_b, 1.0)
lambda_n = compute_contact_constraint_delta(
d, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, -n, n, angular_a, angular_b, relaxation, dt
)
lin_delta_a = -n * lambda_n
lin_delta_b = n * lambda_n
ang_delta_a = angular_a * lambda_n
ang_delta_b = angular_b * lambda_n
# linear friction
if mu > 0.0:
# add on displacement from surface offsets, this ensures we include any rotational effects due to thickness from feature
# need to use the current rotation to account for friction due to angular effects (e.g.: slipping contact)
bx_a += wp.transform_vector(X_wb_a, offset_a)
bx_b += wp.transform_vector(X_wb_b, offset_b)
# update delta
delta = bx_b - bx_a
friction_delta = delta - wp.dot(n, delta) * n
perp = wp.normalize(friction_delta)
r_a = bx_a - wp.transform_point(X_wb_a, com_a)
r_b = bx_b - wp.transform_point(X_wb_b, com_b)
angular_a = -wp.cross(r_a, perp)
angular_b = wp.cross(r_b, perp)
err = wp.length(friction_delta)
if err > 0.0:
lambda_fr = compute_contact_constraint_delta(
err, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, -perp, perp, angular_a, angular_b, 1.0, dt
)
# limit friction based on incremental normal force, good approximation to limiting on total force
lambda_fr = wp.max(lambda_fr, -lambda_n * mu)
lin_delta_a -= perp * lambda_fr
lin_delta_b += perp * lambda_fr
ang_delta_a += angular_a * lambda_fr
ang_delta_b += angular_b * lambda_fr
torsional_friction = mu * contact_torsional_friction
delta_omega = omega_b - omega_a
if torsional_friction > 0.0:
err = wp.dot(delta_omega, n) * dt
if wp.abs(err) > 0.0:
lin = wp.vec3(0.0)
lambda_torsion = compute_contact_constraint_delta(
err, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, lin, lin, -n, n, 1.0, dt
)
lambda_torsion = wp.clamp(lambda_torsion, -lambda_n * torsional_friction, lambda_n * torsional_friction)
ang_delta_a -= n * lambda_torsion
ang_delta_b += n * lambda_torsion
rolling_friction = mu * contact_rolling_friction
if rolling_friction > 0.0:
delta_omega -= wp.dot(n, delta_omega) * n
err = wp.length(delta_omega) * dt
if err > 0.0:
lin = wp.vec3(0.0)
roll_n = wp.normalize(delta_omega)
lambda_roll = compute_contact_constraint_delta(
err, X_wb_a, X_wb_b, m_inv_a, m_inv_b, I_inv_a, I_inv_b, lin, lin, -roll_n, roll_n, 1.0, dt
)
lambda_roll = wp.max(lambda_roll, -lambda_n * rolling_friction)
ang_delta_a -= roll_n * lambda_roll
ang_delta_b += roll_n * lambda_roll
if body_a >= 0:
wp.atomic_add(deltas, body_a, wp.spatial_vector(ang_delta_a, lin_delta_a))
if body_b >= 0:
wp.atomic_add(deltas, body_b, wp.spatial_vector(ang_delta_b, lin_delta_b))
@wp.kernel
def update_body_velocities(
poses: wp.array(dtype=wp.transform),
poses_prev: wp.array(dtype=wp.transform),
body_com: wp.array(dtype=wp.vec3),
dt: float,
qd_out: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
pose = poses[tid]
pose_prev = poses_prev[tid]
x = wp.transform_get_translation(pose)
x_prev = wp.transform_get_translation(pose_prev)
q = wp.transform_get_rotation(pose)
q_prev = wp.transform_get_rotation(pose_prev)
# Update body velocities according to Alg. 2
# XXX we consider the body COM as the origin of the body frame
x_com = x + wp.quat_rotate(q, body_com[tid])
x_com_prev = x_prev + wp.quat_rotate(q_prev, body_com[tid])
# XXX consider the velocity of the COM
v = (x_com - x_com_prev) / dt
dq = q * wp.quat_inverse(q_prev)
omega = 2.0 / dt * wp.vec3(dq[0], dq[1], dq[2])
if dq[3] < 0.0:
omega = -omega
qd_out[tid] = wp.spatial_vector(omega, v)
@wp.kernel
def apply_rigid_restitution(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_q_prev: wp.array(dtype=wp.transform),
body_qd_prev: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
body_m_inv: wp.array(dtype=float),
body_I_inv: wp.array(dtype=wp.mat33),
shape_body: wp.array(dtype=int),
contact_count: wp.array(dtype=int),
contact_normal: wp.array(dtype=wp.vec3),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_offset0: wp.array(dtype=wp.vec3),
contact_offset1: wp.array(dtype=wp.vec3),
contact_thickness: wp.array(dtype=float),
contact_inv_weight: wp.array(dtype=float),
gravity: wp.vec3,
dt: float,
# outputs
deltas: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
count = contact_count[0]
if tid >= count:
return
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a == shape_b:
return
body_a = -1
body_b = -1
# use average contact material properties
mat_nonzero = 0
restitution = 0.0
if shape_a >= 0:
mat_nonzero += 1
restitution += shape_materials.restitution[shape_a]
body_a = shape_body[shape_a]
if shape_b >= 0:
mat_nonzero += 1
restitution += shape_materials.restitution[shape_b]
body_b = shape_body[shape_b]
if mat_nonzero > 0:
restitution /= float(mat_nonzero)
if body_a == body_b:
return
m_inv_a = 0.0
m_inv_b = 0.0
I_inv_a = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
I_inv_b = wp.mat33(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
# body to world transform
X_wb_a_prev = wp.transform_identity()
X_wb_b_prev = wp.transform_identity()
# center of mass in body frame
com_a = wp.vec3(0.0)
com_b = wp.vec3(0.0)
# previous velocity at contact points
v_a = wp.vec3(0.0)
v_b = wp.vec3(0.0)
# new velocity at contact points
v_a_new = wp.vec3(0.0)
v_b_new = wp.vec3(0.0)
# inverse mass used to compute the impulse
inv_mass = 0.0
if body_a >= 0:
X_wb_a_prev = body_q_prev[body_a]
# X_wb_a = body_q[body_a]
m_inv_a = body_m_inv[body_a]
I_inv_a = body_I_inv[body_a]
com_a = body_com[body_a]
if body_b >= 0:
X_wb_b_prev = body_q_prev[body_b]
# X_wb_b = body_q[body_b]
m_inv_b = body_m_inv[body_b]
I_inv_b = body_I_inv[body_b]
com_b = body_com[body_b]
# compute body position in world space
bx_a = wp.transform_point(X_wb_a_prev, contact_point0[tid] + contact_offset0[tid])
bx_b = wp.transform_point(X_wb_b_prev, contact_point1[tid] + contact_offset1[tid])
thickness = contact_thickness[tid]
n = contact_normal[tid]
d = -wp.dot(n, bx_b - bx_a) - thickness
if d >= 0.0:
return
r_a = bx_a - wp.transform_point(X_wb_a_prev, com_a)
r_b = bx_b - wp.transform_point(X_wb_b_prev, com_b)
rxn_a = wp.vec3(0.0)
rxn_b = wp.vec3(0.0)
if body_a >= 0:
v_a = velocity_at_point(body_qd_prev[body_a], r_a) + gravity * dt
v_a_new = velocity_at_point(body_qd[body_a], r_a)
q_a = wp.transform_get_rotation(X_wb_a_prev)
rxn_a = wp.quat_rotate_inv(q_a, wp.cross(r_a, n))
# Eq. 2
inv_mass_a = m_inv_a + wp.dot(rxn_a, I_inv_a * rxn_a)
# if contact_inv_weight:
# if contact_inv_weight[body_a] > 0.0:
# inv_mass_a *= contact_inv_weight[body_a]
inv_mass += inv_mass_a
if body_b >= 0:
v_b = velocity_at_point(body_qd_prev[body_b], r_b) + gravity * dt
v_b_new = velocity_at_point(body_qd[body_b], r_b)
q_b = wp.transform_get_rotation(X_wb_b_prev)
rxn_b = wp.quat_rotate_inv(q_b, wp.cross(r_b, n))
# Eq. 3
inv_mass_b = m_inv_b + wp.dot(rxn_b, I_inv_b * rxn_b)
# if contact_inv_weight:
# if contact_inv_weight[body_b] > 0.0:
# inv_mass_b *= contact_inv_weight[body_b]
inv_mass += inv_mass_b
if inv_mass == 0.0:
return
# Eq. 29
rel_vel_old = wp.dot(n, v_a - v_b)
rel_vel_new = wp.dot(n, v_a_new - v_b_new)
if rel_vel_old >= 0.0:
return
# Eq. 34
dv = (-rel_vel_new - restitution * rel_vel_old) / inv_mass
# Eq. 33
if body_a >= 0:
dv_a = dv
# if contact_inv_weight:
# if contact_inv_weight[body_a] > 0.0:
# dv_a *= contact_inv_weight[body_a]
q_a = wp.transform_get_rotation(X_wb_a_prev)
dq = wp.quat_rotate(q_a, I_inv_a * rxn_a * dv_a)
wp.atomic_add(deltas, body_a, wp.spatial_vector(dq, n * m_inv_a * dv_a))
if body_b >= 0:
dv_b = -dv
# if contact_inv_weight:
# if contact_inv_weight[body_b] > 0.0:
# dv_b *= contact_inv_weight[body_b]
q_b = wp.transform_get_rotation(X_wb_b_prev)
dq = wp.quat_rotate(q_b, I_inv_b * rxn_b * dv_b)
wp.atomic_add(deltas, body_b, wp.spatial_vector(dq, n * m_inv_b * dv_b))
class XPBDIntegrator(Integrator):
"""An implicit integrator using eXtended Position-Based Dynamics (XPBD) for rigid and soft body simulation.
References:
- Miles Macklin, Matthias Müller, and Nuttapong Chentanez. 2016. XPBD: position-based simulation of compliant constrained dynamics. In Proceedings of the 9th International Conference on Motion in Games (MIG '16). Association for Computing Machinery, New York, NY, USA, 49-54. https://doi.org/10.1145/2994258.2994272
- Matthias Müller, Miles Macklin, Nuttapong Chentanez, Stefan Jeschke, and Tae-Yong Kim. 2020. Detailed rigid body simulation with extended position based dynamics. In Proceedings of the ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA '20). Eurographics Association, Goslar, DEU, Article 10, 1-12. https://doi.org/10.1111/cgf.14105
After constructing :class:`Model`, :class:`State`, and :class:`Control` (optional) objects, this time-integrator
may be used to advance the simulation state forward in time.
Example
-------
.. code-block:: python
integrator = wp.XPBDIntegrator()
# simulation loop
for i in range(100):
state = integrator.simulate(model, state_in, state_out, dt, control)
"""
def __init__(
self,
iterations=2,
soft_body_relaxation=0.9,
soft_contact_relaxation=0.9,
joint_linear_relaxation=0.7,
joint_angular_relaxation=0.4,
rigid_contact_relaxation=0.8,
rigid_contact_con_weighting=True,
angular_damping=0.0,
enable_restitution=False,
):
self.iterations = iterations
self.soft_body_relaxation = soft_body_relaxation
self.soft_contact_relaxation = soft_contact_relaxation
self.joint_linear_relaxation = joint_linear_relaxation
self.joint_angular_relaxation = joint_angular_relaxation
self.rigid_contact_relaxation = rigid_contact_relaxation
self.rigid_contact_con_weighting = rigid_contact_con_weighting
self.angular_damping = angular_damping
self.enable_restitution = enable_restitution
self.compute_body_velocity_from_position_delta = False
# helper variables to track constraint resolution vars
self._particle_delta_counter = 0
self._body_delta_counter = 0
def apply_particle_deltas(
self,
model: Model,
state_in: State,
state_out: State,
particle_deltas: wp.array,
dt: float,
):
if state_in.requires_grad:
particle_q = state_out.particle_q
# allocate new particle arrays so gradients can be tracked correctly without overwriting
new_particle_q = wp.empty_like(state_out.particle_q)
new_particle_qd = wp.empty_like(state_out.particle_qd)
self._particle_delta_counter += 1
else:
if self._particle_delta_counter == 0:
particle_q = state_out.particle_q
new_particle_q = state_in.particle_q
new_particle_qd = state_in.particle_qd
else:
particle_q = state_in.particle_q
new_particle_q = state_out.particle_q
new_particle_qd = state_out.particle_qd
self._particle_delta_counter = 1 - self._particle_delta_counter
wp.launch(
kernel=apply_particle_deltas,
dim=model.particle_count,
inputs=[
self.particle_q_init,
particle_q,
model.particle_flags,
particle_deltas,
dt,
model.particle_max_velocity,
],
outputs=[new_particle_q, new_particle_qd],
device=model.device,
)
if state_in.requires_grad:
state_out.particle_q = new_particle_q
state_out.particle_qd = new_particle_qd
return new_particle_q, new_particle_qd
def apply_body_deltas(
self,
model: Model,
state_in: State,
state_out: State,
body_deltas: wp.array,
dt: float,
rigid_contact_inv_weight: wp.array = None,
):
with wp.ScopedTimer("apply_body_deltas", False):
if state_in.requires_grad:
body_q = state_out.body_q
body_qd = state_out.body_qd
new_body_q = wp.clone(body_q)
new_body_qd = wp.clone(body_qd)
self._body_delta_counter += 1
else:
if self._body_delta_counter == 0:
body_q = state_out.body_q
body_qd = state_out.body_qd
new_body_q = state_in.body_q
new_body_qd = state_in.body_qd
else:
body_q = state_in.body_q
body_qd = state_in.body_qd
new_body_q = state_out.body_q
new_body_qd = state_out.body_qd
self._body_delta_counter = 1 - self._body_delta_counter
wp.launch(
kernel=apply_body_deltas,
dim=model.body_count,
inputs=[
body_q,
body_qd,
model.body_com,
model.body_inertia,
model.body_inv_mass,
model.body_inv_inertia,
body_deltas,
rigid_contact_inv_weight,
dt,
],
outputs=[
new_body_q,
new_body_qd,
],
device=model.device,
)
if state_in.requires_grad:
state_out.body_q = new_body_q
state_out.body_qd = new_body_qd
return new_body_q, new_body_qd
def simulate(self, model: Model, state_in: State, state_out: State, dt: float, control: Control = None):
requires_grad = state_in.requires_grad
self._particle_delta_counter = 0
self._body_delta_counter = 0
particle_q = None
particle_qd = None
particle_deltas = None
body_q = None
body_qd = None
body_deltas = None
rigid_contact_inv_weight = None
if model.rigid_contact_max > 0:
if self.rigid_contact_con_weighting:
rigid_contact_inv_weight = wp.zeros_like(model.rigid_contact_thickness)
rigid_contact_inv_weight_init = None
if control is None:
control = model.control(clone_variables=False)
with wp.ScopedTimer("simulate", False):
if model.particle_count:
if requires_grad:
particle_q = state_out.particle_q
particle_qd = state_out.particle_qd
else:
particle_q = state_out.particle_q
particle_qd = state_out.particle_qd
self.particle_q_init = wp.clone(state_in.particle_q)
if self.enable_restitution:
self.particle_qd_init = wp.clone(state_in.particle_qd)
particle_deltas = wp.empty_like(state_out.particle_qd)
self.integrate_particles(model, state_in, state_out, dt)
if model.body_count:
body_q = state_out.body_q
body_qd = state_out.body_qd
if self.compute_body_velocity_from_position_delta or self.enable_restitution:
body_q_init = wp.clone(state_in.body_q)
body_qd_init = wp.clone(state_in.body_qd)
body_deltas = wp.empty_like(state_out.body_qd)
if model.joint_count:
wp.launch(
kernel=apply_joint_torques,
dim=model.joint_count,
inputs=[
state_in.body_q,
model.body_com,
model.joint_q_start,
model.joint_qd_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_axis,
model.joint_axis_mode,
control.joint_act,
],
outputs=[state_in.body_f],
device=model.device,
)
self.integrate_bodies(model, state_in, state_out, dt, self.angular_damping)
spring_constraint_lambdas = None
if model.spring_count:
spring_constraint_lambdas = wp.empty_like(model.spring_rest_length)
edge_constraint_lambdas = None
if model.edge_count:
edge_constraint_lambdas = wp.empty_like(model.edge_rest_angle)
for i in range(self.iterations):
with wp.ScopedTimer(f"iteration_{i}", False):
if model.body_count:
if requires_grad and i > 0:
body_deltas = wp.zeros_like(body_deltas)
else:
body_deltas.zero_()
if model.particle_count:
if requires_grad and i > 0:
particle_deltas = wp.zeros_like(particle_deltas)
else:
particle_deltas.zero_()
# particle ground contact
if model.ground:
wp.launch(
kernel=solve_particle_ground_contacts,
dim=model.particle_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
model.soft_contact_ke,
model.soft_contact_kd,
model.soft_contact_kf,
model.soft_contact_mu,
model.ground_plane,
dt,
self.soft_contact_relaxation,
],
outputs=[particle_deltas],
device=model.device,
)
# particle-rigid body contacts (besides ground plane)
if model.shape_count > 1:
wp.launch(
kernel=solve_particle_shape_contacts,
dim=model.soft_contact_max,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
body_q,
body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.shape_body,
model.shape_materials,
model.soft_contact_mu,
model.particle_adhesion,
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
model.soft_contact_max,
dt,
self.soft_contact_relaxation,
],
# outputs
outputs=[particle_deltas, body_deltas],
device=model.device,
)
if model.particle_max_radius > 0.0 and model.particle_count > 1:
# assert model.particle_grid.reserved, "model.particle_grid must be built, see HashGrid.build()"
wp.launch(
kernel=solve_particle_particle_contacts,
dim=model.particle_count,
inputs=[
model.particle_grid.id,
particle_q,
particle_qd,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
model.particle_mu,
model.particle_cohesion,
model.particle_max_radius,
dt,
self.soft_contact_relaxation,
],
outputs=[particle_deltas],
device=model.device,
)
# distance constraints
if model.spring_count:
spring_constraint_lambdas.zero_()
wp.launch(
kernel=solve_springs,
dim=model.spring_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.spring_indices,
model.spring_rest_length,
model.spring_stiffness,
model.spring_damping,
dt,
spring_constraint_lambdas,
],
outputs=[particle_deltas],
device=model.device,
)
# bending constraints
if model.edge_count:
edge_constraint_lambdas.zero_()
wp.launch(
kernel=bending_constraint,
dim=model.edge_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.edge_indices,
model.edge_rest_angle,
model.edge_bending_properties,
dt,
edge_constraint_lambdas,
],
outputs=[particle_deltas],
device=model.device,
)
# tetrahedral FEM
if model.tet_count:
wp.launch(
kernel=solve_tetrahedra,
dim=model.tet_count,
inputs=[
particle_q,
particle_qd,
model.particle_inv_mass,
model.tet_indices,
model.tet_poses,
model.tet_activations,
model.tet_materials,
dt,
self.soft_body_relaxation,
],
outputs=[particle_deltas],
device=model.device,
)
particle_q, particle_qd = self.apply_particle_deltas(
model, state_in, state_out, particle_deltas, dt
)
# handle rigid bodies
# ----------------------------
if model.joint_count:
# wp.launch(
# kernel=solve_simple_body_joints,
# dim=model.joint_count,
# inputs=[
# body_q,
# body_qd,
# model.body_com,
# model.body_inv_mass,
# model.body_inv_inertia,
# model.joint_type,
# model.joint_enabled,
# model.joint_parent,
# model.joint_child,
# model.joint_X_p,
# model.joint_X_c,
# model.joint_limit_lower,
# model.joint_limit_upper,
# model.joint_axis_start,
# model.joint_axis_dim,
# model.joint_axis_mode,
# model.joint_axis,
# control.joint_target,
# model.joint_target_ke,
# model.joint_target_kd,
# model.joint_linear_compliance,
# model.joint_angular_compliance,
# self.joint_angular_relaxation,
# self.joint_linear_relaxation,
# dt,
# ],
# outputs=[body_deltas],
# device=model.device,
# )
wp.launch(
kernel=solve_body_joints,
dim=model.joint_count,
inputs=[
body_q,
body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.joint_type,
model.joint_enabled,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_limit_lower,
model.joint_limit_upper,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_axis_mode,
model.joint_axis,
control.joint_act,
model.joint_target_ke,
model.joint_target_kd,
model.joint_linear_compliance,
model.joint_angular_compliance,
self.joint_angular_relaxation,
self.joint_linear_relaxation,
dt,
],
outputs=[body_deltas],
device=model.device,
)
body_q, body_qd = self.apply_body_deltas(model, state_in, state_out, body_deltas, dt)
# Solve rigid contact constraints
if model.rigid_contact_max and (
model.ground and model.shape_ground_contact_pair_count or model.shape_contact_pair_count
):
if self.rigid_contact_con_weighting:
rigid_contact_inv_weight.zero_()
body_deltas.zero_()
wp.launch(
kernel=solve_body_contact_positions,
dim=model.rigid_contact_max,
inputs=[
body_q,
body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.shape_body,
model.rigid_contact_count,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_offset0,
model.rigid_contact_offset1,
model.rigid_contact_normal,
model.rigid_contact_thickness,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.shape_materials,
self.rigid_contact_relaxation,
dt,
model.rigid_contact_torsional_friction,
model.rigid_contact_rolling_friction,
],
outputs=[
body_deltas,
rigid_contact_inv_weight,
],
device=model.device,
)
# if model.rigid_contact_count.numpy()[0] > 0:
# print("rigid_contact_count:", model.rigid_contact_count.numpy().flatten())
# # print("rigid_active_contact_distance:", rigid_active_contact_distance.numpy().flatten())
# # print("rigid_active_contact_point0:", rigid_active_contact_point0.numpy().flatten())
# # print("rigid_active_contact_point1:", rigid_active_contact_point1.numpy().flatten())
# print("body_deltas:", body_deltas.numpy().flatten())
# print(rigid_active_contact_distance.numpy().flatten())
if self.enable_restitution and i == 0:
# remember contact constraint weighting from the first iteration
if self.rigid_contact_con_weighting:
rigid_contact_inv_weight_init = wp.clone(rigid_contact_inv_weight)
else:
rigid_contact_inv_weight_init = None
body_q, body_qd = self.apply_body_deltas(
model, state_in, state_out, body_deltas, dt, rigid_contact_inv_weight
)
if model.particle_count:
if particle_q.ptr != state_out.particle_q.ptr:
state_out.particle_q.assign(particle_q)
state_out.particle_qd.assign(particle_qd)
if model.body_count:
if body_q.ptr != state_out.body_q.ptr:
state_out.body_q.assign(body_q)
state_out.body_qd.assign(body_qd)
# update body velocities from position changes
if self.compute_body_velocity_from_position_delta and model.body_count and not requires_grad:
# causes gradient issues (probably due to numerical problems
# when computing velocities from position changes)
if requires_grad:
out_body_qd = wp.clone(state_out.body_qd)
else:
out_body_qd = state_out.body_qd
# update body velocities
wp.launch(
kernel=update_body_velocities,
dim=model.body_count,
inputs=[state_out.body_q, body_q_init, model.body_com, dt],
outputs=[out_body_qd],
device=model.device,
)
if self.enable_restitution:
if model.particle_count:
wp.launch(
kernel=apply_particle_shape_restitution,
dim=model.particle_count,
inputs=[
particle_q,
particle_qd,
self.particle_q_init,
self.particle_qd_init,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
body_q,
body_qd,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.shape_body,
model.shape_materials,
model.particle_adhesion,
model.soft_contact_restitution,
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
model.soft_contact_max,
dt,
self.soft_contact_relaxation,
],
outputs=[state_out.particle_qd],
device=model.device,
)
if model.ground:
wp.launch(
kernel=apply_particle_ground_restitution,
dim=model.particle_count,
inputs=[
particle_q,
particle_qd,
self.particle_q_init,
self.particle_qd_init,
model.particle_inv_mass,
model.particle_radius,
model.particle_flags,
model.particle_adhesion,
model.soft_contact_restitution,
model.ground_plane,
dt,
self.soft_contact_relaxation,
],
outputs=[state_out.particle_qd],
device=model.device,
)
if model.body_count:
body_deltas.zero_()
wp.launch(
kernel=apply_rigid_restitution,
dim=model.rigid_contact_max,
inputs=[
state_out.body_q,
state_out.body_qd,
body_q_init,
body_qd_init,
model.body_com,
model.body_inv_mass,
model.body_inv_inertia,
model.shape_body,
model.rigid_contact_count,
model.rigid_contact_normal,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.shape_materials,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_offset0,
model.rigid_contact_offset1,
model.rigid_contact_thickness,
rigid_contact_inv_weight_init,
model.gravity,
dt,
],
outputs=[
body_deltas,
],
device=model.device,
)
wp.launch(
kernel=apply_body_delta_velocities,
dim=model.body_count,
inputs=[
body_deltas,
],
outputs=[state_out.body_qd],
device=model.device,
)
return state_out
| 115,420 | Python | 34.029135 | 354 | 0.512823 |
NVIDIA/warp/warp/sim/particles.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from .model import PARTICLE_FLAG_ACTIVE
@wp.func
def particle_force(n: wp.vec3, v: wp.vec3, c: float, k_n: float, k_d: float, k_f: float, k_mu: float):
# compute normal and tangential friction force for a single contact
vn = wp.dot(n, v)
jn = c * k_n
jd = min(vn, 0.0) * k_d
# contact force
fn = jn + jd
# friction force
vt = v - n * vn
vs = wp.length(vt)
if vs > 0.0:
vt = vt / vs
# Coulomb condition
ft = wp.min(vs * k_f, k_mu * wp.abs(fn))
# total force
return -n * fn - vt * ft
@wp.kernel
def eval_particle_forces_kernel(
grid: wp.uint64,
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
k_contact: float,
k_damp: float,
k_friction: float,
k_mu: float,
k_cohesion: float,
max_radius: float,
# outputs
particle_f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
# order threads by cell
i = wp.hash_grid_point_id(grid, tid)
if i == -1:
# hash grid has not been built yet
return
if (particle_flags[i] & PARTICLE_FLAG_ACTIVE) == 0:
return
x = particle_x[i]
v = particle_v[i]
radius = particle_radius[i]
f = wp.vec3()
# particle contact
query = wp.hash_grid_query(grid, x, radius + max_radius + k_cohesion)
index = int(0)
count = int(0)
while wp.hash_grid_query_next(query, index):
if (particle_flags[index] & PARTICLE_FLAG_ACTIVE) != 0 and index != i:
# compute distance to point
n = x - particle_x[index]
d = wp.length(n)
err = d - radius - particle_radius[index]
count += 1
if err <= k_cohesion:
n = n / d
vrel = v - particle_v[index]
f = f + particle_force(n, vrel, err, k_contact, k_damp, k_friction, k_mu)
particle_f[i] = f
def eval_particle_forces(model, state, forces):
if model.particle_count > 1 and model.particle_max_radius > 0.0:
wp.launch(
kernel=eval_particle_forces_kernel,
dim=model.particle_count,
inputs=[
model.particle_grid.id,
state.particle_q,
state.particle_qd,
model.particle_radius,
model.particle_flags,
model.particle_ke,
model.particle_kd,
model.particle_kf,
model.particle_mu,
model.particle_cohesion,
model.particle_max_radius,
],
outputs=[forces],
device=model.device,
)
| 3,165 | Python | 26.77193 | 102 | 0.576935 |
NVIDIA/warp/warp/sim/collide.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""
Collision handling functions and kernels.
"""
import warp as wp
from .model import PARTICLE_FLAG_ACTIVE, ModelShapeGeometry
@wp.func
def triangle_closest_point_barycentric(a: wp.vec3, b: wp.vec3, c: wp.vec3, p: wp.vec3):
ab = b - a
ac = c - a
ap = p - a
d1 = wp.dot(ab, ap)
d2 = wp.dot(ac, ap)
if d1 <= 0.0 and d2 <= 0.0:
return wp.vec3(1.0, 0.0, 0.0)
bp = p - b
d3 = wp.dot(ab, bp)
d4 = wp.dot(ac, bp)
if d3 >= 0.0 and d4 <= d3:
return wp.vec3(0.0, 1.0, 0.0)
vc = d1 * d4 - d3 * d2
v = d1 / (d1 - d3)
if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0:
return wp.vec3(1.0 - v, v, 0.0)
cp = p - c
d5 = wp.dot(ab, cp)
d6 = wp.dot(ac, cp)
if d6 >= 0.0 and d5 <= d6:
return wp.vec3(0.0, 0.0, 1.0)
vb = d5 * d2 - d1 * d6
w = d2 / (d2 - d6)
if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0:
return wp.vec3(1.0 - w, 0.0, w)
va = d3 * d6 - d5 * d4
w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0:
return wp.vec3(0.0, w, 1.0 - w)
denom = 1.0 / (va + vb + vc)
v = vb * denom
w = vc * denom
return wp.vec3(1.0 - v - w, v, w)
@wp.func
def sphere_sdf(center: wp.vec3, radius: float, p: wp.vec3):
return wp.length(p - center) - radius
@wp.func
def sphere_sdf_grad(center: wp.vec3, radius: float, p: wp.vec3):
return wp.normalize(p - center)
@wp.func
def box_sdf(upper: wp.vec3, p: wp.vec3):
# adapted from https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
qx = abs(p[0]) - upper[0]
qy = abs(p[1]) - upper[1]
qz = abs(p[2]) - upper[2]
e = wp.vec3(wp.max(qx, 0.0), wp.max(qy, 0.0), wp.max(qz, 0.0))
return wp.length(e) + wp.min(wp.max(qx, wp.max(qy, qz)), 0.0)
@wp.func
def box_sdf_grad(upper: wp.vec3, p: wp.vec3):
qx = abs(p[0]) - upper[0]
qy = abs(p[1]) - upper[1]
qz = abs(p[2]) - upper[2]
# exterior case
if qx > 0.0 or qy > 0.0 or qz > 0.0:
x = wp.clamp(p[0], -upper[0], upper[0])
y = wp.clamp(p[1], -upper[1], upper[1])
z = wp.clamp(p[2], -upper[2], upper[2])
return wp.normalize(p - wp.vec3(x, y, z))
sx = wp.sign(p[0])
sy = wp.sign(p[1])
sz = wp.sign(p[2])
# x projection
if qx > qy and qx > qz or qy == 0.0 and qz == 0.0:
return wp.vec3(sx, 0.0, 0.0)
# y projection
if qy > qx and qy > qz or qx == 0.0 and qz == 0.0:
return wp.vec3(0.0, sy, 0.0)
# z projection
return wp.vec3(0.0, 0.0, sz)
@wp.func
def capsule_sdf(radius: float, half_height: float, p: wp.vec3):
if p[1] > half_height:
return wp.length(wp.vec3(p[0], p[1] - half_height, p[2])) - radius
if p[1] < -half_height:
return wp.length(wp.vec3(p[0], p[1] + half_height, p[2])) - radius
return wp.length(wp.vec3(p[0], 0.0, p[2])) - radius
@wp.func
def capsule_sdf_grad(radius: float, half_height: float, p: wp.vec3):
if p[1] > half_height:
return wp.normalize(wp.vec3(p[0], p[1] - half_height, p[2]))
if p[1] < -half_height:
return wp.normalize(wp.vec3(p[0], p[1] + half_height, p[2]))
return wp.normalize(wp.vec3(p[0], 0.0, p[2]))
@wp.func
def cylinder_sdf(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius
dy = wp.abs(p[1]) - half_height
return wp.min(wp.max(dx, dy), 0.0) + wp.length(wp.vec2(wp.max(dx, 0.0), wp.max(dy, 0.0)))
@wp.func
def cylinder_sdf_grad(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius
dy = wp.abs(p[1]) - half_height
if dx > dy:
return wp.normalize(wp.vec3(p[0], 0.0, p[2]))
return wp.vec3(0.0, wp.sign(p[1]), 0.0)
@wp.func
def cone_sdf(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius * (p[1] + half_height) / (2.0 * half_height)
dy = wp.abs(p[1]) - half_height
return wp.min(wp.max(dx, dy), 0.0) + wp.length(wp.vec2(wp.max(dx, 0.0), wp.max(dy, 0.0)))
@wp.func
def cone_sdf_grad(radius: float, half_height: float, p: wp.vec3):
dx = wp.length(wp.vec3(p[0], 0.0, p[2])) - radius * (p[1] + half_height) / (2.0 * half_height)
dy = wp.abs(p[1]) - half_height
if dy < 0.0 or dx == 0.0:
return wp.vec3(0.0, wp.sign(p[1]), 0.0)
return wp.normalize(wp.vec3(p[0], 0.0, p[2])) + wp.vec3(0.0, radius / (2.0 * half_height), 0.0)
@wp.func
def plane_sdf(width: float, length: float, p: wp.vec3):
# SDF for a quad in the xz plane
if width > 0.0 and length > 0.0:
d = wp.max(wp.abs(p[0]) - width, wp.abs(p[2]) - length)
return wp.max(d, wp.abs(p[1]))
return p[1]
@wp.func
def closest_point_plane(width: float, length: float, point: wp.vec3):
# projects the point onto the quad in the xz plane (if width and length > 0.0, otherwise the plane is infinite)
if width > 0.0:
x = wp.clamp(point[0], -width, width)
else:
x = point[0]
if length > 0.0:
z = wp.clamp(point[2], -length, length)
else:
z = point[2]
return wp.vec3(x, 0.0, z)
@wp.func
def closest_point_line_segment(a: wp.vec3, b: wp.vec3, point: wp.vec3):
ab = b - a
ap = point - a
t = wp.dot(ap, ab) / wp.dot(ab, ab)
t = wp.clamp(t, 0.0, 1.0)
return a + t * ab
@wp.func
def closest_point_box(upper: wp.vec3, point: wp.vec3):
# closest point to box surface
x = wp.clamp(point[0], -upper[0], upper[0])
y = wp.clamp(point[1], -upper[1], upper[1])
z = wp.clamp(point[2], -upper[2], upper[2])
if wp.abs(point[0]) <= upper[0] and wp.abs(point[1]) <= upper[1] and wp.abs(point[2]) <= upper[2]:
# the point is inside, find closest face
sx = wp.abs(wp.abs(point[0]) - upper[0])
sy = wp.abs(wp.abs(point[1]) - upper[1])
sz = wp.abs(wp.abs(point[2]) - upper[2])
# return closest point on closest side, handle corner cases
if sx < sy and sx < sz or sy == 0.0 and sz == 0.0:
x = wp.sign(point[0]) * upper[0]
elif sy < sx and sy < sz or sx == 0.0 and sz == 0.0:
y = wp.sign(point[1]) * upper[1]
else:
z = wp.sign(point[2]) * upper[2]
return wp.vec3(x, y, z)
@wp.func
def get_box_vertex(point_id: int, upper: wp.vec3):
# box vertex numbering:
# 6---7
# |\ |\ y
# | 2-+-3 |
# 4-+-5 | z \|
# \| \| o---x
# 0---1
# get the vertex of the box given its ID (0-7)
sign_x = float(point_id % 2) * 2.0 - 1.0
sign_y = float((point_id // 2) % 2) * 2.0 - 1.0
sign_z = float((point_id // 4) % 2) * 2.0 - 1.0
return wp.vec3(sign_x * upper[0], sign_y * upper[1], sign_z * upper[2])
@wp.func
def get_box_edge(edge_id: int, upper: wp.vec3):
# get the edge of the box given its ID (0-11)
if edge_id < 4:
# edges along x: 0-1, 2-3, 4-5, 6-7
i = edge_id * 2
j = i + 1
return wp.spatial_vector(get_box_vertex(i, upper), get_box_vertex(j, upper))
elif edge_id < 8:
# edges along y: 0-2, 1-3, 4-6, 5-7
edge_id -= 4
i = edge_id % 2 + edge_id // 2 * 4
j = i + 2
return wp.spatial_vector(get_box_vertex(i, upper), get_box_vertex(j, upper))
# edges along z: 0-4, 1-5, 2-6, 3-7
edge_id -= 8
i = edge_id
j = i + 4
return wp.spatial_vector(get_box_vertex(i, upper), get_box_vertex(j, upper))
@wp.func
def get_plane_edge(edge_id: int, plane_width: float, plane_length: float):
# get the edge of the plane given its ID (0-3)
p0x = (2.0 * float(edge_id % 2) - 1.0) * plane_width
p0z = (2.0 * float(edge_id // 2) - 1.0) * plane_length
if edge_id == 0 or edge_id == 3:
p1x = p0x
p1z = -p0z
else:
p1x = -p0x
p1z = p0z
return wp.spatial_vector(wp.vec3(p0x, 0.0, p0z), wp.vec3(p1x, 0.0, p1z))
@wp.func
def closest_edge_coordinate_box(upper: wp.vec3, edge_a: wp.vec3, edge_b: wp.vec3, max_iter: int):
# find point on edge closest to box, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = box_sdf(upper, query)
query = (1.0 - d) * edge_a + d * edge_b
yd = box_sdf(upper, query)
for _k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = box_sdf(upper, query)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = box_sdf(upper, query)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def closest_edge_coordinate_plane(
plane_width: float,
plane_length: float,
edge_a: wp.vec3,
edge_b: wp.vec3,
max_iter: int,
):
# find point on edge closest to plane, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = plane_sdf(plane_width, plane_length, query)
query = (1.0 - d) * edge_a + d * edge_b
yd = plane_sdf(plane_width, plane_length, query)
for _k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = plane_sdf(plane_width, plane_length, query)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = plane_sdf(plane_width, plane_length, query)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def closest_edge_coordinate_capsule(radius: float, half_height: float, edge_a: wp.vec3, edge_b: wp.vec3, max_iter: int):
# find point on edge closest to capsule, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = capsule_sdf(radius, half_height, query)
query = (1.0 - d) * edge_a + d * edge_b
yd = capsule_sdf(radius, half_height, query)
for _k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = capsule_sdf(radius, half_height, query)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = capsule_sdf(radius, half_height, query)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def mesh_sdf(mesh: wp.uint64, point: wp.vec3, max_dist: float):
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(mesh, point, max_dist, sign, face_index, face_u, face_v)
if res:
closest = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
return wp.length(point - closest) * sign
return max_dist
@wp.func
def closest_point_mesh(mesh: wp.uint64, point: wp.vec3, max_dist: float):
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(mesh, point, max_dist, sign, face_index, face_u, face_v)
if res:
return wp.mesh_eval_position(mesh, face_index, face_u, face_v)
# return arbitrary point from mesh
return wp.mesh_eval_position(mesh, 0, 0.0, 0.0)
@wp.func
def closest_edge_coordinate_mesh(mesh: wp.uint64, edge_a: wp.vec3, edge_b: wp.vec3, max_iter: int, max_dist: float):
# find point on edge closest to mesh, return its barycentric edge coordinate
# Golden-section search
a = float(0.0)
b = float(1.0)
h = b - a
invphi = 0.61803398875 # 1 / phi
invphi2 = 0.38196601125 # 1 / phi^2
c = a + invphi2 * h
d = a + invphi * h
query = (1.0 - c) * edge_a + c * edge_b
yc = mesh_sdf(mesh, query, max_dist)
query = (1.0 - d) * edge_a + d * edge_b
yd = mesh_sdf(mesh, query, max_dist)
for _k in range(max_iter):
if yc < yd: # yc > yd to find the maximum
b = d
d = c
yd = yc
h = invphi * h
c = a + invphi2 * h
query = (1.0 - c) * edge_a + c * edge_b
yc = mesh_sdf(mesh, query, max_dist)
else:
a = c
c = d
yc = yd
h = invphi * h
d = a + invphi * h
query = (1.0 - d) * edge_a + d * edge_b
yd = mesh_sdf(mesh, query, max_dist)
if yc < yd:
return 0.5 * (a + d)
return 0.5 * (c + b)
@wp.func
def volume_grad(volume: wp.uint64, p: wp.vec3):
eps = 0.05 # TODO make this a parameter
q = wp.volume_world_to_index(volume, p)
# compute gradient of the SDF using finite differences
dx = wp.volume_sample_f(volume, q + wp.vec3(eps, 0.0, 0.0), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(eps, 0.0, 0.0), wp.Volume.LINEAR
)
dy = wp.volume_sample_f(volume, q + wp.vec3(0.0, eps, 0.0), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(0.0, eps, 0.0), wp.Volume.LINEAR
)
dz = wp.volume_sample_f(volume, q + wp.vec3(0.0, 0.0, eps), wp.Volume.LINEAR) - wp.volume_sample_f(
volume, q - wp.vec3(0.0, 0.0, eps), wp.Volume.LINEAR
)
return wp.normalize(wp.vec3(dx, dy, dz))
@wp.func
def counter_increment(counter: wp.array(dtype=int), counter_index: int, tids: wp.array(dtype=int), tid: int):
# increment counter, remember which thread received which counter value
next_count = wp.atomic_add(counter, counter_index, 1)
tids[tid] = next_count
return next_count
@wp.func_replay(counter_increment)
def replay_counter_increment(counter: wp.array(dtype=int), counter_index: int, tids: wp.array(dtype=int), tid: int):
return tids[tid]
@wp.func
def limited_counter_increment(
counter: wp.array(dtype=int), counter_index: int, tids: wp.array(dtype=int), tid: int, index_limit: int
):
# increment counter but only if it is smaller than index_limit, remember which thread received which counter value
next_count = wp.atomic_add(counter, counter_index, 1)
if next_count < index_limit or index_limit < 0:
tids[tid] = next_count
return next_count
tids[tid] = -1
return -1
@wp.func_replay(limited_counter_increment)
def replay_limited_counter_increment(
counter: wp.array(dtype=int), counter_index: int, tids: wp.array(dtype=int), tid: int, index_limit: int
):
return tids[tid]
@wp.kernel
def create_soft_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_X_wb: wp.array(dtype=wp.transform),
shape_X_bs: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
geo: ModelShapeGeometry,
margin: float,
soft_contact_max: int,
shape_count: int,
# outputs
soft_contact_count: wp.array(dtype=int),
soft_contact_particle: wp.array(dtype=int),
soft_contact_shape: wp.array(dtype=int),
soft_contact_body_pos: wp.array(dtype=wp.vec3),
soft_contact_body_vel: wp.array(dtype=wp.vec3),
soft_contact_normal: wp.array(dtype=wp.vec3),
soft_contact_tids: wp.array(dtype=int),
):
tid = wp.tid()
particle_index, shape_index = tid // shape_count, tid % shape_count
if (particle_flags[particle_index] & PARTICLE_FLAG_ACTIVE) == 0:
return
rigid_index = shape_body[shape_index]
px = particle_x[particle_index]
radius = particle_radius[particle_index]
X_wb = wp.transform_identity()
if rigid_index >= 0:
X_wb = body_X_wb[rigid_index]
X_bs = shape_X_bs[shape_index]
X_ws = wp.transform_multiply(X_wb, X_bs)
X_sw = wp.transform_inverse(X_ws)
# transform particle position to shape local space
x_local = wp.transform_point(X_sw, px)
# geo description
geo_type = geo.type[shape_index]
geo_scale = geo.scale[shape_index]
# evaluate shape sdf
d = 1.0e6
n = wp.vec3()
v = wp.vec3()
if geo_type == wp.sim.GEO_SPHERE:
d = sphere_sdf(wp.vec3(), geo_scale[0], x_local)
n = sphere_sdf_grad(wp.vec3(), geo_scale[0], x_local)
if geo_type == wp.sim.GEO_BOX:
d = box_sdf(geo_scale, x_local)
n = box_sdf_grad(geo_scale, x_local)
if geo_type == wp.sim.GEO_CAPSULE:
d = capsule_sdf(geo_scale[0], geo_scale[1], x_local)
n = capsule_sdf_grad(geo_scale[0], geo_scale[1], x_local)
if geo_type == wp.sim.GEO_CYLINDER:
d = cylinder_sdf(geo_scale[0], geo_scale[1], x_local)
n = cylinder_sdf_grad(geo_scale[0], geo_scale[1], x_local)
if geo_type == wp.sim.GEO_CONE:
d = cone_sdf(geo_scale[0], geo_scale[1], x_local)
n = cone_sdf_grad(geo_scale[0], geo_scale[1], x_local)
if geo_type == wp.sim.GEO_MESH:
mesh = geo.source[shape_index]
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
min_scale = wp.min(geo_scale)
if wp.mesh_query_point_sign_normal(
mesh, wp.cw_div(x_local, geo_scale), margin + radius / min_scale, sign, face_index, face_u, face_v
):
shape_p = wp.mesh_eval_position(mesh, face_index, face_u, face_v)
shape_v = wp.mesh_eval_velocity(mesh, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale)
shape_v = wp.cw_mul(shape_v, geo_scale)
delta = x_local - shape_p
d = wp.length(delta) * sign
n = wp.normalize(delta) * sign
v = shape_v
if geo_type == wp.sim.GEO_SDF:
volume = geo.source[shape_index]
xpred_local = wp.volume_world_to_index(volume, wp.cw_div(x_local, geo_scale))
nn = wp.vec3(0.0, 0.0, 0.0)
d = wp.volume_sample_grad_f(volume, xpred_local, wp.Volume.LINEAR, nn)
n = wp.normalize(nn)
if geo_type == wp.sim.GEO_PLANE:
d = plane_sdf(geo_scale[0], geo_scale[1], x_local)
n = wp.vec3(0.0, 1.0, 0.0)
if d < margin + radius:
index = counter_increment(soft_contact_count, 0, soft_contact_tids, tid)
if index < soft_contact_max:
# compute contact point in body local space
body_pos = wp.transform_point(X_bs, x_local - n * d)
body_vel = wp.transform_vector(X_bs, v)
world_normal = wp.transform_vector(X_ws, n)
soft_contact_shape[index] = shape_index
soft_contact_body_pos[index] = body_pos
soft_contact_body_vel[index] = body_vel
soft_contact_particle[index] = particle_index
soft_contact_normal[index] = world_normal
@wp.kernel(enable_backward=False)
def count_contact_points(
contact_pairs: wp.array(dtype=int, ndim=2),
geo: ModelShapeGeometry,
mesh_contact_max: int,
# outputs
contact_count: wp.array(dtype=int),
):
tid = wp.tid()
shape_a = contact_pairs[tid, 0]
shape_b = contact_pairs[tid, 1]
if shape_b == -1:
actual_shape_a = shape_a
actual_type_a = geo.type[shape_a]
# ground plane
actual_type_b = wp.sim.GEO_PLANE
actual_shape_b = -1
else:
type_a = geo.type[shape_a]
type_b = geo.type[shape_b]
# unique ordering of shape pairs
if type_a < type_b:
actual_shape_a = shape_a
actual_shape_b = shape_b
actual_type_a = type_a
actual_type_b = type_b
else:
actual_shape_a = shape_b
actual_shape_b = shape_a
actual_type_a = type_b
actual_type_b = type_a
# determine how many contact points need to be evaluated
num_contacts = 0
num_actual_contacts = 0
if actual_type_a == wp.sim.GEO_SPHERE:
num_contacts = 1
num_actual_contacts = 1
elif actual_type_a == wp.sim.GEO_CAPSULE:
if actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 2 # vertex-based collision for infinite plane
num_actual_contacts = 2
else:
num_contacts = 2 + 4 # vertex-based collision + plane edges
num_actual_contacts = 2 + 4
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 2
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
if mesh_contact_max > 0:
num_contacts_b = wp.min(mesh_contact_max, num_contacts_b)
num_actual_contacts = num_contacts_a + num_contacts_b
else:
num_contacts = 2
num_actual_contacts = 2
elif actual_type_a == wp.sim.GEO_BOX:
if actual_type_b == wp.sim.GEO_BOX:
num_contacts = 24
num_actual_contacts = 24
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 8
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
if mesh_contact_max > 0:
num_contacts_b = wp.min(mesh_contact_max, num_contacts_b)
num_actual_contacts = num_contacts_a + num_contacts_b
elif actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 8 # vertex-based collision
num_actual_contacts = 8
else:
num_contacts = 8 + 4 # vertex-based collision + plane edges
num_actual_contacts = 8 + 4
else:
num_contacts = 8
elif actual_type_a == wp.sim.GEO_MESH:
mesh_a = wp.mesh_get(geo.source[actual_shape_a])
num_contacts_a = mesh_a.points.shape[0]
if mesh_contact_max > 0:
num_contacts_a = wp.min(mesh_contact_max, num_contacts_a)
if actual_type_b == wp.sim.GEO_MESH:
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
num_contacts = num_contacts_a + num_contacts_b
if mesh_contact_max > 0:
num_contacts_b = wp.min(mesh_contact_max, num_contacts_b)
else:
num_contacts_b = 0
num_contacts = num_contacts_a + num_contacts_b
num_actual_contacts = num_contacts_a + num_contacts_b
elif actual_type_a == wp.sim.GEO_PLANE:
return # no plane-plane contacts
else:
wp.printf(
"count_contact_points: unsupported geometry type combination %d and %d\n", actual_type_a, actual_type_b
)
wp.atomic_add(contact_count, 0, num_contacts)
wp.atomic_add(contact_count, 1, num_actual_contacts)
@wp.kernel(enable_backward=False)
def broadphase_collision_pairs(
contact_pairs: wp.array(dtype=int, ndim=2),
body_q: wp.array(dtype=wp.transform),
shape_X_bs: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
body_mass: wp.array(dtype=float),
num_shapes: int,
geo: ModelShapeGeometry,
collision_radius: wp.array(dtype=float),
rigid_contact_max: int,
rigid_contact_margin: float,
mesh_contact_max: int,
iterate_mesh_vertices: bool,
# outputs
contact_count: wp.array(dtype=int),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
contact_point_id: wp.array(dtype=int),
contact_point_limit: wp.array(dtype=int),
):
tid = wp.tid()
shape_a = contact_pairs[tid, 0]
shape_b = contact_pairs[tid, 1]
mass_a = 0.0
mass_b = 0.0
rigid_a = shape_body[shape_a]
if rigid_a == -1:
X_ws_a = shape_X_bs[shape_a]
else:
X_ws_a = wp.transform_multiply(body_q[rigid_a], shape_X_bs[shape_a])
mass_a = body_mass[rigid_a]
rigid_b = shape_body[shape_b]
if rigid_b == -1:
X_ws_b = shape_X_bs[shape_b]
else:
X_ws_b = wp.transform_multiply(body_q[rigid_b], shape_X_bs[shape_b])
mass_b = body_mass[rigid_b]
if mass_a == 0.0 and mass_b == 0.0:
# skip if both bodies are static
return
type_a = geo.type[shape_a]
type_b = geo.type[shape_b]
# unique ordering of shape pairs
if type_a < type_b:
actual_shape_a = shape_a
actual_shape_b = shape_b
actual_type_a = type_a
actual_type_b = type_b
actual_X_ws_a = X_ws_a
actual_X_ws_b = X_ws_b
else:
actual_shape_a = shape_b
actual_shape_b = shape_a
actual_type_a = type_b
actual_type_b = type_a
actual_X_ws_a = X_ws_b
actual_X_ws_b = X_ws_a
p_a = wp.transform_get_translation(actual_X_ws_a)
if actual_type_b == wp.sim.GEO_PLANE:
if actual_type_a == wp.sim.GEO_PLANE:
return
query_b = wp.transform_point(wp.transform_inverse(actual_X_ws_b), p_a)
scale = geo.scale[actual_shape_b]
closest = closest_point_plane(scale[0], scale[1], query_b)
d = wp.length(query_b - closest)
r_a = collision_radius[actual_shape_a]
if d > r_a + rigid_contact_margin:
return
else:
p_b = wp.transform_get_translation(actual_X_ws_b)
d = wp.length(p_a - p_b) * 0.5 - 0.1
r_a = collision_radius[actual_shape_a]
r_b = collision_radius[actual_shape_b]
if d > r_a + r_b + rigid_contact_margin:
return
pair_index_ab = actual_shape_a * num_shapes + actual_shape_b
pair_index_ba = actual_shape_b * num_shapes + actual_shape_a
# determine how many contact points need to be evaluated
num_contacts = 0
if actual_type_a == wp.sim.GEO_SPHERE:
num_contacts = 1
elif actual_type_a == wp.sim.GEO_CAPSULE:
if actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 2 # vertex-based collision for infinite plane
else:
num_contacts = 2 + 4 # vertex-based collision + plane edges
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 2
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
if iterate_mesh_vertices:
num_contacts_b = mesh_b.points.shape[0]
else:
num_contacts_b = 0
num_contacts = num_contacts_a + num_contacts_b
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from capsule A against mesh B
for i in range(num_contacts_a):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
# allocate contact points from mesh B against capsule A
for i in range(num_contacts_b):
contact_shape0[index + num_contacts_a + i] = actual_shape_b
contact_shape1[index + num_contacts_a + i] = actual_shape_a
contact_point_id[index + num_contacts_a + i] = i
contact_point_limit[pair_index_ab] = 2
if mesh_contact_max > 0:
num_contacts_b = wp.min(mesh_contact_max, num_contacts_b)
contact_point_limit[pair_index_ba] = num_contacts_b
return
else:
num_contacts = 2
elif actual_type_a == wp.sim.GEO_BOX:
if actual_type_b == wp.sim.GEO_BOX:
index = wp.atomic_add(contact_count, 0, 24)
if index + 23 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from box A against B
for i in range(12): # 12 edges
contact_shape0[index + i] = shape_a
contact_shape1[index + i] = shape_b
contact_point_id[index + i] = i
contact_point_limit[pair_index_ab] = 12
# allocate contact points from box B against A
for i in range(12):
contact_shape0[index + 12 + i] = shape_b
contact_shape1[index + 12 + i] = shape_a
contact_point_id[index + 12 + i] = i
contact_point_limit[pair_index_ba] = 12
return
elif actual_type_b == wp.sim.GEO_MESH:
num_contacts_a = 8
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
if iterate_mesh_vertices:
num_contacts_b = mesh_b.points.shape[0]
else:
num_contacts_b = 0
num_contacts = num_contacts_a + num_contacts_b
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from box A against mesh B
for i in range(num_contacts_a):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
# allocate contact points from mesh B against box A
for i in range(num_contacts_b):
contact_shape0[index + num_contacts_a + i] = actual_shape_b
contact_shape1[index + num_contacts_a + i] = actual_shape_a
contact_point_id[index + num_contacts_a + i] = i
contact_point_limit[pair_index_ab] = num_contacts_a
if mesh_contact_max > 0:
num_contacts_b = wp.min(mesh_contact_max, num_contacts_b)
contact_point_limit[pair_index_ba] = num_contacts_b
return
elif actual_type_b == wp.sim.GEO_PLANE:
if geo.scale[actual_shape_b][0] == 0.0 and geo.scale[actual_shape_b][1] == 0.0:
num_contacts = 8 # vertex-based collision
else:
num_contacts = 8 + 4 # vertex-based collision + plane edges
else:
num_contacts = 8
elif actual_type_a == wp.sim.GEO_MESH:
mesh_a = wp.mesh_get(geo.source[actual_shape_a])
num_contacts_a = mesh_a.points.shape[0]
num_contacts_b = 0
if actual_type_b == wp.sim.GEO_MESH:
mesh_b = wp.mesh_get(geo.source[actual_shape_b])
num_contacts_b = mesh_b.points.shape[0]
elif actual_type_b != wp.sim.GEO_PLANE:
print("broadphase_collision_pairs: unsupported geometry type for mesh collision")
return
num_contacts = num_contacts_a + num_contacts_b
if num_contacts > 0:
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Mesh contact: Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points from mesh A against B
for i in range(num_contacts_a):
contact_shape0[index + i] = actual_shape_a
contact_shape1[index + i] = actual_shape_b
contact_point_id[index + i] = i
# allocate contact points from mesh B against A
for i in range(num_contacts_b):
contact_shape0[index + num_contacts_a + i] = actual_shape_b
contact_shape1[index + num_contacts_a + i] = actual_shape_a
contact_point_id[index + num_contacts_a + i] = i
if mesh_contact_max > 0:
num_contacts_a = wp.min(mesh_contact_max, num_contacts_a)
num_contacts_b = wp.min(mesh_contact_max, num_contacts_b)
contact_point_limit[pair_index_ab] = num_contacts_a
contact_point_limit[pair_index_ba] = num_contacts_b
return
elif actual_type_a == wp.sim.GEO_PLANE:
return # no plane-plane contacts
else:
print("broadphase_collision_pairs: unsupported geometry type")
if num_contacts > 0:
index = wp.atomic_add(contact_count, 0, num_contacts)
if index + num_contacts - 1 >= rigid_contact_max:
print("Number of rigid contacts exceeded limit. Increase Model.rigid_contact_max.")
return
# allocate contact points
for i in range(num_contacts):
cp_index = index + i
contact_shape0[cp_index] = actual_shape_a
contact_shape1[cp_index] = actual_shape_b
contact_point_id[cp_index] = i
contact_point_limit[pair_index_ab] = num_contacts
contact_point_limit[pair_index_ba] = 0
@wp.kernel
def handle_contact_pairs(
body_q: wp.array(dtype=wp.transform),
shape_X_bs: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
geo: ModelShapeGeometry,
rigid_contact_margin: float,
contact_broad_shape0: wp.array(dtype=int),
contact_broad_shape1: wp.array(dtype=int),
num_shapes: int,
contact_point_id: wp.array(dtype=int),
contact_point_limit: wp.array(dtype=int),
edge_sdf_iter: int,
# outputs
contact_count: wp.array(dtype=int),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_offset0: wp.array(dtype=wp.vec3),
contact_offset1: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_thickness: wp.array(dtype=float),
contact_pairwise_counter: wp.array(dtype=int),
contact_tids: wp.array(dtype=int),
):
tid = wp.tid()
shape_a = contact_broad_shape0[tid]
shape_b = contact_broad_shape1[tid]
if shape_a == shape_b:
return
point_id = contact_point_id[tid]
pair_index = shape_a * num_shapes + shape_b
contact_limit = contact_point_limit[pair_index]
if contact_pairwise_counter[pair_index] >= contact_limit:
# reached limit of contact points per contact pair
return
rigid_a = shape_body[shape_a]
X_wb_a = wp.transform_identity()
if rigid_a >= 0:
X_wb_a = body_q[rigid_a]
X_bs_a = shape_X_bs[shape_a]
X_ws_a = wp.transform_multiply(X_wb_a, X_bs_a)
X_sw_a = wp.transform_inverse(X_ws_a)
X_bw_a = wp.transform_inverse(X_wb_a)
geo_type_a = geo.type[shape_a]
geo_scale_a = geo.scale[shape_a]
min_scale_a = min(geo_scale_a)
thickness_a = geo.thickness[shape_a]
# is_solid_a = geo.is_solid[shape_a]
rigid_b = shape_body[shape_b]
X_wb_b = wp.transform_identity()
if rigid_b >= 0:
X_wb_b = body_q[rigid_b]
X_bs_b = shape_X_bs[shape_b]
X_ws_b = wp.transform_multiply(X_wb_b, X_bs_b)
X_sw_b = wp.transform_inverse(X_ws_b)
X_bw_b = wp.transform_inverse(X_wb_b)
geo_type_b = geo.type[shape_b]
geo_scale_b = geo.scale[shape_b]
min_scale_b = min(geo_scale_b)
thickness_b = geo.thickness[shape_b]
# is_solid_b = geo.is_solid[shape_b]
distance = 1.0e6
u = float(0.0)
thickness = thickness_a + thickness_b
if geo_type_a == wp.sim.GEO_SPHERE:
p_a_world = wp.transform_get_translation(X_ws_a)
if geo_type_b == wp.sim.GEO_SPHERE:
p_b_world = wp.transform_get_translation(X_ws_b)
elif geo_type_b == wp.sim.GEO_BOX:
# contact point in frame of body B
p_a_body = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_box(geo_scale_b, p_a_body)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
elif geo_type_b == wp.sim.GEO_CAPSULE:
half_height_b = geo_scale_b[1]
# capsule B
A_b = wp.transform_point(X_ws_b, wp.vec3(0.0, half_height_b, 0.0))
B_b = wp.transform_point(X_ws_b, wp.vec3(0.0, -half_height_b, 0.0))
p_b_world = closest_point_line_segment(A_b, B_b, p_a_world)
elif geo_type_b == wp.sim.GEO_MESH:
mesh_b = geo.source[shape_b]
query_b_local = wp.transform_point(X_sw_b, p_a_world)
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
max_dist = (thickness + rigid_contact_margin) / min_scale_b
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
else:
return
elif geo_type_b == wp.sim.GEO_PLANE:
p_b_body = closest_point_plane(geo_scale_b[0], geo_scale_b[1], wp.transform_point(X_sw_b, p_a_world))
p_b_world = wp.transform_point(X_ws_b, p_b_body)
else:
print("Unsupported geometry type in sphere collision handling")
print(geo_type_b)
return
diff = p_a_world - p_b_world
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_BOX:
# edge-based box contact
edge = get_box_edge(point_id, geo_scale_a)
edge0_world = wp.transform_point(X_ws_a, wp.spatial_top(edge))
edge1_world = wp.transform_point(X_ws_a, wp.spatial_bottom(edge))
edge0_b = wp.transform_point(X_sw_b, edge0_world)
edge1_b = wp.transform_point(X_sw_b, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_box(geo_scale_b, edge0_b, edge1_b, max_iter)
p_a_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on box B
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_box(geo_scale_b, query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
# use center of box A to query normal to make sure we are not inside B
query_b = wp.transform_point(X_sw_b, wp.transform_get_translation(X_ws_a))
normal = wp.transform_vector(X_ws_b, box_sdf_grad(geo_scale_b, query_b))
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_CAPSULE:
half_height_b = geo_scale_b[1]
# capsule B
# depending on point id, we query an edge from 0 to 0.5 or 0.5 to 1
e0 = wp.vec3(0.0, -half_height_b * float(point_id % 2), 0.0)
e1 = wp.vec3(0.0, half_height_b * float((point_id + 1) % 2), 0.0)
edge0_world = wp.transform_point(X_ws_b, e0)
edge1_world = wp.transform_point(X_ws_b, e1)
edge0_a = wp.transform_point(X_sw_a, edge0_world)
edge1_a = wp.transform_point(X_sw_a, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_box(geo_scale_a, edge0_a, edge1_a, max_iter)
p_b_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on box A
query_a = wp.transform_point(X_sw_a, p_b_world)
p_a_body = closest_point_box(geo_scale_a, query_a)
p_a_world = wp.transform_point(X_ws_a, p_a_body)
diff = p_a_world - p_b_world
# the contact point inside the capsule should already be outside the box
normal = -wp.transform_vector(X_ws_a, box_sdf_grad(geo_scale_a, query_a))
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_PLANE:
plane_width = geo_scale_b[0]
plane_length = geo_scale_b[1]
if point_id < 8:
# vertex-based contact
p_a_body = get_box_vertex(point_id, geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, p_a_body)
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_plane(plane_width, plane_length, query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
if plane_width > 0.0 and plane_length > 0.0:
if wp.abs(query_b[0]) > plane_width or wp.abs(query_b[2]) > plane_length:
# skip, we will evaluate the plane edge contact with the box later
return
# check whether the COM is above the plane
# sign = wp.sign(wp.dot(wp.transform_get_translation(X_ws_a) - p_b_world, normal))
# if sign < 0.0:
# # the entire box is most likely below the plane
# return
# the contact point is within plane boundaries
distance = wp.dot(diff, normal)
else:
# contact between box A and edges of finite plane B
edge = get_plane_edge(point_id - 8, plane_width, plane_length)
edge0_world = wp.transform_point(X_ws_b, wp.spatial_top(edge))
edge1_world = wp.transform_point(X_ws_b, wp.spatial_bottom(edge))
edge0_a = wp.transform_point(X_sw_a, edge0_world)
edge1_a = wp.transform_point(X_sw_a, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_box(geo_scale_a, edge0_a, edge1_a, max_iter)
p_b_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on box A
query_a = wp.transform_point(X_sw_a, p_b_world)
p_a_body = closest_point_box(geo_scale_a, query_a)
p_a_world = wp.transform_point(X_ws_a, p_a_body)
query_b = wp.transform_point(X_sw_b, p_a_world)
if wp.abs(query_b[0]) > plane_width or wp.abs(query_b[2]) > plane_length:
# ensure that the closest point is actually inside the plane
return
diff = p_a_world - p_b_world
com_a = wp.transform_get_translation(X_ws_a)
query_b = wp.transform_point(X_sw_b, com_a)
if wp.abs(query_b[0]) > plane_width or wp.abs(query_b[2]) > plane_length:
# the COM is outside the plane
normal = wp.normalize(com_a - p_b_world)
else:
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_CAPSULE and geo_type_b == wp.sim.GEO_CAPSULE:
# find closest edge coordinate to capsule SDF B
half_height_a = geo_scale_a[1]
half_height_b = geo_scale_b[1]
# edge from capsule A
# depending on point id, we query an edge from 0 to 0.5 or 0.5 to 1
e0 = wp.vec3(0.0, half_height_a * float(point_id % 2), 0.0)
e1 = wp.vec3(0.0, -half_height_a * float((point_id + 1) % 2), 0.0)
edge0_world = wp.transform_point(X_ws_a, e0)
edge1_world = wp.transform_point(X_ws_a, e1)
edge0_b = wp.transform_point(X_sw_b, edge0_world)
edge1_b = wp.transform_point(X_sw_b, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_capsule(geo_scale_b[0], geo_scale_b[1], edge0_b, edge1_b, max_iter)
p_a_world = (1.0 - u) * edge0_world + u * edge1_world
p0_b_world = wp.transform_point(X_ws_b, wp.vec3(0.0, half_height_b, 0.0))
p1_b_world = wp.transform_point(X_ws_b, wp.vec3(0.0, -half_height_b, 0.0))
p_b_world = closest_point_line_segment(p0_b_world, p1_b_world, p_a_world)
diff = p_a_world - p_b_world
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_CAPSULE and geo_type_b == wp.sim.GEO_MESH:
# find closest edge coordinate to mesh SDF B
half_height_a = geo_scale_a[1]
# edge from capsule A
# depending on point id, we query an edge from -h to 0 or 0 to h
e0 = wp.vec3(0.0, -half_height_a * float(point_id % 2), 0.0)
e1 = wp.vec3(0.0, half_height_a * float((point_id + 1) % 2), 0.0)
edge0_world = wp.transform_point(X_ws_a, e0)
edge1_world = wp.transform_point(X_ws_a, e1)
edge0_b = wp.transform_point(X_sw_b, edge0_world)
edge1_b = wp.transform_point(X_sw_b, edge1_world)
max_iter = edge_sdf_iter
max_dist = (rigid_contact_margin + thickness) / min_scale_b
mesh_b = geo.source[shape_b]
u = closest_edge_coordinate_mesh(
mesh_b, wp.cw_div(edge0_b, geo_scale_b), wp.cw_div(edge1_b, geo_scale_b), max_iter, max_dist
)
p_a_world = (1.0 - u) * edge0_world + u * edge1_world
query_b_local = wp.transform_point(X_sw_b, p_a_world)
mesh_b = geo.source[shape_b]
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
p_a_world = closest_point_line_segment(edge0_world, edge1_world, p_b_world)
# contact direction vector in world frame
diff = p_a_world - p_b_world
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
else:
return
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_CAPSULE:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
# find closest point + contact normal on capsule B
half_height_b = geo_scale_b[1]
A_b = wp.transform_point(X_ws_b, wp.vec3(0.0, half_height_b, 0.0))
B_b = wp.transform_point(X_ws_b, wp.vec3(0.0, -half_height_b, 0.0))
p_b_world = closest_point_line_segment(A_b, B_b, p_a_world)
diff = p_a_world - p_b_world
# this is more reliable in practice than using the SDF gradient
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_CAPSULE and geo_type_b == wp.sim.GEO_PLANE:
plane_width = geo_scale_b[0]
plane_length = geo_scale_b[1]
if point_id < 2:
# vertex-based collision
half_height_a = geo_scale_a[1]
side = float(point_id) * 2.0 - 1.0
p_a_world = wp.transform_point(X_ws_a, wp.vec3(0.0, side * half_height_a, 0.0))
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_plane(geo_scale_b[0], geo_scale_b[1], query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
if geo_scale_b[0] > 0.0 and geo_scale_b[1] > 0.0:
normal = wp.normalize(diff)
else:
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
distance = wp.dot(diff, normal)
else:
# contact between capsule A and edges of finite plane B
plane_width = geo_scale_b[0]
plane_length = geo_scale_b[1]
edge = get_plane_edge(point_id - 2, plane_width, plane_length)
edge0_world = wp.transform_point(X_ws_b, wp.spatial_top(edge))
edge1_world = wp.transform_point(X_ws_b, wp.spatial_bottom(edge))
edge0_a = wp.transform_point(X_sw_a, edge0_world)
edge1_a = wp.transform_point(X_sw_a, edge1_world)
max_iter = edge_sdf_iter
u = closest_edge_coordinate_capsule(geo_scale_a[0], geo_scale_a[1], edge0_a, edge1_a, max_iter)
p_b_world = (1.0 - u) * edge0_world + u * edge1_world
# find closest point + contact normal on capsule A
half_height_a = geo_scale_a[1]
p0_a_world = wp.transform_point(X_ws_a, wp.vec3(0.0, half_height_a, 0.0))
p1_a_world = wp.transform_point(X_ws_a, wp.vec3(0.0, -half_height_a, 0.0))
p_a_world = closest_point_line_segment(p0_a_world, p1_a_world, p_b_world)
diff = p_a_world - p_b_world
# normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_BOX:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
# find closest point + contact normal on box B
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_box(geo_scale_b, query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
# this is more reliable in practice than using the SDF gradient
normal = wp.normalize(diff)
if box_sdf(geo_scale_b, query_b) < 0.0:
normal = -normal
distance = wp.dot(diff, normal)
elif geo_type_a == wp.sim.GEO_BOX and geo_type_b == wp.sim.GEO_MESH:
# vertex-based contact
query_a = get_box_vertex(point_id, geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, query_a)
query_b_local = wp.transform_point(X_sw_b, p_a_world)
mesh_b = geo.source[shape_b]
max_dist = (rigid_contact_margin + thickness) / min_scale_b
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
# contact direction vector in world frame
diff_b = p_a_world - p_b_world
normal = wp.normalize(diff_b) * sign
distance = wp.dot(diff_b, normal)
else:
return
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_MESH:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
mesh_b = geo.source[shape_b]
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
query_b_local = wp.transform_point(X_sw_b, p_a_world)
face_index = int(0)
face_u = float(0.0)
face_v = float(0.0)
sign = float(0.0)
min_scale = min(min_scale_a, min_scale_b)
max_dist = (rigid_contact_margin + thickness) / min_scale
res = wp.mesh_query_point_sign_normal(
mesh_b, wp.cw_div(query_b_local, geo_scale_b), max_dist, sign, face_index, face_u, face_v
)
if res:
shape_p = wp.mesh_eval_position(mesh_b, face_index, face_u, face_v)
shape_p = wp.cw_mul(shape_p, geo_scale_b)
p_b_world = wp.transform_point(X_ws_b, shape_p)
# contact direction vector in world frame
diff_b = p_a_world - p_b_world
normal = wp.normalize(diff_b) * sign
distance = wp.dot(diff_b, normal)
else:
return
elif geo_type_a == wp.sim.GEO_MESH and geo_type_b == wp.sim.GEO_PLANE:
# vertex-based contact
mesh = wp.mesh_get(geo.source[shape_a])
body_a_pos = wp.cw_mul(mesh.points[point_id], geo_scale_a)
p_a_world = wp.transform_point(X_ws_a, body_a_pos)
query_b = wp.transform_point(X_sw_b, p_a_world)
p_b_body = closest_point_plane(geo_scale_b[0], geo_scale_b[1], query_b)
p_b_world = wp.transform_point(X_ws_b, p_b_body)
diff = p_a_world - p_b_world
# if the plane is infinite or the point is within the plane we fix the normal to prevent intersections
if (
geo_scale_b[0] == 0.0
and geo_scale_b[1] == 0.0
or wp.abs(query_b[0]) < geo_scale_b[0]
and wp.abs(query_b[2]) < geo_scale_b[1]
):
normal = wp.transform_vector(X_ws_b, wp.vec3(0.0, 1.0, 0.0))
distance = wp.dot(diff, normal)
else:
normal = wp.normalize(diff)
distance = wp.dot(diff, normal)
# ignore extreme penetrations (e.g. when mesh is below the plane)
if distance < -rigid_contact_margin:
return
else:
print("Unsupported geometry pair in collision handling")
return
d = distance - thickness
if d < rigid_contact_margin:
pair_contact_id = limited_counter_increment(
contact_pairwise_counter, pair_index, contact_tids, tid, contact_limit
)
if pair_contact_id == -1:
# wp.printf("Reached contact point limit %d >= %d for shape pair %d and %d (pair_index: %d)\n",
# contact_pairwise_counter[pair_index], contact_limit, shape_a, shape_b, pair_index)
# reached contact point limit
return
index = limited_counter_increment(contact_count, 0, contact_tids, tid, -1)
contact_shape0[index] = shape_a
contact_shape1[index] = shape_b
# transform from world into body frame (so the contact point includes the shape transform)
contact_point0[index] = wp.transform_point(X_bw_a, p_a_world)
contact_point1[index] = wp.transform_point(X_bw_b, p_b_world)
contact_offset0[index] = wp.transform_vector(X_bw_a, -thickness_a * normal)
contact_offset1[index] = wp.transform_vector(X_bw_b, thickness_b * normal)
contact_normal[index] = normal
contact_thickness[index] = thickness
def collide(model, state, edge_sdf_iter: int = 10, iterate_mesh_vertices: bool = True, requires_grad: bool = None):
"""
Generates contact points for the particles and rigid bodies in the model,
to be used in the contact dynamics kernel of the integrator.
Args:
model: the model to be simulated
state: the state of the model
edge_sdf_iter: number of search iterations for finding closest contact points between edges and SDF
iterate_mesh_vertices: whether to iterate over all vertices of a mesh for contact generation (used for capsule/box <> mesh collision)
requires_grad: whether to duplicate contact arrays for gradient computation (if None uses model.requires_grad)
"""
if requires_grad is None:
requires_grad = model.requires_grad
with wp.ScopedTimer("collide", False):
# generate soft contacts for particles and shapes except ground plane (last shape)
if model.particle_count and model.shape_count > 1:
if requires_grad:
model.soft_contact_body_pos = wp.clone(model.soft_contact_body_pos)
model.soft_contact_body_vel = wp.clone(model.soft_contact_body_vel)
model.soft_contact_normal = wp.clone(model.soft_contact_normal)
# clear old count
model.soft_contact_count.zero_()
wp.launch(
kernel=create_soft_contacts,
dim=model.particle_count * (model.shape_count - 1),
inputs=[
state.particle_q,
model.particle_radius,
model.particle_flags,
state.body_q,
model.shape_transform,
model.shape_body,
model.shape_geo,
model.soft_contact_margin,
model.soft_contact_max,
model.shape_count - 1,
],
outputs=[
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
model.soft_contact_tids,
],
device=model.device,
)
if model.shape_contact_pair_count or model.ground and model.shape_ground_contact_pair_count:
# clear old count
model.rigid_contact_count.zero_()
model.rigid_contact_broad_shape0.fill_(-1)
model.rigid_contact_broad_shape1.fill_(-1)
if model.shape_contact_pair_count:
wp.launch(
kernel=broadphase_collision_pairs,
dim=model.shape_contact_pair_count,
inputs=[
model.shape_contact_pairs,
state.body_q,
model.shape_transform,
model.shape_body,
model.body_mass,
model.shape_count,
model.shape_geo,
model.shape_collision_radius,
model.rigid_contact_max,
model.rigid_contact_margin,
model.rigid_mesh_contact_max,
iterate_mesh_vertices,
],
outputs=[
model.rigid_contact_count,
model.rigid_contact_broad_shape0,
model.rigid_contact_broad_shape1,
model.rigid_contact_point_id,
model.rigid_contact_point_limit,
],
device=model.device,
record_tape=False,
)
if model.ground and model.shape_ground_contact_pair_count:
wp.launch(
kernel=broadphase_collision_pairs,
dim=model.shape_ground_contact_pair_count,
inputs=[
model.shape_ground_contact_pairs,
state.body_q,
model.shape_transform,
model.shape_body,
model.body_mass,
model.shape_count,
model.shape_geo,
model.shape_collision_radius,
model.rigid_contact_max,
model.rigid_contact_margin,
model.rigid_mesh_contact_max,
iterate_mesh_vertices,
],
outputs=[
model.rigid_contact_count,
model.rigid_contact_broad_shape0,
model.rigid_contact_broad_shape1,
model.rigid_contact_point_id,
model.rigid_contact_point_limit,
],
device=model.device,
record_tape=False,
)
if model.shape_contact_pair_count or model.ground and model.shape_ground_contact_pair_count:
if requires_grad:
model.rigid_contact_point0 = wp.clone(model.rigid_contact_point0)
model.rigid_contact_point1 = wp.clone(model.rigid_contact_point1)
model.rigid_contact_offset0 = wp.clone(model.rigid_contact_offset0)
model.rigid_contact_offset1 = wp.clone(model.rigid_contact_offset1)
model.rigid_contact_normal = wp.clone(model.rigid_contact_normal)
model.rigid_contact_thickness = wp.clone(model.rigid_contact_thickness)
model.rigid_contact_count = wp.zeros_like(model.rigid_contact_count)
model.rigid_contact_pairwise_counter = wp.zeros_like(model.rigid_contact_pairwise_counter)
model.rigid_contact_tids = wp.zeros_like(model.rigid_contact_tids)
model.rigid_contact_shape0 = wp.empty_like(model.rigid_contact_shape0)
model.rigid_contact_shape1 = wp.empty_like(model.rigid_contact_shape1)
else:
model.rigid_contact_count.zero_()
model.rigid_contact_pairwise_counter.zero_()
model.rigid_contact_tids.zero_()
model.rigid_contact_shape0.fill_(-1)
model.rigid_contact_shape1.fill_(-1)
wp.launch(
kernel=handle_contact_pairs,
dim=model.rigid_contact_max,
inputs=[
state.body_q,
model.shape_transform,
model.shape_body,
model.shape_geo,
model.rigid_contact_margin,
model.rigid_contact_broad_shape0,
model.rigid_contact_broad_shape1,
model.shape_count,
model.rigid_contact_point_id,
model.rigid_contact_point_limit,
edge_sdf_iter,
],
outputs=[
model.rigid_contact_count,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_offset0,
model.rigid_contact_offset1,
model.rigid_contact_normal,
model.rigid_contact_thickness,
model.rigid_contact_pairwise_counter,
model.rigid_contact_tids,
],
device=model.device,
)
| 63,358 | Python | 38.723511 | 141 | 0.559929 |
NVIDIA/warp/warp/sim/__init__.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from .articulation import eval_fk, eval_ik
from .collide import collide
from .import_mjcf import parse_mjcf
from .import_snu import parse_snu
from .import_urdf import parse_urdf
from .import_usd import parse_usd, resolve_usd_from_url
from .inertia import transform_inertia
from .integrator import Integrator, integrate_bodies, integrate_particles
from .integrator_euler import SemiImplicitIntegrator
from .integrator_featherstone import FeatherstoneIntegrator
from .integrator_xpbd import XPBDIntegrator
from .model import (
GEO_BOX,
GEO_CAPSULE,
GEO_CONE,
GEO_CYLINDER,
GEO_MESH,
GEO_NONE,
GEO_PLANE,
GEO_SDF,
GEO_SPHERE,
JOINT_BALL,
JOINT_COMPOUND,
JOINT_D6,
JOINT_DISTANCE,
JOINT_FIXED,
JOINT_FREE,
JOINT_MODE_FORCE,
JOINT_MODE_TARGET_POSITION,
JOINT_MODE_TARGET_VELOCITY,
JOINT_PRISMATIC,
JOINT_REVOLUTE,
JOINT_UNIVERSAL,
SDF,
Control,
JointAxis,
Mesh,
Model,
ModelBuilder,
ModelShapeGeometry,
ModelShapeMaterials,
State,
)
from .utils import load_mesh, quat_from_euler, quat_to_euler, velocity_at_point
| 1,553 | Python | 28.320754 | 79 | 0.746941 |
NVIDIA/warp/warp/sim/articulation.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from .utils import quat_decompose, quat_twist
@wp.func
def compute_2d_rotational_dofs(
axis_0: wp.vec3,
axis_1: wp.vec3,
q0: float,
q1: float,
qd0: float,
qd1: float,
):
"""
Computes the rotation quaternion and 3D angular velocity given the joint axes, coordinates and velocities.
"""
q_off = wp.quat_from_matrix(wp.mat33(axis_0, axis_1, wp.cross(axis_0, axis_1)))
# body local axes
local_0 = wp.quat_rotate(q_off, wp.vec3(1.0, 0.0, 0.0))
local_1 = wp.quat_rotate(q_off, wp.vec3(0.0, 1.0, 0.0))
axis_0 = local_0
q_0 = wp.quat_from_axis_angle(axis_0, q0)
axis_1 = wp.quat_rotate(q_0, local_1)
q_1 = wp.quat_from_axis_angle(axis_1, q1)
rot = q_1 * q_0
vel = axis_0 * qd0 + axis_1 * qd1
return rot, vel
@wp.func
def invert_2d_rotational_dofs(
axis_0: wp.vec3,
axis_1: wp.vec3,
q_p: wp.quat,
q_c: wp.quat,
w_err: wp.vec3,
):
"""
Computes generalized joint position and velocity coordinates for a 2D rotational joint given the joint axes, relative orientations and angular velocity differences between the two bodies the joint connects.
"""
q_off = wp.quat_from_matrix(wp.mat33(axis_0, axis_1, wp.cross(axis_0, axis_1)))
q_pc = wp.quat_inverse(q_off) * wp.quat_inverse(q_p) * q_c * q_off
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# find rotation axes
local_0 = wp.quat_rotate(q_off, wp.vec3(1.0, 0.0, 0.0))
local_1 = wp.quat_rotate(q_off, wp.vec3(0.0, 1.0, 0.0))
local_2 = wp.quat_rotate(q_off, wp.vec3(0.0, 0.0, 1.0))
axis_0 = local_0
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, local_1)
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, local_2)
# convert angular velocity to local space
w_err_p = wp.quat_rotate_inv(q_p, w_err)
# given joint axes and angular velocity error, solve for joint velocities
c12 = wp.cross(axis_1, axis_2)
c02 = wp.cross(axis_0, axis_2)
vel = wp.vec2(wp.dot(w_err_p, c12) / wp.dot(axis_0, c12), wp.dot(w_err_p, c02) / wp.dot(axis_1, c02))
return wp.vec2(angles[0], angles[1]), vel
@wp.func
def compute_3d_rotational_dofs(
axis_0: wp.vec3,
axis_1: wp.vec3,
axis_2: wp.vec3,
q0: float,
q1: float,
q2: float,
qd0: float,
qd1: float,
qd2: float,
):
"""
Computes the rotation quaternion and 3D angular velocity given the joint axes, coordinates and velocities.
"""
q_off = wp.quat_from_matrix(wp.mat33(axis_0, axis_1, axis_2))
# body local axes
local_0 = wp.quat_rotate(q_off, wp.vec3(1.0, 0.0, 0.0))
local_1 = wp.quat_rotate(q_off, wp.vec3(0.0, 1.0, 0.0))
local_2 = wp.quat_rotate(q_off, wp.vec3(0.0, 0.0, 1.0))
# reconstruct rotation axes
axis_0 = local_0
q_0 = wp.quat_from_axis_angle(axis_0, q0)
axis_1 = wp.quat_rotate(q_0, local_1)
q_1 = wp.quat_from_axis_angle(axis_1, q1)
axis_2 = wp.quat_rotate(q_1 * q_0, local_2)
q_2 = wp.quat_from_axis_angle(axis_2, q2)
rot = q_2 * q_1 * q_0
vel = axis_0 * qd0 + axis_1 * qd1 + axis_2 * qd2
return rot, vel
@wp.func
def invert_3d_rotational_dofs(
axis_0: wp.vec3, axis_1: wp.vec3, axis_2: wp.vec3, q_p: wp.quat, q_c: wp.quat, w_err: wp.vec3
):
"""
Computes generalized joint position and velocity coordinates for a 3D rotational joint given the joint axes, relative orientations and angular velocity differences between the two bodies the joint connects.
"""
q_off = wp.quat_from_matrix(wp.mat33(axis_0, axis_1, axis_2))
q_pc = wp.quat_inverse(q_off) * wp.quat_inverse(q_p) * q_c * q_off
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# find rotation axes
local_0 = wp.quat_rotate(q_off, wp.vec3(1.0, 0.0, 0.0))
local_1 = wp.quat_rotate(q_off, wp.vec3(0.0, 1.0, 0.0))
local_2 = wp.quat_rotate(q_off, wp.vec3(0.0, 0.0, 1.0))
axis_0 = local_0
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, local_1)
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, local_2)
# convert angular velocity to local space
w_err_p = wp.quat_rotate_inv(q_p, w_err)
# given joint axes and angular velocity error, solve for joint velocities
c12 = wp.cross(axis_1, axis_2)
c02 = wp.cross(axis_0, axis_2)
c01 = wp.cross(axis_0, axis_1)
velocities = wp.vec3(
wp.dot(w_err_p, c12) / wp.dot(axis_0, c12),
wp.dot(w_err_p, c02) / wp.dot(axis_1, c02),
wp.dot(w_err_p, c01) / wp.dot(axis_2, c01),
)
return angles, velocities
@wp.kernel
def eval_articulation_fk(
articulation_start: wp.array(dtype=int),
articulation_mask: wp.array(
dtype=int
), # used to enable / disable FK for an articulation, if None then treat all as enabled
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
body_com: wp.array(dtype=wp.vec3),
# outputs
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
# early out if disabling FK for this articulation
if articulation_mask:
if articulation_mask[tid] == 0:
return
joint_start = articulation_start[tid]
joint_end = articulation_start[tid + 1]
for i in range(joint_start, joint_end):
parent = joint_parent[i]
child = joint_child[i]
# compute transform across the joint
type = joint_type[i]
X_pj = joint_X_p[i]
X_cj = joint_X_c[i]
# parent anchor frame in world space
X_wpj = X_pj
# velocity of parent anchor point in world space
v_wpj = wp.spatial_vector()
if parent >= 0:
X_wp = body_q[parent]
X_wpj = X_wp * X_wpj
r_p = wp.transform_get_translation(X_wpj) - wp.transform_point(X_wp, body_com[parent])
v_wp = body_qd[parent]
w_p = wp.spatial_top(v_wp)
v_p = wp.spatial_bottom(v_wp) + wp.cross(w_p, r_p)
v_wpj = wp.spatial_vector(w_p, v_p)
q_start = joint_q_start[i]
qd_start = joint_qd_start[i]
axis_start = joint_axis_start[i]
lin_axis_count = joint_axis_dim[i, 0]
ang_axis_count = joint_axis_dim[i, 1]
X_j = wp.transform_identity()
v_j = wp.spatial_vector(wp.vec3(), wp.vec3())
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
q = joint_q[q_start]
qd = joint_qd[qd_start]
X_j = wp.transform(axis * q, wp.quat_identity())
v_j = wp.spatial_vector(wp.vec3(), axis * qd)
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
q = joint_q[q_start]
qd = joint_qd[qd_start]
X_j = wp.transform(wp.vec3(), wp.quat_from_axis_angle(axis, q))
v_j = wp.spatial_vector(axis * qd, wp.vec3())
if type == wp.sim.JOINT_BALL:
r = wp.quat(joint_q[q_start + 0], joint_q[q_start + 1], joint_q[q_start + 2], joint_q[q_start + 3])
w = wp.vec3(joint_qd[qd_start + 0], joint_qd[qd_start + 1], joint_qd[qd_start + 2])
X_j = wp.transform(wp.vec3(), r)
v_j = wp.spatial_vector(w, wp.vec3())
if type == wp.sim.JOINT_FREE or type == wp.sim.JOINT_DISTANCE:
t = wp.transform(
wp.vec3(joint_q[q_start + 0], joint_q[q_start + 1], joint_q[q_start + 2]),
wp.quat(joint_q[q_start + 3], joint_q[q_start + 4], joint_q[q_start + 5], joint_q[q_start + 6]),
)
v = wp.spatial_vector(
wp.vec3(joint_qd[qd_start + 0], joint_qd[qd_start + 1], joint_qd[qd_start + 2]),
wp.vec3(joint_qd[qd_start + 3], joint_qd[qd_start + 4], joint_qd[qd_start + 5]),
)
X_j = t
v_j = v
if type == wp.sim.JOINT_COMPOUND:
rot, vel_w = compute_3d_rotational_dofs(
joint_axis[axis_start],
joint_axis[axis_start + 1],
joint_axis[axis_start + 2],
joint_q[q_start + 0],
joint_q[q_start + 1],
joint_q[q_start + 2],
joint_qd[qd_start + 0],
joint_qd[qd_start + 1],
joint_qd[qd_start + 2],
)
t = wp.transform(wp.vec3(0.0, 0.0, 0.0), rot)
v = wp.spatial_vector(vel_w, wp.vec3(0.0, 0.0, 0.0))
X_j = t
v_j = v
if type == wp.sim.JOINT_UNIVERSAL:
rot, vel_w = compute_2d_rotational_dofs(
joint_axis[axis_start],
joint_axis[axis_start + 1],
joint_q[q_start + 0],
joint_q[q_start + 1],
joint_qd[qd_start + 0],
joint_qd[qd_start + 1],
)
t = wp.transform(wp.vec3(0.0, 0.0, 0.0), rot)
v = wp.spatial_vector(vel_w, wp.vec3(0.0, 0.0, 0.0))
X_j = t
v_j = v
if type == wp.sim.JOINT_D6:
pos = wp.vec3(0.0)
rot = wp.quat_identity()
vel_v = wp.vec3(0.0)
vel_w = wp.vec3(0.0)
# unroll for loop to ensure joint actions remain differentiable
# (since differentiating through a for loop that updates a local variable is not supported)
if lin_axis_count > 0:
axis = joint_axis[axis_start + 0]
pos += axis * joint_q[q_start + 0]
vel_v += axis * joint_qd[qd_start + 0]
if lin_axis_count > 1:
axis = joint_axis[axis_start + 1]
pos += axis * joint_q[q_start + 1]
vel_v += axis * joint_qd[qd_start + 1]
if lin_axis_count > 2:
axis = joint_axis[axis_start + 2]
pos += axis * joint_q[q_start + 2]
vel_v += axis * joint_qd[qd_start + 2]
ia = axis_start + lin_axis_count
iq = q_start + lin_axis_count
iqd = qd_start + lin_axis_count
if ang_axis_count == 1:
axis = joint_axis[ia]
rot = wp.quat_from_axis_angle(axis, joint_q[iq])
vel_w = joint_qd[iqd] * axis
if ang_axis_count == 2:
rot, vel_w = compute_2d_rotational_dofs(
joint_axis[ia + 0],
joint_axis[ia + 1],
joint_q[iq + 0],
joint_q[iq + 1],
joint_qd[iqd + 0],
joint_qd[iqd + 1],
)
if ang_axis_count == 3:
rot, vel_w = compute_3d_rotational_dofs(
joint_axis[ia + 0],
joint_axis[ia + 1],
joint_axis[ia + 2],
joint_q[iq + 0],
joint_q[iq + 1],
joint_q[iq + 2],
joint_qd[iqd + 0],
joint_qd[iqd + 1],
joint_qd[iqd + 2],
)
X_j = wp.transform(pos, rot)
v_j = wp.spatial_vector(vel_w, vel_v)
# transform from world to joint anchor frame at child body
X_wcj = X_wpj * X_j
# transform from world to child body frame
X_wc = X_wcj * wp.transform_inverse(X_cj)
# transform velocity across the joint to world space
angular_vel = wp.transform_vector(X_wpj, wp.spatial_top(v_j))
linear_vel = wp.transform_vector(X_wpj, wp.spatial_bottom(v_j))
v_wc = v_wpj + wp.spatial_vector(angular_vel, linear_vel)
body_q[child] = X_wc
body_qd[child] = v_wc
# updates state body information based on joint coordinates
def eval_fk(model, joint_q, joint_qd, mask, state):
"""
Evaluates the model's forward kinematics given the joint coordinates and updates the state's body information (:attr:`State.body_q` and :attr:`State.body_qd`).
Args:
model (Model): The model to evaluate.
joint_q (array): Generalized joint position coordinates, shape [joint_coord_count], float
joint_qd (array): Generalized joint velocity coordinates, shape [joint_dof_count], float
mask (array): The mask to use to enable / disable FK for an articulation. If None then treat all as enabled, shape [articulation_count], int
state (State): The state to update.
"""
wp.launch(
kernel=eval_articulation_fk,
dim=model.articulation_count,
inputs=[
model.articulation_start,
mask,
joint_q,
joint_qd,
model.joint_q_start,
model.joint_qd_start,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
model.body_com,
],
outputs=[
state.body_q,
state.body_qd,
],
device=model.device,
)
@wp.func
def reconstruct_angular_q_qd(q_pc: wp.quat, w_err: wp.vec3, X_wp: wp.transform, axis: wp.vec3):
"""
Reconstructs the angular joint coordinates and velocities given the relative rotation and angular velocity
between a parent and child body.
Args:
q_pc (quat): The relative rotation between the parent and child body.
w_err (vec3): The angular velocity between the parent and child body.
X_wp (transform): The parent body's transform in world space.
axis (vec3): The joint axis in the frame of the parent body.
Returns:
q (float): The joint position coordinate.
qd (float): The joint velocity coordinate.
"""
axis_p = wp.transform_vector(X_wp, axis)
twist = quat_twist(axis, q_pc)
q = wp.acos(twist[3]) * 2.0 * wp.sign(wp.dot(axis, wp.vec3(twist[0], twist[1], twist[2])))
qd = wp.dot(w_err, axis_p)
return q, qd
@wp.kernel
def eval_articulation_ik(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
joint_type: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_q_start: wp.array(dtype=int),
joint_qd_start: wp.array(dtype=int),
joint_q: wp.array(dtype=float),
joint_qd: wp.array(dtype=float),
):
tid = wp.tid()
parent = joint_parent[tid]
child = joint_child[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
w_p = wp.vec3()
v_p = wp.vec3()
v_wp = wp.spatial_vector()
# parent anchor frame in world space
X_wpj = X_pj
if parent >= 0:
X_wp = body_q[parent]
X_wpj = X_wp * X_pj
r_p = wp.transform_get_translation(X_wpj) - wp.transform_point(X_wp, body_com[parent])
v_wp = body_qd[parent]
w_p = wp.spatial_top(v_wp)
v_p = wp.spatial_bottom(v_wp) + wp.cross(w_p, r_p)
# child transform and moment arm
X_wc = body_q[child]
X_wcj = X_wc * X_cj
v_wc = body_qd[child]
w_c = wp.spatial_top(v_wc)
v_c = wp.spatial_bottom(v_wc)
# joint properties
type = joint_type[tid]
# compute position and orientation differences between anchor frames
x_p = wp.transform_get_translation(X_wpj)
x_c = wp.transform_get_translation(X_wcj)
q_p = wp.transform_get_rotation(X_wpj)
q_c = wp.transform_get_rotation(X_wcj)
x_err = x_c - x_p
v_err = v_c - v_p
w_err = w_c - w_p
q_start = joint_q_start[tid]
qd_start = joint_qd_start[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
# world space joint axis
axis_p = wp.quat_rotate(q_p, axis)
# evaluate joint coordinates
q = wp.dot(x_err, axis_p)
qd = wp.dot(v_err, axis_p)
joint_q[q_start] = q
joint_qd[qd_start] = qd
return
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
q_pc = wp.quat_inverse(q_p) * q_c
q, qd = reconstruct_angular_q_qd(q_pc, w_err, X_wpj, axis)
joint_q[q_start] = q
joint_qd[qd_start] = qd
return
if type == wp.sim.JOINT_BALL:
q_pc = wp.quat_inverse(q_p) * q_c
joint_q[q_start + 0] = q_pc[0]
joint_q[q_start + 1] = q_pc[1]
joint_q[q_start + 2] = q_pc[2]
joint_q[q_start + 3] = q_pc[3]
ang_vel = wp.transform_vector(wp.transform_inverse(X_wpj), w_err)
joint_qd[qd_start + 0] = ang_vel[0]
joint_qd[qd_start + 1] = ang_vel[1]
joint_qd[qd_start + 2] = ang_vel[2]
return
if type == wp.sim.JOINT_FIXED:
return
if type == wp.sim.JOINT_FREE or type == wp.sim.JOINT_DISTANCE:
q_pc = wp.quat_inverse(q_p) * q_c
x_err_c = wp.quat_rotate_inv(q_p, x_err)
v_err_c = wp.quat_rotate_inv(q_p, v_err)
w_err_c = wp.quat_rotate_inv(q_p, w_err)
joint_q[q_start + 0] = x_err_c[0]
joint_q[q_start + 1] = x_err_c[1]
joint_q[q_start + 2] = x_err_c[2]
joint_q[q_start + 3] = q_pc[0]
joint_q[q_start + 4] = q_pc[1]
joint_q[q_start + 5] = q_pc[2]
joint_q[q_start + 6] = q_pc[3]
joint_qd[qd_start + 0] = w_err_c[0]
joint_qd[qd_start + 1] = w_err_c[1]
joint_qd[qd_start + 2] = w_err_c[2]
joint_qd[qd_start + 3] = v_err_c[0]
joint_qd[qd_start + 4] = v_err_c[1]
joint_qd[qd_start + 5] = v_err_c[2]
return
if type == wp.sim.JOINT_COMPOUND:
axis_0 = joint_axis[axis_start + 0]
axis_1 = joint_axis[axis_start + 1]
axis_2 = joint_axis[axis_start + 2]
qs, qds = invert_3d_rotational_dofs(axis_0, axis_1, axis_2, q_p, q_c, w_err)
joint_q[q_start + 0] = qs[0]
joint_q[q_start + 1] = qs[1]
joint_q[q_start + 2] = qs[2]
joint_qd[qd_start + 0] = qds[0]
joint_qd[qd_start + 1] = qds[1]
joint_qd[qd_start + 2] = qds[2]
return
if type == wp.sim.JOINT_UNIVERSAL:
axis_0 = joint_axis[axis_start + 0]
axis_1 = joint_axis[axis_start + 1]
qs2, qds2 = invert_2d_rotational_dofs(axis_0, axis_1, q_p, q_c, w_err)
joint_q[q_start + 0] = qs2[0]
joint_q[q_start + 1] = qs2[1]
joint_qd[qd_start + 0] = qds2[0]
joint_qd[qd_start + 1] = qds2[1]
return
if type == wp.sim.JOINT_D6:
x_err_c = wp.quat_rotate_inv(q_p, x_err)
v_err_c = wp.quat_rotate_inv(q_p, v_err)
if lin_axis_count > 0:
axis = joint_axis[axis_start + 0]
joint_q[q_start + 0] = wp.dot(x_err_c, axis)
joint_qd[qd_start + 0] = wp.dot(v_err_c, axis)
if lin_axis_count > 1:
axis = joint_axis[axis_start + 1]
joint_q[q_start + 1] = wp.dot(x_err_c, axis)
joint_qd[qd_start + 1] = wp.dot(v_err_c, axis)
if lin_axis_count > 2:
axis = joint_axis[axis_start + 2]
joint_q[q_start + 2] = wp.dot(x_err_c, axis)
joint_qd[qd_start + 2] = wp.dot(v_err_c, axis)
if ang_axis_count == 1:
axis = joint_axis[axis_start]
q_pc = wp.quat_inverse(q_p) * q_c
q, qd = reconstruct_angular_q_qd(q_pc, w_err, X_wpj, joint_axis[axis_start + lin_axis_count])
joint_q[q_start + lin_axis_count] = q
joint_qd[qd_start + lin_axis_count] = qd
if ang_axis_count == 2:
axis_0 = joint_axis[axis_start + lin_axis_count + 0]
axis_1 = joint_axis[axis_start + lin_axis_count + 1]
qs2, qds2 = invert_2d_rotational_dofs(axis_0, axis_1, q_p, q_c, w_err)
joint_q[q_start + lin_axis_count + 0] = qs2[0]
joint_q[q_start + lin_axis_count + 1] = qs2[1]
joint_qd[qd_start + lin_axis_count + 0] = qds2[0]
joint_qd[qd_start + lin_axis_count + 1] = qds2[1]
if ang_axis_count == 3:
axis_0 = joint_axis[axis_start + lin_axis_count + 0]
axis_1 = joint_axis[axis_start + lin_axis_count + 1]
axis_2 = joint_axis[axis_start + lin_axis_count + 2]
qs3, qds3 = invert_3d_rotational_dofs(axis_0, axis_1, axis_2, q_p, q_c, w_err)
joint_q[q_start + lin_axis_count + 0] = qs3[0]
joint_q[q_start + lin_axis_count + 1] = qs3[1]
joint_q[q_start + lin_axis_count + 2] = qs3[2]
joint_qd[qd_start + lin_axis_count + 0] = qds3[0]
joint_qd[qd_start + lin_axis_count + 1] = qds3[1]
joint_qd[qd_start + lin_axis_count + 2] = qds3[2]
return
# given maximal coordinate model computes ik (closest point projection)
def eval_ik(model, state, joint_q, joint_qd):
"""
Evaluates the model's inverse kinematics given the state's body information (:attr:`State.body_q` and :attr:`State.body_qd`) and updates the generalized joint coordinates `joint_q` and `joint_qd`.
Args:
model (Model): The model to evaluate.
state (State): The state with the body's maximal coordinates (positions :attr:`State.body_q` and velocities :attr:`State.body_qd`) to use.
joint_q (array): Generalized joint position coordinates, shape [joint_coord_count], float
joint_qd (array): Generalized joint velocity coordinates, shape [joint_dof_count], float
"""
wp.launch(
kernel=eval_articulation_ik,
dim=model.joint_count,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.joint_type,
model.joint_parent,
model.joint_child,
model.joint_X_p,
model.joint_X_c,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_q_start,
model.joint_qd_start,
],
outputs=[joint_q, joint_qd],
device=model.device,
)
| 23,349 | Python | 33.037901 | 210 | 0.555698 |
NVIDIA/warp/warp/sim/render.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from collections import defaultdict
import numpy as np
import warp as wp
import warp.render
import warp.sim
from warp.render.utils import solidify_mesh, tab10_color_map
# TODO allow NaNs in Warp kernels
NAN = wp.constant(-1.0e8)
@wp.kernel
def compute_contact_points(
body_q: wp.array(dtype=wp.transform),
shape_body: wp.array(dtype=int),
contact_count: wp.array(dtype=int),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
# outputs
contact_pos0: wp.array(dtype=wp.vec3),
contact_pos1: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
count = contact_count[0]
if tid >= count:
contact_pos0[tid] = wp.vec3(NAN, NAN, NAN)
contact_pos1[tid] = wp.vec3(NAN, NAN, NAN)
return
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a == shape_b:
contact_pos0[tid] = wp.vec3(NAN, NAN, NAN)
contact_pos1[tid] = wp.vec3(NAN, NAN, NAN)
return
body_a = shape_body[shape_a]
body_b = shape_body[shape_b]
X_wb_a = wp.transform_identity()
X_wb_b = wp.transform_identity()
if body_a >= 0:
X_wb_a = body_q[body_a]
if body_b >= 0:
X_wb_b = body_q[body_b]
contact_pos0[tid] = wp.transform_point(X_wb_a, contact_point0[tid])
contact_pos1[tid] = wp.transform_point(X_wb_b, contact_point1[tid])
def CreateSimRenderer(renderer):
class SimRenderer(renderer):
use_unique_colors = True
def __init__(
self,
model: warp.sim.Model,
path,
scaling=1.0,
fps=60,
up_axis="Y",
show_rigid_contact_points=False,
contact_points_radius=1e-3,
show_joints=False,
**render_kwargs,
):
# create USD stage
super().__init__(path, scaling=scaling, fps=fps, up_axis=up_axis, **render_kwargs)
self.scaling = scaling
self.cam_axis = "XYZ".index(up_axis.upper())
self.show_rigid_contact_points = show_rigid_contact_points
self.show_joints = show_joints
self.contact_points_radius = contact_points_radius
self.populate(model)
def populate(self, model: warp.sim.Model):
self.skip_rendering = False
self.model = model
self.num_envs = model.num_envs
self.body_names = []
if self.show_rigid_contact_points and model.rigid_contact_max:
self.contact_points0 = wp.array(
np.zeros((model.rigid_contact_max, 3)), dtype=wp.vec3, device=model.device
)
self.contact_points1 = wp.array(
np.zeros((model.rigid_contact_max, 3)), dtype=wp.vec3, device=model.device
)
self.contact_points0_colors = [(1.0, 0.5, 0.0)] * model.rigid_contact_max
self.contact_points1_colors = [(0.0, 0.5, 1.0)] * model.rigid_contact_max
self.body_env = [] # mapping from body index to its environment index
env_id = 0
self.bodies_per_env = model.body_count // self.num_envs
# create rigid body nodes
for b in range(model.body_count):
body_name = f"body_{b}_{self.model.body_name[b].replace(' ', '_')}"
self.body_names.append(body_name)
self.register_body(body_name)
if b > 0 and b % self.bodies_per_env == 0:
env_id += 1
self.body_env.append(env_id)
# create rigid shape children
if self.model.shape_count:
# mapping from hash of geometry to shape ID
self.geo_shape = {}
self.instance_count = 0
self.body_name = {} # mapping from body name to its body ID
self.body_shapes = defaultdict(list) # mapping from body index to its shape IDs
shape_body = model.shape_body.numpy()
shape_geo_src = model.shape_geo_src
shape_geo_type = model.shape_geo.type.numpy()
shape_geo_scale = model.shape_geo.scale.numpy()
shape_geo_thickness = model.shape_geo.thickness.numpy()
shape_geo_is_solid = model.shape_geo.is_solid.numpy()
shape_transform = model.shape_transform.numpy()
shape_visible = model.shape_visible.numpy()
p = np.zeros(3, dtype=np.float32)
q = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32)
scale = np.ones(3)
color = (1.0, 1.0, 1.0)
# loop over shapes excluding the ground plane
for s in range(model.shape_count - 1):
geo_type = shape_geo_type[s]
geo_scale = [float(v) for v in shape_geo_scale[s]]
geo_thickness = float(shape_geo_thickness[s])
geo_is_solid = bool(shape_geo_is_solid[s])
geo_src = shape_geo_src[s]
name = f"shape_{s}"
# shape transform in body frame
body = int(shape_body[s])
if body >= 0 and body < len(self.body_names):
body = self.body_names[body]
else:
body = None
if self.use_unique_colors and body is not None:
color = self._get_new_color()
# shape transform in body frame
X_bs = wp.transform_expand(shape_transform[s])
# check whether we can instance an already created shape with the same geometry
geo_hash = hash((int(geo_type), geo_src, *geo_scale, geo_thickness, geo_is_solid))
if geo_hash in self.geo_shape:
shape = self.geo_shape[geo_hash]
else:
if geo_type == warp.sim.GEO_PLANE:
if s == model.shape_count - 1 and not model.ground:
continue # hide ground plane
# plane mesh
width = geo_scale[0] if geo_scale[0] > 0.0 else 100.0
length = geo_scale[1] if geo_scale[1] > 0.0 else 100.0
shape = self.render_plane(
name, p, q, width, length, color, parent_body=body, is_template=True
)
elif geo_type == warp.sim.GEO_SPHERE:
shape = self.render_sphere(
name, p, q, geo_scale[0], parent_body=body, is_template=True, color=color
)
elif geo_type == warp.sim.GEO_CAPSULE:
shape = self.render_capsule(
name, p, q, geo_scale[0], geo_scale[1], parent_body=body, is_template=True, color=color
)
elif geo_type == warp.sim.GEO_CYLINDER:
shape = self.render_cylinder(
name, p, q, geo_scale[0], geo_scale[1], parent_body=body, is_template=True, color=color
)
elif geo_type == warp.sim.GEO_CONE:
shape = self.render_cone(
name, p, q, geo_scale[0], geo_scale[1], parent_body=body, is_template=True, color=color
)
elif geo_type == warp.sim.GEO_BOX:
shape = self.render_box(
name, p, q, geo_scale, parent_body=body, is_template=True, color=color
)
elif geo_type == warp.sim.GEO_MESH:
if not geo_is_solid:
faces, vertices = solidify_mesh(geo_src.indices, geo_src.vertices, geo_thickness)
else:
faces, vertices = geo_src.indices, geo_src.vertices
shape = self.render_mesh(
name,
vertices,
faces,
pos=p,
rot=q,
scale=geo_scale,
colors=[color],
parent_body=body,
is_template=True,
)
elif geo_type == warp.sim.GEO_SDF:
continue
self.geo_shape[geo_hash] = shape
if shape_visible[s]:
# TODO support dynamic visibility
self.add_shape_instance(
name, shape, body, X_bs.p, X_bs.q, scale, custom_index=s, visible=shape_visible[s]
)
self.instance_count += 1
if self.show_joints and model.joint_count:
joint_type = model.joint_type.numpy()
joint_axis = model.joint_axis.numpy()
joint_axis_start = model.joint_axis_start.numpy()
joint_axis_dim = model.joint_axis_dim.numpy()
joint_parent = model.joint_parent.numpy()
joint_child = model.joint_child.numpy()
joint_tf = model.joint_X_p.numpy()
shape_collision_radius = model.shape_collision_radius.numpy()
y_axis = wp.vec3(0.0, 1.0, 0.0)
color = (1.0, 0.0, 1.0)
shape = self.render_arrow(
"joint_arrow",
None,
None,
base_radius=0.01,
base_height=0.4,
cap_radius=0.02,
cap_height=0.1,
parent_body=None,
is_template=True,
color=color,
)
for i, t in enumerate(joint_type):
if t not in {
warp.sim.JOINT_REVOLUTE,
# warp.sim.JOINT_PRISMATIC,
warp.sim.JOINT_UNIVERSAL,
warp.sim.JOINT_COMPOUND,
warp.sim.JOINT_D6,
}:
continue
tf = joint_tf[i]
body = int(joint_parent[i])
# if body == -1:
# continue
num_linear_axes = int(joint_axis_dim[i][0])
num_angular_axes = int(joint_axis_dim[i][1])
# find a good scale for the arrow based on the average radius
# of the shapes attached to the joint child body
scale = np.ones(3)
child = int(joint_child[i])
if child >= 0:
radii = []
for s in model.body_shapes[child]:
radii.append(shape_collision_radius[s])
if len(radii) > 0:
scale *= np.mean(radii) * 2.0
for a in range(num_linear_axes, num_linear_axes + num_angular_axes):
index = joint_axis_start[i] + a
axis = joint_axis[index]
if np.linalg.norm(axis) < 1e-6:
continue
p = wp.vec3(tf[:3])
q = wp.quat(tf[3:])
# compute rotation between axis and y
axis = axis / np.linalg.norm(axis)
q = q * wp.quat_between_vectors(wp.vec3(axis), y_axis)
name = f"joint_{i}_{a}"
self.add_shape_instance(name, shape, body, p, q, scale, color1=color, color2=color)
self.instance_count += 1
if model.ground:
self.render_ground(plane=model.ground_plane_params)
if hasattr(self, "complete_setup"):
self.complete_setup()
def _get_new_color(self):
return tab10_color_map(self.instance_count)
def render(self, state: warp.sim.State):
"""
Updates the renderer with the given simulation state.
Args:
state (warp.sim.State): The simulation state to render.
"""
if self.skip_rendering:
return
if self.model.particle_count:
particle_q = state.particle_q.numpy()
# render particles
self.render_points(
"particles", particle_q, radius=self.model.particle_radius.numpy(), colors=(0.8, 0.3, 0.2)
)
# render tris
if self.model.tri_count:
self.render_mesh(
"surface",
particle_q,
self.model.tri_indices.numpy().flatten(),
colors=(((0.75, 0.25, 0.0),) * len(particle_q)),
)
# render springs
if self.model.spring_count:
self.render_line_list(
"springs", particle_q, self.model.spring_indices.numpy().flatten(), (0.25, 0.5, 0.25), 0.02
)
# render muscles
if self.model.muscle_count:
body_q = state.body_q.numpy()
muscle_start = self.model.muscle_start.numpy()
muscle_links = self.model.muscle_bodies.numpy()
muscle_points = self.model.muscle_points.numpy()
muscle_activation = self.model.muscle_activation.numpy()
# for s in self.skeletons:
# # for mesh, link in s.mesh_map.items():
# # if link != -1:
# # X_sc = wp.transform_expand(self.state.body_X_sc[link].tolist())
# # #self.renderer.add_mesh(mesh, "../assets/snu/OBJ/" + mesh + ".usd", X_sc, 1.0, self.render_time)
# # self.renderer.add_mesh(mesh, "../assets/snu/OBJ/" + mesh + ".usd", X_sc, 1.0, self.render_time)
for m in range(self.model.muscle_count):
start = int(muscle_start[m])
end = int(muscle_start[m + 1])
points = []
for w in range(start, end):
link = muscle_links[w]
point = muscle_points[w]
X_sc = wp.transform_expand(body_q[link][0])
points.append(wp.transform_point(X_sc, point).tolist())
self.render_line_strip(
name=f"muscle_{m}", vertices=points, radius=0.0075, color=(muscle_activation[m], 0.2, 0.5)
)
# update bodies
if self.model.body_count:
self.update_body_transforms(state.body_q)
if self.show_rigid_contact_points and self.model.rigid_contact_max:
wp.launch(
kernel=compute_contact_points,
dim=self.model.rigid_contact_max,
inputs=[
state.body_q,
self.model.shape_body,
self.model.rigid_contact_count,
self.model.rigid_contact_shape0,
self.model.rigid_contact_shape1,
self.model.rigid_contact_point0,
self.model.rigid_contact_point1,
],
outputs=[
self.contact_points0,
self.contact_points1,
],
device=self.model.device,
)
self.render_points(
"contact_points0",
self.contact_points0.numpy(),
radius=self.contact_points_radius * self.scaling,
colors=self.contact_points0_colors,
)
self.render_points(
"contact_points1",
self.contact_points1.numpy(),
radius=self.contact_points_radius * self.scaling,
colors=self.contact_points1_colors,
)
return SimRenderer
SimRendererUsd = CreateSimRenderer(wp.render.UsdRenderer)
SimRendererOpenGL = CreateSimRenderer(wp.render.OpenGLRenderer)
SimRenderer = SimRendererUsd
| 17,794 | Python | 41.57177 | 128 | 0.462796 |
NVIDIA/warp/warp/sim/utils.py | from typing import List, Tuple
import numpy as np
import warp as wp
@wp.func
def velocity_at_point(qd: wp.spatial_vector, r: wp.vec3):
"""
Returns the velocity of a point relative to the frame with the given spatial velocity.
Args:
qd (spatial_vector): The spatial velocity of the frame.
r (vec3): The position of the point relative to the frame.
Returns:
vec3: The velocity of the point.
"""
return wp.cross(wp.spatial_top(qd), r) + wp.spatial_bottom(qd)
@wp.func
def quat_twist(axis: wp.vec3, q: wp.quat):
"""
Returns the twist around an axis.
"""
# project imaginary part onto axis
a = wp.vec3(q[0], q[1], q[2])
proj = wp.dot(a, axis)
a = proj * axis
# if proj < 0.0:
# # ensure twist points in same direction as axis
# a = -a
return wp.normalize(wp.quat(a[0], a[1], a[2], q[3]))
@wp.func
def quat_twist_angle(axis: wp.vec3, q: wp.quat):
"""
Returns the angle of the twist around an axis.
"""
return 2.0 * wp.acos(quat_twist(axis, q)[3])
@wp.func
def quat_decompose(q: wp.quat):
"""
Decompose a quaternion into a sequence of 3 rotations around x,y',z' respectively, i.e.: q = q_z''q_y'q_x.
"""
R = wp.mat33(
wp.quat_rotate(q, wp.vec3(1.0, 0.0, 0.0)),
wp.quat_rotate(q, wp.vec3(0.0, 1.0, 0.0)),
wp.quat_rotate(q, wp.vec3(0.0, 0.0, 1.0)),
)
# https://www.sedris.org/wg8home/Documents/WG80485.pdf
phi = wp.atan2(R[1, 2], R[2, 2])
sinp = -R[0, 2]
if wp.abs(sinp) >= 1.0:
theta = wp.HALF_PI * wp.sign(sinp)
else:
theta = wp.asin(-R[0, 2])
psi = wp.atan2(R[0, 1], R[0, 0])
return -wp.vec3(phi, theta, psi)
@wp.func
def quat_to_rpy(q: wp.quat):
"""
Convert a quaternion into Euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
x = q[0]
y = q[1]
z = q[2]
w = q[3]
t0 = 2.0 * (w * x + y * z)
t1 = 1.0 - 2.0 * (x * x + y * y)
roll_x = wp.atan2(t0, t1)
t2 = 2.0 * (w * y - z * x)
t2 = wp.clamp(t2, -1.0, 1.0)
pitch_y = wp.asin(t2)
t3 = 2.0 * (w * z + x * y)
t4 = 1.0 - 2.0 * (y * y + z * z)
yaw_z = wp.atan2(t3, t4)
return wp.vec3(roll_x, pitch_y, yaw_z)
@wp.func
def quat_to_euler(q: wp.quat, i: int, j: int, k: int) -> wp.vec3:
"""
Convert a quaternion into Euler angles.
:math:`i, j, k` are the indices in :math:`[0, 1, 2]` of the axes to use
(:math:`i \\neq j, j \\neq k`).
Reference: https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0276302
Args:
q (quat): The quaternion to convert
i (int): The index of the first axis
j (int): The index of the second axis
k (int): The index of the third axis
Returns:
vec3: The Euler angles (in radians)
"""
# i, j, k are actually assumed to follow 1-based indexing but
# we want to be compatible with quat_from_euler
i += 1
j += 1
k += 1
not_proper = True
if i == k:
not_proper = False
k = 6 - i - j # because i + j + k = 1 + 2 + 3 = 6
e = float((i - j) * (j - k) * (k - i)) / 2.0 # Levi-Civita symbol
a = q[0]
b = q[i]
c = q[j]
d = q[k] * e
if not_proper:
a -= q[j]
b += q[k] * e
c += q[0]
d -= q[i]
t2 = wp.acos(2.0 * (a * a + b * b) / (a * a + b * b + c * c + d * d) - 1.0)
tp = wp.atan2(b, a)
tm = wp.atan2(d, c)
t1 = 0.0
t3 = 0.0
if wp.abs(t2) < 1e-6:
t3 = 2.0 * tp - t1
elif wp.abs(t2 - wp.HALF_PI) < 1e-6:
t3 = 2.0 * tm + t1
else:
t1 = tp - tm
t3 = tp + tm
if not_proper:
t2 -= wp.HALF_PI
t3 *= e
return wp.vec3(t1, t2, t3)
@wp.func
def quat_from_euler(e: wp.vec3, i: int, j: int, k: int) -> wp.quat:
"""
Convert Euler angles to a quaternion.
:math:`i, j, k` are the indices in :math:`[0, 1, 2]` of the axes in which the Euler angles are provided
(:math:`i \\neq j, j \\neq k`), e.g. (0, 1, 2) for Euler sequence XYZ.
Args:
e (vec3): The Euler angles (in radians)
i (int): The index of the first axis
j (int): The index of the second axis
k (int): The index of the third axis
Returns:
quat: The quaternion
"""
# Half angles
half_e = e / 2.0
# Precompute sines and cosines of half angles
cr = wp.cos(half_e[i])
sr = wp.sin(half_e[i])
cp = wp.cos(half_e[j])
sp = wp.sin(half_e[j])
cy = wp.cos(half_e[k])
sy = wp.sin(half_e[k])
# Components of the quaternion based on the rotation sequence
return wp.quat(
(cy * sr * cp - sy * cr * sp),
(cy * cr * sp + sy * sr * cp),
(sy * cr * cp - cy * sr * sp),
(cy * cr * cp + sy * sr * sp),
)
@wp.func
def transform_twist(t: wp.transform, x: wp.spatial_vector):
# Frank & Park definition 3.20, pg 100
q = wp.transform_get_rotation(t)
p = wp.transform_get_translation(t)
w = wp.spatial_top(x)
v = wp.spatial_bottom(x)
w = wp.quat_rotate(q, w)
v = wp.quat_rotate(q, v) + wp.cross(p, w)
return wp.spatial_vector(w, v)
@wp.func
def transform_wrench(t: wp.transform, x: wp.spatial_vector):
q = wp.transform_get_rotation(t)
p = wp.transform_get_translation(t)
w = wp.spatial_top(x)
v = wp.spatial_bottom(x)
v = wp.quat_rotate(q, v)
w = wp.quat_rotate(q, w) + wp.cross(p, v)
return wp.spatial_vector(w, v)
@wp.func
def transform_inertia(t: wp.transform, I: wp.spatial_matrix):
"""
Computes adj_t^-T*I*adj_t^-1 (tensor change of coordinates).
(Frank & Park, section 8.2.3, pg 290)
"""
t_inv = wp.transform_inverse(t)
q = wp.transform_get_rotation(t_inv)
p = wp.transform_get_translation(t_inv)
r1 = wp.quat_rotate(q, wp.vec3(1.0, 0.0, 0.0))
r2 = wp.quat_rotate(q, wp.vec3(0.0, 1.0, 0.0))
r3 = wp.quat_rotate(q, wp.vec3(0.0, 0.0, 1.0))
R = wp.mat33(r1, r2, r3)
S = wp.mul(wp.skew(p), R)
T = wp.spatial_adjoint(R, S)
return wp.mul(wp.mul(wp.transpose(T), I), T)
@wp.func
def boltzmann(a: float, b: float, alpha: float):
e1 = wp.exp(alpha * a)
e2 = wp.exp(alpha * b)
return (a * e1 + b * e2) / (e1 + e2)
@wp.func
def smooth_max(a: float, b: float, eps: float):
d = a - b
return 0.5 * (a + b + wp.sqrt(d * d + eps))
@wp.func
def smooth_min(a: float, b: float, eps: float):
d = a - b
return 0.5 * (a + b - wp.sqrt(d * d + eps))
@wp.func
def leaky_max(a: float, b: float):
return smooth_max(a, b, 1e-5)
@wp.func
def leaky_min(a: float, b: float):
return smooth_min(a, b, 1e-5)
@wp.func
def vec_min(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.min(a[0], b[0]), wp.min(a[1], b[1]), wp.min(a[2], b[2]))
@wp.func
def vec_max(a: wp.vec3, b: wp.vec3):
return wp.vec3(wp.max(a[0], b[0]), wp.max(a[1], b[1]), wp.max(a[2], b[2]))
@wp.func
def vec_leaky_min(a: wp.vec3, b: wp.vec3):
return wp.vec3(leaky_min(a[0], b[0]), leaky_min(a[1], b[1]), leaky_min(a[2], b[2]))
@wp.func
def vec_leaky_max(a: wp.vec3, b: wp.vec3):
return wp.vec3(leaky_max(a[0], b[0]), leaky_max(a[1], b[1]), leaky_max(a[2], b[2]))
@wp.func
def vec_abs(a: wp.vec3):
return wp.vec3(wp.abs(a[0]), wp.abs(a[1]), wp.abs(a[2]))
def load_mesh(filename: str, method: str = None):
"""
Loads a 3D triangular surface mesh from a file.
Args:
filename (str): The path to the 3D model file (obj, and other formats supported by the different methods) to load.
method (str): The method to use for loading the mesh (default None). Can be either `"trimesh"`, `"meshio"`, `"pcu"`, or `"openmesh"`. If None, every method is tried and the first successful mesh import where the number of vertices is greater than 0 is returned.
Returns:
Tuple of (mesh_points, mesh_indices), where mesh_points is a Nx3 numpy array of vertex positions (float32),
and mesh_indices is a Mx3 numpy array of vertex indices (int32) for the triangular faces.
"""
import os
if not os.path.exists(filename):
raise ValueError(f"File not found: {filename}")
def load_mesh_with_method(method):
if method == "meshio":
import meshio
m = meshio.read(filename)
mesh_points = np.array(m.points)
mesh_indices = np.array(m.cells[0].data, dtype=np.int32)
elif method == "openmesh":
import openmesh
m = openmesh.read_trimesh(filename)
mesh_points = np.array(m.points())
mesh_indices = np.array(m.face_vertex_indices(), dtype=np.int32)
elif method == "pcu":
import point_cloud_utils as pcu
mesh_points, mesh_indices = pcu.load_mesh_vf(filename)
mesh_indices = mesh_indices.flatten()
else:
import trimesh
m = trimesh.load(filename)
if hasattr(m, "geometry"):
# multiple meshes are contained in a scene; combine to one mesh
mesh_points = []
mesh_indices = []
index_offset = 0
for geom in m.geometry.values():
vertices = np.array(geom.vertices, dtype=np.float32)
faces = np.array(geom.faces.flatten(), dtype=np.int32)
mesh_points.append(vertices)
mesh_indices.append(faces + index_offset)
index_offset += len(vertices)
mesh_points = np.concatenate(mesh_points, axis=0)
mesh_indices = np.concatenate(mesh_indices)
else:
# a single mesh
mesh_points = np.array(m.vertices, dtype=np.float32)
mesh_indices = np.array(m.faces.flatten(), dtype=np.int32)
return mesh_points, mesh_indices
if method is None:
methods = ["trimesh", "meshio", "pcu", "openmesh"]
for method in methods:
try:
mesh = load_mesh_with_method(method)
if mesh is not None and len(mesh[0]) > 0:
return mesh
except Exception:
pass
raise ValueError(f"Failed to load mesh using any of the methods: {methods}")
else:
mesh = load_mesh_with_method(method)
if mesh is None or len(mesh[0]) == 0:
raise ValueError(f"Failed to load mesh using method {method}")
return mesh
def visualize_meshes(
meshes: List[Tuple[list, list]], num_cols=0, num_rows=0, titles=None, scale_axes=True, show_plot=True
):
# render meshes in a grid with matplotlib
import matplotlib.pyplot as plt
if titles is None:
titles = []
num_cols = min(num_cols, len(meshes))
num_rows = min(num_rows, len(meshes))
if num_cols and not num_rows:
num_rows = int(np.ceil(len(meshes) / num_cols))
elif num_rows and not num_cols:
num_cols = int(np.ceil(len(meshes) / num_rows))
else:
num_cols = len(meshes)
num_rows = 1
vertices = [np.array(v).reshape((-1, 3)) for v, _ in meshes]
faces = [np.array(f, dtype=np.int32).reshape((-1, 3)) for _, f in meshes]
if scale_axes:
ranges = np.array([v.max(axis=0) - v.min(axis=0) for v in vertices])
max_range = ranges.max()
mid_points = np.array([v.max(axis=0) + v.min(axis=0) for v in vertices]) * 0.5
fig = plt.figure(figsize=(12, 6))
for i, (vertices, faces) in enumerate(meshes):
ax = fig.add_subplot(num_rows, num_cols, i + 1, projection="3d")
if i < len(titles):
ax.set_title(titles[i])
ax.plot_trisurf(vertices[:, 0], vertices[:, 1], vertices[:, 2], triangles=faces, edgecolor="k")
if scale_axes:
mid = mid_points[i]
ax.set_xlim(mid[0] - max_range, mid[0] + max_range)
ax.set_ylim(mid[1] - max_range, mid[1] + max_range)
ax.set_zlim(mid[2] - max_range, mid[2] + max_range)
if show_plot:
plt.show()
return fig
| 12,194 | Python | 28.456522 | 269 | 0.556175 |
NVIDIA/warp/warp/sim/model.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""A module for building simulation models and state."""
import copy
import math
from typing import List, Optional, Tuple
import numpy as np
import warp as wp
from .inertia import (
compute_box_inertia,
compute_capsule_inertia,
compute_cone_inertia,
compute_cylinder_inertia,
compute_mesh_inertia,
compute_sphere_inertia,
transform_inertia,
)
Vec3 = List[float]
Vec4 = List[float]
Quat = List[float]
Mat33 = List[float]
Transform = Tuple[Vec3, Quat]
# Particle flags
PARTICLE_FLAG_ACTIVE = wp.constant(wp.uint32(1 << 0))
# Shape geometry types
GEO_SPHERE = wp.constant(0)
GEO_BOX = wp.constant(1)
GEO_CAPSULE = wp.constant(2)
GEO_CYLINDER = wp.constant(3)
GEO_CONE = wp.constant(4)
GEO_MESH = wp.constant(5)
GEO_SDF = wp.constant(6)
GEO_PLANE = wp.constant(7)
GEO_NONE = wp.constant(8)
# Types of joints linking rigid bodies
JOINT_PRISMATIC = wp.constant(0)
JOINT_REVOLUTE = wp.constant(1)
JOINT_BALL = wp.constant(2)
JOINT_FIXED = wp.constant(3)
JOINT_FREE = wp.constant(4)
JOINT_COMPOUND = wp.constant(5)
JOINT_UNIVERSAL = wp.constant(6)
JOINT_DISTANCE = wp.constant(7)
JOINT_D6 = wp.constant(8)
# Joint axis control mode types
JOINT_MODE_FORCE = wp.constant(0)
JOINT_MODE_TARGET_POSITION = wp.constant(1)
JOINT_MODE_TARGET_VELOCITY = wp.constant(2)
def flag_to_int(flag):
"""Converts a flag to an integer."""
if type(flag) in wp.types.int_types:
return flag.value
return int(flag)
# Material properties pertaining to rigid shape contact dynamics
@wp.struct
class ModelShapeMaterials:
ke: wp.array(dtype=float) # The contact elastic stiffness (only used by the Euler integrators)
kd: wp.array(dtype=float) # The contact damping stiffness (only used by the Euler integrators)
kf: wp.array(dtype=float) # The contact friction stiffness (only used by the Euler integrators)
ka: wp.array(
dtype=float
) # The contact adhesion distance (values greater than 0 mean adhesive contact; only used by the Euler integrators)
mu: wp.array(dtype=float) # The coefficient of friction
restitution: wp.array(dtype=float) # The coefficient of restitution (only used by XPBD integrator)
# Shape properties of geometry
@wp.struct
class ModelShapeGeometry:
type: wp.array(dtype=wp.int32) # The type of geometry (GEO_SPHERE, GEO_BOX, etc.)
is_solid: wp.array(dtype=wp.uint8) # Indicates whether the shape is solid or hollow
thickness: wp.array(
dtype=float
) # The thickness of the shape (used for collision detection, and inertia computation of hollow shapes)
source: wp.array(dtype=wp.uint64) # Pointer to the source geometry (in case of a mesh, zero otherwise)
scale: wp.array(dtype=wp.vec3) # The 3D scale of the shape
# Axis (linear or angular) of a joint that can have bounds and be driven towards a target
class JointAxis:
"""
Describes a joint axis that can have limits and be driven towards a target.
Attributes:
axis (3D vector or JointAxis): The 3D axis that this JointAxis object describes, or alternatively another JointAxis object to copy from
limit_lower (float): The lower position limit of the joint axis
limit_upper (float): The upper position limit of the joint axis
limit_ke (float): The elastic stiffness of the joint axis limits, only respected by :class:`SemiImplicitIntegrator` and :class:`FeatherstoneIntegrator`
limit_kd (float): The damping stiffness of the joint axis limits, only respected by :class:`SemiImplicitIntegrator` and :class:`FeatherstoneIntegrator`
action (float): The force applied by default to this joint axis, or the target position or velocity (depending on the mode, see `Joint modes`_) of the joint axis
target_ke (float): The proportional gain of the joint axis target drive PD controller
target_kd (float): The derivative gain of the joint axis target drive PD controller
mode (int): The mode of the joint axis, see `Joint modes`_
"""
def __init__(
self,
axis,
limit_lower=-math.inf,
limit_upper=math.inf,
limit_ke=100.0,
limit_kd=10.0,
action=None,
target_ke=0.0,
target_kd=0.0,
mode=JOINT_MODE_FORCE,
):
if isinstance(axis, JointAxis):
self.axis = axis.axis
self.limit_lower = axis.limit_lower
self.limit_upper = axis.limit_upper
self.limit_ke = axis.limit_ke
self.limit_kd = axis.limit_kd
self.action = axis.action
self.target_ke = axis.target_ke
self.target_kd = axis.target_kd
self.mode = axis.mode
else:
self.axis = wp.normalize(wp.vec3(axis))
self.limit_lower = limit_lower
self.limit_upper = limit_upper
self.limit_ke = limit_ke
self.limit_kd = limit_kd
if action is not None:
self.action = action
elif mode == JOINT_MODE_TARGET_POSITION and (limit_lower > 0.0 or limit_upper < 0.0):
self.action = 0.5 * (limit_lower + limit_upper)
else:
self.action = 0.0
self.target_ke = target_ke
self.target_kd = target_kd
self.mode = mode
class SDF:
"""Describes a signed distance field for simulation
Attributes:
volume (Volume): The volume defining the SDF
I (Mat33): 3x3 inertia matrix of the SDF
mass (float): The total mass of the SDF
com (Vec3): The center of mass of the SDF
"""
def __init__(self, volume=None, I=None, mass=1.0, com=None):
self.volume = volume
self.I = I if I is not None else wp.mat33(np.eye(3))
self.mass = mass
self.com = com if com is not None else wp.vec3()
# Need to specify these for now
self.has_inertia = True
self.is_solid = True
def finalize(self, device=None):
return self.volume.id
def __hash__(self):
return hash((self.volume.id))
class Mesh:
"""Describes a triangle collision mesh for simulation
Example mesh creation from a triangle OBJ mesh file:
====================================================
See :func:`load_mesh` which is provided as a utility function.
.. code-block:: python
import numpy as np
import warp as wp
import warp.sim
import openmesh
m = openmesh.read_trimesh("mesh.obj")
mesh_points = np.array(m.points())
mesh_indices = np.array(m.face_vertex_indices(), dtype=np.int32).flatten()
mesh = wp.sim.Mesh(mesh_points, mesh_indices)
Attributes:
vertices (List[Vec3]): Mesh 3D vertices points
indices (List[int]): Mesh indices as a flattened list of vertex indices describing triangles
I (Mat33): 3x3 inertia matrix of the mesh assuming density of 1.0 (around the center of mass)
mass (float): The total mass of the body assuming density of 1.0
com (Vec3): The center of mass of the body
"""
def __init__(self, vertices: List[Vec3], indices: List[int], compute_inertia=True, is_solid=True):
"""Construct a Mesh object from a triangle mesh
The mesh center of mass and inertia tensor will automatically be
calculated using a density of 1.0. This computation is only valid
if the mesh is closed (two-manifold).
Args:
vertices: List of vertices in the mesh
indices: List of triangle indices, 3 per-element
compute_inertia: If True, the mass, inertia tensor and center of mass will be computed assuming density of 1.0
is_solid: If True, the mesh is assumed to be a solid during inertia computation, otherwise it is assumed to be a hollow surface
"""
self.vertices = np.array(vertices).reshape(-1, 3)
self.indices = np.array(indices, dtype=np.int32).flatten()
self.is_solid = is_solid
self.has_inertia = compute_inertia
if compute_inertia:
self.mass, self.com, self.I, _ = compute_mesh_inertia(1.0, vertices, indices, is_solid=is_solid)
else:
self.I = wp.mat33(np.eye(3))
self.mass = 1.0
self.com = wp.vec3()
# construct simulation ready buffers from points
def finalize(self, device=None):
"""
Constructs a simulation-ready :class:`Mesh` object from the mesh data and returns its ID.
Args:
device: The device on which to allocate the mesh buffers
Returns:
The ID of the simulation-ready :class:`Mesh`
"""
with wp.ScopedDevice(device):
pos = wp.array(self.vertices, dtype=wp.vec3)
vel = wp.zeros_like(pos)
indices = wp.array(self.indices, dtype=wp.int32)
self.mesh = wp.Mesh(points=pos, velocities=vel, indices=indices)
return self.mesh.id
def __hash__(self):
"""
Computes a hash of the mesh data for use in caching. The hash considers the mesh vertices, indices, and whether the mesh is solid or not.
"""
return hash((tuple(np.array(self.vertices).flatten()), tuple(np.array(self.indices).flatten()), self.is_solid))
class State:
"""The State object holds all *time-varying* data for a model.
Time-varying data includes particle positions, velocities, rigid body states, and
anything that is output from the integrator as derived data, e.g.: forces.
The exact attributes depend on the contents of the model. State objects should
generally be created using the :func:`Model.state()` function.
Attributes:
particle_q (array): Array of 3D particle positions, shape [particle_count], :class:`vec3`
particle_qd (array): Array of 3D particle velocities, shape [particle_count], :class:`vec3`
particle_f (array): Array of 3D particle forces, shape [particle_count], :class:`vec3`
body_q (array): Array of body coordinates (7-dof transforms) in maximal coordinates, shape [body_count], :class:`transform`
body_qd (array): Array of body velocities in maximal coordinates (first 3 entries represent angular velocity, last 3 entries represent linear velocity), shape [body_count], :class:`spatial_vector`
body_f (array): Array of body forces in maximal coordinates (first 3 entries represent torque, last 3 entries represent linear force), shape [body_count], :class:`spatial_vector`
Note:
:attr:`body_f` represents external wrenches in world frame and denotes wrenches measured w.r.t. to the body's center of mass for all integrators except :class:`FeatherstoneIntegrator` which assumes the wrenches are measured w.r.t. world origin.
joint_q (array): Array of generalized joint coordinates, shape [joint_coord_count], float
joint_qd (array): Array of generalized joint velocities, shape [joint_dof_count], float
"""
def __init__(self):
self.particle_q = None
self.particle_qd = None
self.particle_f = None
self.body_q = None
self.body_qd = None
self.body_f = None
self.joint_q = None
self.joint_qd = None
def clear_forces(self):
"""Clears all forces (for particles and bodies) in the state object."""
with wp.ScopedTimer("clear_forces", False):
if self.particle_count:
self.particle_f.zero_()
if self.body_count:
self.body_f.zero_()
@property
def requires_grad(self):
"""Indicates whether the state arrays have gradient computation enabled."""
if self.particle_q:
return self.particle_q.requires_grad
if self.body_q:
return self.body_q.requires_grad
return False
@property
def body_count(self):
"""The number of bodies represented in the state."""
if self.body_q is None:
return 0
return len(self.body_q)
@property
def particle_count(self):
"""The number of particles represented in the state."""
if self.particle_q is None:
return 0
return len(self.particle_q)
@property
def joint_coord_count(self):
"""The number of generalized joint position coordinates represented in the state."""
if self.joint_q is None:
return 0
return len(self.joint_q)
@property
def joint_dof_count(self):
"""The number of generalized joint velocity coordinates represented in the state."""
if self.joint_qd is None:
return 0
return len(self.joint_qd)
class Control:
"""
The Control object holds all *time-varying* control data for a model.
Time-varying control data includes joint control inputs, muscle activations, and activation forces for triangle and tetrahedral elements.
The exact attributes depend on the contents of the model. Control objects should generally be created using the :func:`Model.control()` function.
Attributes:
joint_act (array): Array of joint control inputs, shape [joint_axis_count], float
tri_activations (array): Array of triangle element activations, shape [tri_count], float
tet_activations (array): Array of tetrahedral element activations, shape [tet_count], float
muscle_activations (array): Array of muscle activations, shape [muscle_count], float
"""
def __init__(self, model):
"""
Args:
model (Model): The model to use as a reference for the control inputs
"""
self.model = model
self.joint_act = None
self.tri_activations = None
self.tet_activations = None
self.muscle_activations = None
def reset(self):
"""
Resets the control inputs to their initial state defined in :class:`Model`.
"""
if self.joint_act is not None:
self.joint_act.assign(self.model.joint_act)
if self.tri_activations is not None:
self.tri_activations.assign(self.model.tri_activations)
if self.tet_activations is not None:
self.tet_activations.assign(self.model.tet_activations)
if self.muscle_activations is not None:
self.muscle_activations.assign(self.model.muscle_activations)
def compute_shape_mass(type, scale, src, density, is_solid, thickness):
"""Computes the mass, center of mass and 3x3 inertia tensor of a shape
Args:
type: The type of shape (GEO_SPHERE, GEO_BOX, etc.)
scale: The scale of the shape
src: The source shape (Mesh or SDF)
density: The density of the shape
is_solid: Whether the shape is solid or hollow
thickness: The thickness of the shape (used for collision detection, and inertia computation of hollow shapes)
Returns:
The mass, center of mass and 3x3 inertia tensor of the shape
"""
if density == 0.0 or type == GEO_PLANE: # zero density means fixed
return 0.0, wp.vec3(), wp.mat33()
if type == GEO_SPHERE:
solid = compute_sphere_inertia(density, scale[0])
if is_solid:
return solid
else:
hollow = compute_sphere_inertia(density, scale[0] - thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_BOX:
w, h, d = scale * 2.0
solid = compute_box_inertia(density, w, h, d)
if is_solid:
return solid
else:
hollow = compute_box_inertia(density, w - thickness, h - thickness, d - thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_CAPSULE:
r, h = scale[0], scale[1] * 2.0
solid = compute_capsule_inertia(density, r, h)
if is_solid:
return solid
else:
hollow = compute_capsule_inertia(density, r - thickness, h - 2.0 * thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_CYLINDER:
r, h = scale[0], scale[1] * 2.0
solid = compute_cylinder_inertia(density, r, h)
if is_solid:
return solid
else:
hollow = compute_cylinder_inertia(density, r - thickness, h - 2.0 * thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_CONE:
r, h = scale[0], scale[1] * 2.0
solid = compute_cone_inertia(density, r, h)
if is_solid:
return solid
else:
hollow = compute_cone_inertia(density, r - thickness, h - 2.0 * thickness)
return solid[0] - hollow[0], solid[1], solid[2] - hollow[2]
elif type == GEO_MESH or type == GEO_SDF:
if src.has_inertia and src.mass > 0.0 and src.is_solid == is_solid:
m, c, I = src.mass, src.com, src.I
sx, sy, sz = scale
mass_ratio = sx * sy * sz * density
m_new = m * mass_ratio
c_new = wp.cw_mul(c, scale)
Ixx = I[0, 0] * (sy**2 + sz**2) / 2 * mass_ratio
Iyy = I[1, 1] * (sx**2 + sz**2) / 2 * mass_ratio
Izz = I[2, 2] * (sx**2 + sy**2) / 2 * mass_ratio
Ixy = I[0, 1] * sx * sy * mass_ratio
Ixz = I[0, 2] * sx * sz * mass_ratio
Iyz = I[1, 2] * sy * sz * mass_ratio
I_new = wp.mat33([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])
return m_new, c_new, I_new
elif type == GEO_MESH:
# fall back to computing inertia from mesh geometry
vertices = np.array(src.vertices) * np.array(scale)
m, c, I, vol = compute_mesh_inertia(density, vertices, src.indices, is_solid, thickness)
return m, c, I
raise ValueError("Unsupported shape type: {}".format(type))
class Model:
"""Holds the definition of the simulation model
This class holds the non-time varying description of the system, i.e.:
all geometry, constraints, and parameters used to describe the simulation.
Attributes:
requires_grad (float): Indicates whether the model was finalized (see :meth:`ModelBuilder.finalize`) with gradient computation enabled
num_envs (int): Number of articulation environments that were added to the ModelBuilder via `add_builder`
particle_q (array): Particle positions, shape [particle_count, 3], float
particle_qd (array): Particle velocities, shape [particle_count, 3], float
particle_mass (array): Particle mass, shape [particle_count], float
particle_inv_mass (array): Particle inverse mass, shape [particle_count], float
particle_radius (array): Particle radius, shape [particle_count], float
particle_max_radius (float): Maximum particle radius (useful for HashGrid construction)
particle_ke (array): Particle normal contact stiffness (used by :class:`SemiImplicitIntegrator`), shape [particle_count], float
particle_kd (array): Particle normal contact damping (used by :class:`SemiImplicitIntegrator`), shape [particle_count], float
particle_kf (array): Particle friction force stiffness (used by :class:`SemiImplicitIntegrator`), shape [particle_count], float
particle_mu (array): Particle friction coefficient, shape [particle_count], float
particle_cohesion (array): Particle cohesion strength, shape [particle_count], float
particle_adhesion (array): Particle adhesion strength, shape [particle_count], float
particle_grid (HashGrid): HashGrid instance used for accelerated simulation of particle interactions
particle_flags (array): Particle enabled state, shape [particle_count], bool
particle_max_velocity (float): Maximum particle velocity (to prevent instability)
shape_transform (array): Rigid shape transforms, shape [shape_count, 7], float
shape_visible (array): Rigid shape visibility, shape [shape_count], bool
shape_body (array): Rigid shape body index, shape [shape_count], int
body_shapes (dict): Mapping from body index to list of attached shape indices
shape_materials (ModelShapeMaterials): Rigid shape contact materials, shape [shape_count], float
shape_shape_geo (ModelShapeGeometry): Shape geometry properties (geo type, scale, thickness, etc.), shape [shape_count, 3], float
shape_geo_src (list): List of `wp.Mesh` instances used for rendering of mesh geometry
shape_collision_group (list): Collision group of each shape, shape [shape_count], int
shape_collision_group_map (dict): Mapping from collision group to list of shape indices
shape_collision_filter_pairs (set): Pairs of shape indices that should not collide
shape_collision_radius (array): Collision radius of each shape used for bounding sphere broadphase collision checking, shape [shape_count], float
shape_ground_collision (list): Indicates whether each shape should collide with the ground, shape [shape_count], bool
shape_shape_collision (list): Indicates whether each shape should collide with any other shape, shape [shape_count], bool
shape_contact_pairs (array): Pairs of shape indices that may collide, shape [contact_pair_count, 2], int
shape_ground_contact_pairs (array): Pairs of shape, ground indices that may collide, shape [ground_contact_pair_count, 2], int
spring_indices (array): Particle spring indices, shape [spring_count*2], int
spring_rest_length (array): Particle spring rest length, shape [spring_count], float
spring_stiffness (array): Particle spring stiffness, shape [spring_count], float
spring_damping (array): Particle spring damping, shape [spring_count], float
spring_control (array): Particle spring activation, shape [spring_count], float
tri_indices (array): Triangle element indices, shape [tri_count*3], int
tri_poses (array): Triangle element rest pose, shape [tri_count, 2, 2], float
tri_activations (array): Triangle element activations, shape [tri_count], float
tri_materials (array): Triangle element materials, shape [tri_count, 5], float
edge_indices (array): Bending edge indices, shape [edge_count*4], int
edge_rest_angle (array): Bending edge rest angle, shape [edge_count], float
edge_bending_properties (array): Bending edge stiffness and damping parameters, shape [edge_count, 2], float
tet_indices (array): Tetrahedral element indices, shape [tet_count*4], int
tet_poses (array): Tetrahedral rest poses, shape [tet_count, 3, 3], float
tet_activations (array): Tetrahedral volumetric activations, shape [tet_count], float
tet_materials (array): Tetrahedral elastic parameters in form :math:`k_{mu}, k_{lambda}, k_{damp}`, shape [tet_count, 3]
muscle_start (array): Start index of the first muscle point per muscle, shape [muscle_count], int
muscle_params (array): Muscle parameters, shape [muscle_count, 5], float
muscle_bodies (array): Body indices of the muscle waypoints, int
muscle_points (array): Local body offset of the muscle waypoints, float
muscle_activations (array): Muscle activations, shape [muscle_count], float
body_q (array): Poses of rigid bodies used for state initialization, shape [body_count, 7], float
body_qd (array): Velocities of rigid bodies used for state initialization, shape [body_count, 6], float
body_com (array): Rigid body center of mass (in local frame), shape [body_count, 7], float
body_inertia (array): Rigid body inertia tensor (relative to COM), shape [body_count, 3, 3], float
body_inv_inertia (array): Rigid body inverse inertia tensor (relative to COM), shape [body_count, 3, 3], float
body_mass (array): Rigid body mass, shape [body_count], float
body_inv_mass (array): Rigid body inverse mass, shape [body_count], float
body_name (list): Rigid body names, shape [body_count], str
joint_q (array): Generalized joint positions used for state initialization, shape [joint_coord_count], float
joint_qd (array): Generalized joint velocities used for state initialization, shape [joint_dof_count], float
joint_act (array): Generalized joint control inputs, shape [joint_axis_count], float
joint_type (array): Joint type, shape [joint_count], int
joint_parent (array): Joint parent body indices, shape [joint_count], int
joint_child (array): Joint child body indices, shape [joint_count], int
joint_X_p (array): Joint transform in parent frame, shape [joint_count, 7], float
joint_X_c (array): Joint mass frame in child frame, shape [joint_count, 7], float
joint_axis (array): Joint axis in child frame, shape [joint_axis_count, 3], float
joint_armature (array): Armature for each joint axis (only used by :class:`FeatherstoneIntegrator`), shape [joint_count], float
joint_target_ke (array): Joint stiffness, shape [joint_axis_count], float
joint_target_kd (array): Joint damping, shape [joint_axis_count], float
joint_axis_start (array): Start index of the first axis per joint, shape [joint_count], int
joint_axis_dim (array): Number of linear and angular axes per joint, shape [joint_count, 2], int
joint_axis_mode (array): Joint axis mode, shape [joint_axis_count], int. See `Joint modes`_.
joint_linear_compliance (array): Joint linear compliance, shape [joint_count], float
joint_angular_compliance (array): Joint linear compliance, shape [joint_count], float
joint_enabled (array): Controls which joint is simulated (bodies become disconnected if False), shape [joint_count], int
Note:
This setting is not supported by :class:`FeatherstoneIntegrator`.
joint_limit_lower (array): Joint lower position limits, shape [joint_count], float
joint_limit_upper (array): Joint upper position limits, shape [joint_count], float
joint_limit_ke (array): Joint position limit stiffness (used by the Euler integrators), shape [joint_count], float
joint_limit_kd (array): Joint position limit damping (used by the Euler integrators), shape [joint_count], float
joint_twist_lower (array): Joint lower twist limit, shape [joint_count], float
joint_twist_upper (array): Joint upper twist limit, shape [joint_count], float
joint_q_start (array): Start index of the first position coordinate per joint, shape [joint_count], int
joint_qd_start (array): Start index of the first velocity coordinate per joint, shape [joint_count], int
articulation_start (array): Articulation start index, shape [articulation_count], int
joint_name (list): Joint names, shape [joint_count], str
joint_attach_ke (float): Joint attachment force stiffness (used by :class:`SemiImplicitIntegrator`)
joint_attach_kd (float): Joint attachment force damping (used by :class:`SemiImplicitIntegrator`)
soft_contact_margin (float): Contact margin for generation of soft contacts
soft_contact_ke (float): Stiffness of soft contacts (used by the Euler integrators)
soft_contact_kd (float): Damping of soft contacts (used by the Euler integrators)
soft_contact_kf (float): Stiffness of friction force in soft contacts (used by the Euler integrators)
soft_contact_mu (float): Friction coefficient of soft contacts
soft_contact_restitution (float): Restitution coefficient of soft contacts (used by :class:`XPBDIntegrator`)
soft_contact_count (array): Number of active particle-shape contacts, shape [1], int
soft_contact_particle (array), Index of particle per soft contact point, shape [soft_contact_max], int
soft_contact_shape (array), Index of shape per soft contact point, shape [soft_contact_max], int
soft_contact_body_pos (array), Positional offset of soft contact point in body frame, shape [soft_contact_max], vec3
soft_contact_body_vel (array), Linear velocity of soft contact point in body frame, shape [soft_contact_max], vec3
soft_contact_normal (array), Contact surface normal of soft contact point in world space, shape [soft_contact_max], vec3
rigid_contact_max (int): Maximum number of potential rigid body contact points to generate ignoring the `rigid_mesh_contact_max` limit.
rigid_contact_max_limited (int): Maximum number of potential rigid body contact points to generate respecting the `rigid_mesh_contact_max` limit.
rigid_mesh_contact_max (int): Maximum number of rigid body contact points to generate per mesh (0 = unlimited, default)
rigid_contact_margin (float): Contact margin for generation of rigid body contacts
rigid_contact_torsional_friction (float): Torsional friction coefficient for rigid body contacts (used by :class:`XPBDIntegrator`)
rigid_contact_rolling_friction (float): Rolling friction coefficient for rigid body contacts (used by :class:`XPBDIntegrator`)
rigid_contact_count (array): Number of active shape-shape contacts, shape [1], int
rigid_contact_point0 (array): Contact point relative to frame of body 0, shape [rigid_contact_max], vec3
rigid_contact_point1 (array): Contact point relative to frame of body 1, shape [rigid_contact_max], vec3
rigid_contact_offset0 (array): Contact offset due to contact thickness relative to body 0, shape [rigid_contact_max], vec3
rigid_contact_offset1 (array): Contact offset due to contact thickness relative to body 1, shape [rigid_contact_max], vec3
rigid_contact_normal (array): Contact normal in world space, shape [rigid_contact_max], vec3
rigid_contact_thickness (array): Total contact thickness, shape [rigid_contact_max], float
rigid_contact_shape0 (array): Index of shape 0 per contact, shape [rigid_contact_max], int
rigid_contact_shape1 (array): Index of shape 1 per contact, shape [rigid_contact_max], int
ground (bool): Whether the ground plane and ground contacts are enabled
ground_plane (array): Ground plane 3D normal and offset, shape [4], float
up_vector (np.ndarray): Up vector of the world, shape [3], float
up_axis (int): Up axis, 0 for x, 1 for y, 2 for z
gravity (np.ndarray): Gravity vector, shape [3], float
particle_count (int): Total number of particles in the system
body_count (int): Total number of bodies in the system
shape_count (int): Total number of shapes in the system
joint_count (int): Total number of joints in the system
tri_count (int): Total number of triangles in the system
tet_count (int): Total number of tetrahedra in the system
edge_count (int): Total number of edges in the system
spring_count (int): Total number of springs in the system
contact_count (int): Total number of contacts in the system
muscle_count (int): Total number of muscles in the system
articulation_count (int): Total number of articulations in the system
joint_dof_count (int): Total number of velocity degrees of freedom of all joints in the system
joint_coord_count (int): Total number of position degrees of freedom of all joints in the system
device (wp.Device): Device on which the Model was allocated
Note:
It is strongly recommended to use the ModelBuilder to construct a simulation rather
than creating your own Model object directly, however it is possible to do so if
desired.
"""
def __init__(self, device=None):
self.requires_grad = False
self.num_envs = 0
self.particle_q = None
self.particle_qd = None
self.particle_mass = None
self.particle_inv_mass = None
self.particle_radius = None
self.particle_max_radius = 0.0
self.particle_ke = 1.0e3
self.particle_kd = 1.0e2
self.particle_kf = 1.0e2
self.particle_mu = 0.5
self.particle_cohesion = 0.0
self.particle_adhesion = 0.0
self.particle_grid = None
self.particle_flags = None
self.particle_max_velocity = 1e5
self.shape_transform = None
self.shape_body = None
self.shape_visible = None
self.body_shapes = {}
self.shape_materials = ModelShapeMaterials()
self.shape_geo = ModelShapeGeometry()
self.shape_geo_src = None
self.shape_collision_group = None
self.shape_collision_group_map = None
self.shape_collision_filter_pairs = None
self.shape_collision_radius = None
self.shape_ground_collision = None
self.shape_shape_collision = None
self.shape_contact_pairs = None
self.shape_ground_contact_pairs = None
self.spring_indices = None
self.spring_rest_length = None
self.spring_stiffness = None
self.spring_damping = None
self.spring_control = None
self.spring_constraint_lambdas = None
self.tri_indices = None
self.tri_poses = None
self.tri_activations = None
self.tri_materials = None
self.edge_indices = None
self.edge_rest_angle = None
self.edge_bending_properties = None
self.edge_constraint_lambdas = None
self.tet_indices = None
self.tet_poses = None
self.tet_activations = None
self.tet_materials = None
self.muscle_start = None
self.muscle_params = None
self.muscle_bodies = None
self.muscle_points = None
self.muscle_activations = None
self.body_q = None
self.body_qd = None
self.body_com = None
self.body_inertia = None
self.body_inv_inertia = None
self.body_mass = None
self.body_inv_mass = None
self.body_name = None
self.joint_q = None
self.joint_qd = None
self.joint_act = None
self.joint_type = None
self.joint_parent = None
self.joint_child = None
self.joint_X_p = None
self.joint_X_c = None
self.joint_axis = None
self.joint_armature = None
self.joint_target_ke = None
self.joint_target_kd = None
self.joint_axis_start = None
self.joint_axis_dim = None
self.joint_axis_mode = None
self.joint_linear_compliance = None
self.joint_angular_compliance = None
self.joint_enabled = None
self.joint_limit_lower = None
self.joint_limit_upper = None
self.joint_limit_ke = None
self.joint_limit_kd = None
self.joint_twist_lower = None
self.joint_twist_upper = None
self.joint_q_start = None
self.joint_qd_start = None
self.articulation_start = None
self.joint_name = None
# todo: per-joint values?
self.joint_attach_ke = 1.0e3
self.joint_attach_kd = 1.0e2
self.soft_contact_margin = 0.2
self.soft_contact_ke = 1.0e3
self.soft_contact_kd = 10.0
self.soft_contact_kf = 1.0e3
self.soft_contact_mu = 0.5
self.soft_contact_restitution = 0.0
self.soft_contact_count = 0
self.soft_contact_particle = None
self.soft_contact_shape = None
self.soft_contact_body_pos = None
self.soft_contact_body_vel = None
self.soft_contact_normal = None
self.rigid_contact_max = 0
self.rigid_contact_max_limited = 0
self.rigid_mesh_contact_max = 0
self.rigid_contact_margin = None
self.rigid_contact_torsional_friction = None
self.rigid_contact_rolling_friction = None
self.rigid_contact_count = None
self.rigid_contact_point0 = None
self.rigid_contact_point1 = None
self.rigid_contact_offset0 = None
self.rigid_contact_offset1 = None
self.rigid_contact_normal = None
self.rigid_contact_thickness = None
self.rigid_contact_shape0 = None
self.rigid_contact_shape1 = None
# toggles ground contact for all shapes
self.ground = True
self.ground_plane = None
self.up_vector = np.array((0.0, 1.0, 0.0))
self.up_axis = 1
self.gravity = np.array((0.0, -9.80665, 0.0))
self.particle_count = 0
self.body_count = 0
self.shape_count = 0
self.joint_count = 0
self.joint_axis_count = 0
self.tri_count = 0
self.tet_count = 0
self.edge_count = 0
self.spring_count = 0
self.muscle_count = 0
self.articulation_count = 0
self.joint_dof_count = 0
self.joint_coord_count = 0
self.device = wp.get_device(device)
def state(self, requires_grad=None) -> State:
"""Returns a state object for the model
The returned state will be initialized with the initial configuration given in
the model description.
Args:
requires_grad (bool): Manual overwrite whether the state variables should have `requires_grad` enabled (defaults to `None` to use the model's setting :attr:`requires_grad`)
Returns:
State: The state object
"""
s = State()
if requires_grad is None:
requires_grad = self.requires_grad
# particles
if self.particle_count:
s.particle_q = wp.clone(self.particle_q, requires_grad=requires_grad)
s.particle_qd = wp.clone(self.particle_qd, requires_grad=requires_grad)
s.particle_f = wp.zeros_like(self.particle_qd, requires_grad=requires_grad)
# articulations
if self.body_count:
s.body_q = wp.clone(self.body_q, requires_grad=requires_grad)
s.body_qd = wp.clone(self.body_qd, requires_grad=requires_grad)
s.body_f = wp.zeros_like(self.body_qd, requires_grad=requires_grad)
if self.joint_count:
s.joint_q = wp.clone(self.joint_q, requires_grad=requires_grad)
s.joint_qd = wp.clone(self.joint_qd, requires_grad=requires_grad)
return s
def control(self, requires_grad=None, clone_variables=True) -> Control:
"""
Returns a control object for the model.
The returned control object will be initialized with the control inputs given in the model description.
Args:
requires_grad (bool): Manual overwrite whether the control variables should have `requires_grad` enabled (defaults to `None` to use the model's setting :attr:`requires_grad`)
clone_variables (bool): Whether to clone the control inputs or use the original data
Returns:
Control: The control object
"""
c = Control(self)
if requires_grad is None:
requires_grad = self.requires_grad
if clone_variables:
if self.joint_count:
c.joint_act = wp.clone(self.joint_act, requires_grad=requires_grad)
if self.tri_count:
c.tri_activations = wp.clone(self.tri_activations, requires_grad=requires_grad)
if self.tet_count:
c.tet_activations = wp.clone(self.tet_activations, requires_grad=requires_grad)
if self.muscle_count:
c.muscle_activations = wp.clone(self.muscle_activations, requires_grad=requires_grad)
else:
c.joint_act = self.joint_act
c.tri_activations = self.tri_activations
c.tet_activations = self.tet_activations
c.muscle_activations = self.muscle_activations
return c
def _allocate_soft_contacts(self, target, count, requires_grad=False):
with wp.ScopedDevice(self.device):
target.soft_contact_count = wp.zeros(1, dtype=wp.int32)
target.soft_contact_particle = wp.zeros(count, dtype=int)
target.soft_contact_shape = wp.zeros(count, dtype=int)
target.soft_contact_body_pos = wp.zeros(count, dtype=wp.vec3, requires_grad=requires_grad)
target.soft_contact_body_vel = wp.zeros(count, dtype=wp.vec3, requires_grad=requires_grad)
target.soft_contact_normal = wp.zeros(count, dtype=wp.vec3, requires_grad=requires_grad)
target.soft_contact_tids = wp.zeros(count, dtype=int)
def allocate_soft_contacts(self, count, requires_grad=False):
self._allocate_soft_contacts(self, count, requires_grad)
def find_shape_contact_pairs(self):
# find potential contact pairs based on collision groups and collision mask (pairwise filtering)
import copy
import itertools
filters = copy.copy(self.shape_collision_filter_pairs)
for a, b in self.shape_collision_filter_pairs:
filters.add((b, a))
contact_pairs = []
# iterate over collision groups (islands)
for group, shapes in self.shape_collision_group_map.items():
for shape_a, shape_b in itertools.product(shapes, shapes):
if not self.shape_shape_collision[shape_a]:
continue
if not self.shape_shape_collision[shape_b]:
continue
if shape_a < shape_b and (shape_a, shape_b) not in filters:
contact_pairs.append((shape_a, shape_b))
if group != -1 and -1 in self.shape_collision_group_map:
# shapes with collision group -1 collide with all other shapes
for shape_a, shape_b in itertools.product(shapes, self.shape_collision_group_map[-1]):
if shape_a < shape_b and (shape_a, shape_b) not in filters:
contact_pairs.append((shape_a, shape_b))
self.shape_contact_pairs = wp.array(np.array(contact_pairs), dtype=wp.int32, device=self.device)
self.shape_contact_pair_count = len(contact_pairs)
# find ground contact pairs
ground_contact_pairs = []
ground_id = self.shape_count - 1
for i in range(ground_id):
if self.shape_ground_collision[i]:
ground_contact_pairs.append((i, ground_id))
self.shape_ground_contact_pairs = wp.array(np.array(ground_contact_pairs), dtype=wp.int32, device=self.device)
self.shape_ground_contact_pair_count = len(ground_contact_pairs)
def count_contact_points(self):
"""
Counts the maximum number of rigid contact points that need to be allocated.
This function returns two values corresponding to the maximum number of potential contacts
excluding the limiting from `Model.rigid_mesh_contact_max` and the maximum number of
contact points that may be generated when considering the `Model.rigid_mesh_contact_max` limit.
:returns:
- potential_count (int): Potential number of contact points
- actual_count (int): Actual number of contact points
"""
from .collide import count_contact_points
# calculate the potential number of shape pair contact points
contact_count = wp.zeros(2, dtype=wp.int32, device=self.device)
wp.launch(
kernel=count_contact_points,
dim=self.shape_contact_pair_count,
inputs=[
self.shape_contact_pairs,
self.shape_geo,
self.rigid_mesh_contact_max,
],
outputs=[contact_count],
device=self.device,
record_tape=False,
)
# count ground contacts
wp.launch(
kernel=count_contact_points,
dim=self.shape_ground_contact_pair_count,
inputs=[
self.shape_ground_contact_pairs,
self.shape_geo,
self.rigid_mesh_contact_max,
],
outputs=[contact_count],
device=self.device,
record_tape=False,
)
counts = contact_count.numpy()
potential_count = int(counts[0])
actual_count = int(counts[1])
return potential_count, actual_count
def allocate_rigid_contacts(self, target=None, count=None, limited_contact_count=None, requires_grad=False):
if count is not None:
# potential number of contact points to consider
self.rigid_contact_max = count
if limited_contact_count is not None:
self.rigid_contact_max_limited = limited_contact_count
if target is None:
target = self
with wp.ScopedDevice(self.device):
# serves as counter of the number of active contact points
target.rigid_contact_count = wp.zeros(1, dtype=wp.int32)
# contact point ID within the (shape_a, shape_b) contact pair
target.rigid_contact_point_id = wp.zeros(self.rigid_contact_max, dtype=wp.int32)
# position of contact point in body 0's frame before the integration step
target.rigid_contact_point0 = wp.zeros(
self.rigid_contact_max_limited, dtype=wp.vec3, requires_grad=requires_grad
)
# position of contact point in body 1's frame before the integration step
target.rigid_contact_point1 = wp.zeros(
self.rigid_contact_max_limited, dtype=wp.vec3, requires_grad=requires_grad
)
# moment arm before the integration step resulting from thickness displacement added to contact point 0 in body 0's frame (used in XPBD contact friction handling)
target.rigid_contact_offset0 = wp.zeros(
self.rigid_contact_max_limited, dtype=wp.vec3, requires_grad=requires_grad
)
# moment arm before the integration step resulting from thickness displacement added to contact point 1 in body 1's frame (used in XPBD contact friction handling)
target.rigid_contact_offset1 = wp.zeros(
self.rigid_contact_max_limited, dtype=wp.vec3, requires_grad=requires_grad
)
# contact normal in world frame
target.rigid_contact_normal = wp.zeros(
self.rigid_contact_max_limited, dtype=wp.vec3, requires_grad=requires_grad
)
# combined thickness of both shapes
target.rigid_contact_thickness = wp.zeros(
self.rigid_contact_max_limited, dtype=wp.float32, requires_grad=requires_grad
)
# ID of the first shape in the contact pair
target.rigid_contact_shape0 = wp.zeros(self.rigid_contact_max_limited, dtype=wp.int32)
# ID of the second shape in the contact pair
target.rigid_contact_shape1 = wp.zeros(self.rigid_contact_max_limited, dtype=wp.int32)
# shape IDs of potential contact pairs found during broadphase
target.rigid_contact_broad_shape0 = wp.zeros(self.rigid_contact_max, dtype=wp.int32)
target.rigid_contact_broad_shape1 = wp.zeros(self.rigid_contact_max, dtype=wp.int32)
max_pair_count = self.shape_count * self.shape_count
# maximum number of contact points per contact pair
target.rigid_contact_point_limit = wp.zeros(max_pair_count, dtype=wp.int32)
# currently found contacts per contact pair
target.rigid_contact_pairwise_counter = wp.zeros(max_pair_count, dtype=wp.int32)
# ID of thread that found the current contact point
target.rigid_contact_tids = wp.zeros(self.rigid_contact_max, dtype=wp.int32)
@property
def soft_contact_max(self):
"""Maximum number of soft contacts that can be registered"""
return len(self.soft_contact_particle)
class ModelBuilder:
"""A helper class for building simulation models at runtime.
Use the ModelBuilder to construct a simulation scene. The ModelBuilder
and builds the scene representation using standard Python data structures (lists),
this means it is not differentiable. Once :func:`finalize()`
has been called the ModelBuilder transfers all data to Warp tensors and returns
an object that may be used for simulation.
Example
-------
.. code-block:: python
import warp as wp
import warp.sim
builder = wp.sim.ModelBuilder()
# anchor point (zero mass)
builder.add_particle((0, 1.0, 0.0), (0.0, 0.0, 0.0), 0.0)
# build chain
for i in range(1, 10):
builder.add_particle((i, 1.0, 0.0), (0.0, 0.0, 0.0), 1.0)
builder.add_spring(i - 1, i, 1.0e3, 0.0, 0)
# create model
model = builder.finalize("cuda")
state = model.state()
control = model.control() # optional, to support time-varying control inputs
integrator = wp.sim.SemiImplicitIntegrator()
for i in range(100):
state.clear_forces()
integrator.simulate(model, state, state, dt=1.0 / 60.0, control=control)
Note:
It is strongly recommended to use the ModelBuilder to construct a simulation rather
than creating your own Model object directly, however it is possible to do so if
desired.
"""
# Default particle settings
default_particle_radius = 0.1
# Default triangle soft mesh settings
default_tri_ke = 100.0
default_tri_ka = 100.0
default_tri_kd = 10.0
default_tri_drag = 0.0
default_tri_lift = 0.0
# Default distance constraint properties
default_spring_ke = 100.0
default_spring_kd = 0.0
# Default edge bending properties
default_edge_ke = 100.0
default_edge_kd = 0.0
# Default rigid shape contact material properties
default_shape_ke = 1.0e5
default_shape_kd = 1000.0
default_shape_kf = 1000.0
default_shape_ka = 0.0
default_shape_mu = 0.5
default_shape_restitution = 0.0
default_shape_density = 1000.0
default_shape_thickness = 1e-5
# Default joint settings
default_joint_limit_ke = 100.0
default_joint_limit_kd = 1.0
def __init__(self, up_vector=(0.0, 1.0, 0.0), gravity=-9.80665):
self.num_envs = 0
# particles
self.particle_q = []
self.particle_qd = []
self.particle_mass = []
self.particle_radius = []
self.particle_flags = []
self.particle_max_velocity = 1e5
# shapes (each shape has an entry in these arrays)
# transform from shape to body
self.shape_transform = []
# maps from shape index to body index
self.shape_body = []
self.shape_visible = []
self.shape_geo_type = []
self.shape_geo_scale = []
self.shape_geo_src = []
self.shape_geo_is_solid = []
self.shape_geo_thickness = []
self.shape_material_ke = []
self.shape_material_kd = []
self.shape_material_kf = []
self.shape_material_ka = []
self.shape_material_mu = []
self.shape_material_restitution = []
# collision groups within collisions are handled
self.shape_collision_group = []
self.shape_collision_group_map = {}
self.last_collision_group = 0
# radius to use for broadphase collision checking
self.shape_collision_radius = []
# whether the shape collides with the ground
self.shape_ground_collision = []
# whether the shape collides with any other shape
self.shape_shape_collision = []
# filtering to ignore certain collision pairs
self.shape_collision_filter_pairs = set()
# geometry
self.geo_meshes = []
self.geo_sdfs = []
# springs
self.spring_indices = []
self.spring_rest_length = []
self.spring_stiffness = []
self.spring_damping = []
self.spring_control = []
# triangles
self.tri_indices = []
self.tri_poses = []
self.tri_activations = []
self.tri_materials = []
# edges (bending)
self.edge_indices = []
self.edge_rest_angle = []
self.edge_bending_properties = []
# tetrahedra
self.tet_indices = []
self.tet_poses = []
self.tet_activations = []
self.tet_materials = []
# muscles
self.muscle_start = []
self.muscle_params = []
self.muscle_activations = []
self.muscle_bodies = []
self.muscle_points = []
# rigid bodies
self.body_mass = []
self.body_inertia = []
self.body_inv_mass = []
self.body_inv_inertia = []
self.body_com = []
self.body_q = []
self.body_qd = []
self.body_name = []
self.body_shapes = {} # mapping from body to shapes
# rigid joints
self.joint = {}
self.joint_parent = [] # index of the parent body (constant)
self.joint_parents = {} # mapping from joint to parent bodies
self.joint_child = [] # index of the child body (constant)
self.joint_axis = [] # joint axis in child joint frame (constant)
self.joint_X_p = [] # frame of joint in parent (constant)
self.joint_X_c = [] # frame of child com (in child coordinates) (constant)
self.joint_q = []
self.joint_qd = []
self.joint_type = []
self.joint_name = []
self.joint_armature = []
self.joint_target_ke = []
self.joint_target_kd = []
self.joint_axis_mode = []
self.joint_limit_lower = []
self.joint_limit_upper = []
self.joint_limit_ke = []
self.joint_limit_kd = []
self.joint_act = []
self.joint_twist_lower = []
self.joint_twist_upper = []
self.joint_linear_compliance = []
self.joint_angular_compliance = []
self.joint_enabled = []
self.joint_q_start = []
self.joint_qd_start = []
self.joint_axis_start = []
self.joint_axis_dim = []
self.articulation_start = []
self.joint_dof_count = 0
self.joint_coord_count = 0
self.joint_axis_total_count = 0
self.up_vector = wp.vec3(up_vector)
self.up_axis = wp.vec3(np.argmax(np.abs(up_vector)))
self.gravity = gravity
# indicates whether a ground plane has been created
self._ground_created = False
# constructor parameters for ground plane shape
self._ground_params = {
"plane": (*up_vector, 0.0),
"width": 0.0,
"length": 0.0,
"ke": self.default_shape_ke,
"kd": self.default_shape_kd,
"kf": self.default_shape_kf,
"mu": self.default_shape_mu,
"restitution": self.default_shape_restitution,
}
# Maximum number of soft contacts that can be registered
self.soft_contact_max = 64 * 1024
# maximum number of contact points to generate per mesh shape
self.rigid_mesh_contact_max = 0 # 0 = unlimited
# contacts to be generated within the given distance margin to be generated at
# every simulation substep (can be 0 if only one PBD solver iteration is used)
self.rigid_contact_margin = 0.1
# torsional friction coefficient (only considered by XPBD so far)
self.rigid_contact_torsional_friction = 0.5
# rolling friction coefficient (only considered by XPBD so far)
self.rigid_contact_rolling_friction = 0.001
# number of rigid contact points to allocate in the model during self.finalize() per environment
# if setting is None, the number of worst-case number of contacts will be calculated in self.finalize()
self.num_rigid_contacts_per_env = None
@property
def shape_count(self):
return len(self.shape_geo_type)
@property
def body_count(self):
return len(self.body_q)
@property
def joint_count(self):
return len(self.joint_type)
@property
def joint_axis_count(self):
return len(self.joint_axis)
@property
def particle_count(self):
return len(self.particle_q)
@property
def tri_count(self):
return len(self.tri_poses)
@property
def tet_count(self):
return len(self.tet_poses)
@property
def edge_count(self):
return len(self.edge_rest_angle)
@property
def spring_count(self):
return len(self.spring_rest_length)
@property
def muscle_count(self):
return len(self.muscle_start)
@property
def articulation_count(self):
return len(self.articulation_start)
# an articulation is a set of contiguous bodies bodies from articulation_start[i] to articulation_start[i+1]
# these are used for computing forward kinematics e.g.:
#
# model.eval_articulation_fk()
# model.eval_articulation_j()
# model.eval_articulation_m()
#
# articulations are automatically 'closed' when calling finalize
def add_articulation(self):
self.articulation_start.append(self.joint_count)
def add_builder(self, builder, xform=None, update_num_env_count=True, separate_collision_group=True):
"""Copies the data from `builder`, another `ModelBuilder` to this `ModelBuilder`.
Args:
builder (ModelBuilder): a model builder to add model data from.
xform (:ref:`transform <transform>`): offset transform applied to root bodies.
update_num_env_count (bool): if True, the number of environments is incremented by 1.
separate_collision_group (bool): if True, the shapes from the articulations in `builder` will all be put into a single new collision group, otherwise, only the shapes in collision group > -1 will be moved to a new group.
"""
start_particle_idx = self.particle_count
if builder.particle_count:
self.particle_max_velocity = builder.particle_max_velocity
if xform is not None:
pos_offset = wp.transform_get_translation(xform)
else:
pos_offset = np.zeros(3)
self.particle_q.extend((np.array(builder.particle_q) + pos_offset).tolist())
# other particle attributes are added below
if builder.spring_count:
self.spring_indices.extend((np.array(builder.spring_indices, dtype=np.int32) + start_particle_idx).tolist())
if builder.edge_count:
self.edge_indices.extend((np.array(builder.edge_indices, dtype=np.int32) + start_particle_idx).tolist())
if builder.tri_count:
self.tri_indices.extend((np.array(builder.tri_indices, dtype=np.int32) + start_particle_idx).tolist())
if builder.tet_count:
self.tet_indices.extend((np.array(builder.tet_indices, dtype=np.int32) + start_particle_idx).tolist())
start_body_idx = self.body_count
start_shape_idx = self.shape_count
for s, b in enumerate(builder.shape_body):
if b > -1:
new_b = b + start_body_idx
self.shape_body.append(new_b)
self.shape_transform.append(builder.shape_transform[s])
else:
self.shape_body.append(-1)
# apply offset transform to root bodies
if xform is not None:
self.shape_transform.append(xform * builder.shape_transform[s])
for b, shapes in builder.body_shapes.items():
self.body_shapes[b + start_body_idx] = [s + start_shape_idx for s in shapes]
if builder.joint_count:
joint_X_p = copy.deepcopy(builder.joint_X_p)
joint_q = copy.deepcopy(builder.joint_q)
if xform is not None:
for i in range(len(joint_X_p)):
if builder.joint_type[i] == wp.sim.JOINT_FREE:
qi = builder.joint_q_start[i]
xform_prev = wp.transform(joint_q[qi : qi + 3], joint_q[qi + 3 : qi + 7])
tf = xform * xform_prev
joint_q[qi : qi + 3] = tf.p
joint_q[qi + 3 : qi + 7] = tf.q
elif builder.joint_parent[i] == -1:
joint_X_p[i] = xform * joint_X_p[i]
self.joint_X_p.extend(joint_X_p)
self.joint_q.extend(joint_q)
self.add_articulation()
# offset the indices
self.joint_parent.extend([p + self.joint_count if p != -1 else -1 for p in builder.joint_parent])
self.joint_child.extend([c + self.joint_count for c in builder.joint_child])
self.joint_q_start.extend([c + self.joint_coord_count for c in builder.joint_q_start])
self.joint_qd_start.extend([c + self.joint_dof_count for c in builder.joint_qd_start])
self.joint_axis_start.extend([a + self.joint_axis_total_count for a in builder.joint_axis_start])
joint_children = set(builder.joint_child)
for i in range(builder.body_count):
if xform is not None and i not in joint_children:
# rigid body is not attached to a joint, so apply input transform directly
self.body_q.append(xform * builder.body_q[i])
else:
self.body_q.append(builder.body_q[i])
# apply collision group
if separate_collision_group:
self.shape_collision_group.extend([self.last_collision_group + 1 for _ in builder.shape_collision_group])
else:
self.shape_collision_group.extend(
[(g + self.last_collision_group if g > -1 else -1) for g in builder.shape_collision_group]
)
shape_count = self.shape_count
for i, j in builder.shape_collision_filter_pairs:
self.shape_collision_filter_pairs.add((i + shape_count, j + shape_count))
for group, shapes in builder.shape_collision_group_map.items():
if separate_collision_group:
group = self.last_collision_group + 1
else:
group = group + self.last_collision_group if group > -1 else -1
if group not in self.shape_collision_group_map:
self.shape_collision_group_map[group] = []
self.shape_collision_group_map[group].extend([s + shape_count for s in shapes])
# update last collision group counter
if separate_collision_group:
self.last_collision_group += 1
elif builder.last_collision_group > -1:
self.last_collision_group += builder.last_collision_group
more_builder_attrs = [
"body_inertia",
"body_mass",
"body_inv_inertia",
"body_inv_mass",
"body_com",
"body_qd",
"body_name",
"joint_type",
"joint_enabled",
"joint_X_c",
"joint_armature",
"joint_axis",
"joint_axis_dim",
"joint_axis_mode",
"joint_name",
"joint_qd",
"joint_act",
"joint_limit_lower",
"joint_limit_upper",
"joint_limit_ke",
"joint_limit_kd",
"joint_target_ke",
"joint_target_kd",
"joint_linear_compliance",
"joint_angular_compliance",
"shape_visible",
"shape_geo_type",
"shape_geo_scale",
"shape_geo_src",
"shape_geo_is_solid",
"shape_geo_thickness",
"shape_material_ke",
"shape_material_kd",
"shape_material_kf",
"shape_material_ka",
"shape_material_mu",
"shape_material_restitution",
"shape_collision_radius",
"shape_ground_collision",
"shape_shape_collision",
"particle_qd",
"particle_mass",
"particle_radius",
"particle_flags",
"edge_rest_angle",
"edge_bending_properties",
"spring_rest_length",
"spring_stiffness",
"spring_damping",
"spring_control",
"tri_poses",
"tri_activations",
"tri_materials",
"tet_poses",
"tet_activations",
"tet_materials",
]
for attr in more_builder_attrs:
getattr(self, attr).extend(getattr(builder, attr))
self.joint_dof_count += builder.joint_dof_count
self.joint_coord_count += builder.joint_coord_count
self.joint_axis_total_count += builder.joint_axis_total_count
self.up_vector = builder.up_vector
self.gravity = builder.gravity
self._ground_params = builder._ground_params
if update_num_env_count:
self.num_envs += 1
# register a rigid body and return its index.
def add_body(
self,
origin: Optional[Transform] = None,
armature: float = 0.0,
com: Optional[Vec3] = None,
I_m: Optional[Mat33] = None,
m: float = 0.0,
name: str = None,
) -> int:
"""Adds a rigid body to the model.
Args:
origin: The location of the body in the world frame
armature: Artificial inertia added to the body
com: The center of mass of the body w.r.t its origin
I_m: The 3x3 inertia tensor of the body (specified relative to the center of mass)
m: Mass of the body
name: Name of the body (optional)
Returns:
The index of the body in the model
Note:
If the mass (m) is zero then the body is treated as kinematic with no dynamics
"""
if origin is None:
origin = wp.transform()
if com is None:
com = wp.vec3()
if I_m is None:
I_m = wp.mat33()
body_id = len(self.body_mass)
# body data
inertia = I_m + wp.mat33(np.eye(3)) * armature
self.body_inertia.append(inertia)
self.body_mass.append(m)
self.body_com.append(com)
if m > 0.0:
self.body_inv_mass.append(1.0 / m)
else:
self.body_inv_mass.append(0.0)
if any(x for x in inertia):
self.body_inv_inertia.append(wp.inverse(inertia))
else:
self.body_inv_inertia.append(inertia)
self.body_q.append(origin)
self.body_qd.append(wp.spatial_vector())
self.body_name.append(name or f"body {body_id}")
self.body_shapes[body_id] = []
return body_id
def add_joint(
self,
joint_type: wp.constant,
parent: int,
child: int,
linear_axes: Optional[List[JointAxis]] = None,
angular_axes: Optional[List[JointAxis]] = None,
name: str = None,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""
Generic method to add any type of joint to this ModelBuilder.
Args:
joint_type (constant): The type of joint to add (see `Joint types`_)
parent (int): The index of the parent body (-1 is the world)
child (int): The index of the child body
linear_axes (list(:class:`JointAxis`)): The linear axes (see :class:`JointAxis`) of the joint
angular_axes (list(:class:`JointAxis`)): The angular axes (see :class:`JointAxis`) of the joint
name (str): The name of the joint (optional)
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
linear_compliance (float): The linear compliance of the joint
angular_compliance (float): The angular compliance of the joint
armature (float): Artificial inertia added around the joint axes (only considered by :class:`FeatherstoneIntegrator`)
collision_filter_parent (bool): Whether to filter collisions between shapes of the parent and child bodies
enabled (bool): Whether the joint is enabled (not considered by :class:`FeatherstoneIntegrator`)
Returns:
The index of the added joint
"""
if linear_axes is None:
linear_axes = []
if angular_axes is None:
angular_axes = []
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
if len(self.articulation_start) == 0:
# automatically add an articulation if none exists
self.add_articulation()
self.joint_type.append(joint_type)
self.joint_parent.append(parent)
if child not in self.joint_parents:
self.joint_parents[child] = [parent]
else:
self.joint_parents[child].append(parent)
self.joint_child.append(child)
self.joint_X_p.append(wp.transform(parent_xform))
self.joint_X_c.append(wp.transform(child_xform))
self.joint_name.append(name or f"joint {self.joint_count}")
self.joint_axis_start.append(len(self.joint_axis))
self.joint_axis_dim.append((len(linear_axes), len(angular_axes)))
self.joint_axis_total_count += len(linear_axes) + len(angular_axes)
self.joint_linear_compliance.append(linear_compliance)
self.joint_angular_compliance.append(angular_compliance)
self.joint_enabled.append(enabled)
def add_axis_dim(dim: JointAxis):
self.joint_axis.append(dim.axis)
self.joint_axis_mode.append(dim.mode)
self.joint_act.append(dim.action)
self.joint_target_ke.append(dim.target_ke)
self.joint_target_kd.append(dim.target_kd)
self.joint_limit_ke.append(dim.limit_ke)
self.joint_limit_kd.append(dim.limit_kd)
if np.isfinite(dim.limit_lower):
self.joint_limit_lower.append(dim.limit_lower)
else:
self.joint_limit_lower.append(-1e6)
if np.isfinite(dim.limit_upper):
self.joint_limit_upper.append(dim.limit_upper)
else:
self.joint_limit_upper.append(1e6)
for dim in linear_axes:
add_axis_dim(dim)
for dim in angular_axes:
add_axis_dim(dim)
if joint_type == JOINT_PRISMATIC:
dof_count = 1
coord_count = 1
elif joint_type == JOINT_REVOLUTE:
dof_count = 1
coord_count = 1
elif joint_type == JOINT_BALL:
dof_count = 3
coord_count = 4
elif joint_type == JOINT_FREE or joint_type == JOINT_DISTANCE:
dof_count = 6
coord_count = 7
elif joint_type == JOINT_FIXED:
dof_count = 0
coord_count = 0
elif joint_type == JOINT_UNIVERSAL:
dof_count = 2
coord_count = 2
elif joint_type == JOINT_COMPOUND:
dof_count = 3
coord_count = 3
elif joint_type == JOINT_D6:
dof_count = len(linear_axes) + len(angular_axes)
coord_count = dof_count
for _i in range(coord_count):
self.joint_q.append(0.0)
for _i in range(dof_count):
self.joint_qd.append(0.0)
self.joint_armature.append(armature)
if joint_type == JOINT_FREE or joint_type == JOINT_DISTANCE or joint_type == JOINT_BALL:
# ensure that a valid quaternion is used for the angular dofs
self.joint_q[-1] = 1.0
self.joint_q_start.append(self.joint_coord_count)
self.joint_qd_start.append(self.joint_dof_count)
self.joint_dof_count += dof_count
self.joint_coord_count += coord_count
if collision_filter_parent and parent > -1:
for child_shape in self.body_shapes[child]:
for parent_shape in self.body_shapes[parent]:
self.shape_collision_filter_pairs.add((parent_shape, child_shape))
return self.joint_count - 1
def add_joint_revolute(
self,
parent: int,
child: int,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
axis: Vec3 = (1.0, 0.0, 0.0),
target: float = None,
target_ke: float = 0.0,
target_kd: float = 0.0,
mode: int = JOINT_MODE_FORCE,
limit_lower: float = -2 * math.pi,
limit_upper: float = 2 * math.pi,
limit_ke: float = default_joint_limit_ke,
limit_kd: float = default_joint_limit_kd,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a revolute (hinge) joint to the model. It has one degree of freedom.
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
axis (3D vector or JointAxis): The axis of rotation in the parent body's local frame, can be a JointAxis object whose settings will be used instead of the other arguments
target: The target angle (in radians) or target velocity of the joint (if None, the joint is considered to be in force control mode)
target_ke: The stiffness of the joint target
target_kd: The damping of the joint target
limit_lower: The lower limit of the joint
limit_upper: The upper limit of the joint
limit_ke: The stiffness of the joint limit
limit_kd: The damping of the joint limit
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature: Artificial inertia added around the joint axis
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
action = 0.0
if target is None and mode == JOINT_MODE_TARGET_POSITION:
action = 0.5 * (limit_lower + limit_upper)
elif target is not None:
action = target
if mode == JOINT_MODE_FORCE:
mode = JOINT_MODE_TARGET_POSITION
ax = JointAxis(
axis=axis,
limit_lower=limit_lower,
limit_upper=limit_upper,
action=action,
target_ke=target_ke,
target_kd=target_kd,
mode=mode,
limit_ke=limit_ke,
limit_kd=limit_kd,
)
return self.add_joint(
JOINT_REVOLUTE,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
angular_axes=[ax],
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_prismatic(
self,
parent: int,
child: int,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
axis: Vec3 = (1.0, 0.0, 0.0),
target: float = None,
target_ke: float = 0.0,
target_kd: float = 0.0,
mode: int = JOINT_MODE_FORCE,
limit_lower: float = -1e4,
limit_upper: float = 1e4,
limit_ke: float = default_joint_limit_ke,
limit_kd: float = default_joint_limit_kd,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a prismatic (sliding) joint to the model. It has one degree of freedom.
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
axis (3D vector or JointAxis): The axis of rotation in the parent body's local frame, can be a JointAxis object whose settings will be used instead of the other arguments
target: The target position or velocity of the joint (if None, the joint is considered to be in force control mode)
target_ke: The stiffness of the joint target
target_kd: The damping of the joint target
limit_lower: The lower limit of the joint
limit_upper: The upper limit of the joint
limit_ke: The stiffness of the joint limit
limit_kd: The damping of the joint limit
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature: Artificial inertia added around the joint axis
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
action = 0.0
if target is None and mode == JOINT_MODE_TARGET_POSITION:
action = 0.5 * (limit_lower + limit_upper)
elif target is not None:
action = target
if mode == JOINT_MODE_FORCE:
mode = JOINT_MODE_TARGET_POSITION
ax = JointAxis(
axis=axis,
limit_lower=limit_lower,
limit_upper=limit_upper,
action=action,
target_ke=target_ke,
target_kd=target_kd,
mode=mode,
limit_ke=limit_ke,
limit_kd=limit_kd,
)
return self.add_joint(
JOINT_PRISMATIC,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_axes=[ax],
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_ball(
self,
parent: int,
child: int,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a ball (spherical) joint to the model. Its position is defined by a 4D quaternion (xyzw) and its velocity is a 3D vector.
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature (float): Artificial inertia added around the joint axis (only considered by FeatherstoneIntegrator)
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
return self.add_joint(
JOINT_BALL,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_fixed(
self,
parent: int,
child: int,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a fixed (static) joint to the model. It has no degrees of freedom.
See :meth:`collapse_fixed_joints` for a helper function that removes these fixed joints and merges the connecting bodies to simplify the model and improve stability.
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature (float): Artificial inertia added around the joint axis (only considered by FeatherstoneIntegrator)
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
return self.add_joint(
JOINT_FIXED,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_free(
self,
child: int,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
armature: float = 0.0,
parent: int = -1,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a free joint to the model.
It has 7 positional degrees of freedom (first 3 linear and then 4 angular dimensions for the orientation quaternion in `xyzw` notation) and 6 velocity degrees of freedom (first 3 angular and then 3 linear velocity dimensions).
Args:
child: The index of the child body
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
armature (float): Artificial inertia added around the joint axis (only considered by FeatherstoneIntegrator)
parent: The index of the parent body (-1 by default to use the world frame, e.g. to make the child body and its children a floating-base mechanism)
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
return self.add_joint(
JOINT_FREE,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_distance(
self,
parent: int,
child: int,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
min_distance: float = -1.0,
max_distance: float = 1.0,
compliance: float = 0.0,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a distance joint to the model. The distance joint constraints the distance between the joint anchor points on the two bodies (see :ref:`FK-IK`) it connects to the interval [`min_distance`, `max_distance`].
It has 7 positional degrees of freedom (first 3 linear and then 4 angular dimensions for the orientation quaternion in `xyzw` notation) and 6 velocity degrees of freedom (first 3 angular and then 3 linear velocity dimensions).
Args:
parent: The index of the parent body
child: The index of the child body
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
min_distance: The minimum distance between the bodies (no limit if negative)
max_distance: The maximum distance between the bodies (no limit if negative)
compliance: The compliance of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
.. note:: Distance joints are currently only supported in the :class:`XPBDIntegrator` at the moment.
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
ax = JointAxis(
axis=(1.0, 0.0, 0.0),
limit_lower=min_distance,
limit_upper=max_distance,
)
return self.add_joint(
JOINT_DISTANCE,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_axes=[ax],
linear_compliance=compliance,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_universal(
self,
parent: int,
child: int,
axis_0: JointAxis,
axis_1: JointAxis,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a universal joint to the model. U-joints have two degrees of freedom, one for each axis.
Args:
parent: The index of the parent body
child: The index of the child body
axis_0 (3D vector or JointAxis): The first axis of the joint, can be a JointAxis object whose settings will be used instead of the other arguments
axis_1 (3D vector or JointAxis): The second axis of the joint, can be a JointAxis object whose settings will be used instead of the other arguments
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature: Artificial inertia added around the joint axes
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
return self.add_joint(
JOINT_UNIVERSAL,
parent,
child,
angular_axes=[JointAxis(axis_0), JointAxis(axis_1)],
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_compound(
self,
parent: int,
child: int,
axis_0: JointAxis,
axis_1: JointAxis,
axis_2: JointAxis,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
name: str = None,
collision_filter_parent: bool = True,
enabled: bool = True,
) -> int:
"""Adds a compound joint to the model, which has 3 degrees of freedom, one for each axis.
Similar to the ball joint (see :meth:`add_ball_joint`), the compound joint allows bodies to move in a 3D rotation relative to each other,
except that the rotation is defined by 3 axes instead of a quaternion.
Depending on the choice of axes, the orientation can be specified through Euler angles, e.g. `z-x-z` or `x-y-x`, or through a Tait-Bryan angle sequence, e.g. `z-y-x` or `x-y-z`.
Args:
parent: The index of the parent body
child: The index of the child body
axis_0 (3D vector or JointAxis): The first axis of the joint, can be a JointAxis object whose settings will be used instead of the other arguments
axis_1 (3D vector or JointAxis): The second axis of the joint, can be a JointAxis object whose settings will be used instead of the other arguments
axis_2 (3D vector or JointAxis): The third axis of the joint, can be a JointAxis object whose settings will be used instead of the other arguments
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature: Artificial inertia added around the joint axes
name: The name of the joint
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
return self.add_joint(
JOINT_COMPOUND,
parent,
child,
angular_axes=[JointAxis(axis_0), JointAxis(axis_1), JointAxis(axis_2)],
parent_xform=parent_xform,
child_xform=child_xform,
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def add_joint_d6(
self,
parent: int,
child: int,
linear_axes: Optional[List[JointAxis]] = None,
angular_axes: Optional[List[JointAxis]] = None,
name: str = None,
parent_xform: Optional[wp.transform] = None,
child_xform: Optional[wp.transform] = None,
linear_compliance: float = 0.0,
angular_compliance: float = 0.0,
armature: float = 1e-2,
collision_filter_parent: bool = True,
enabled: bool = True,
):
"""Adds a generic joint with custom linear and angular axes. The number of axes determines the number of degrees of freedom of the joint.
Args:
parent: The index of the parent body
child: The index of the child body
linear_axes: A list of linear axes
angular_axes: A list of angular axes
name: The name of the joint
parent_xform (:ref:`transform <transform>`): The transform of the joint in the parent body's local frame
child_xform (:ref:`transform <transform>`): The transform of the joint in the child body's local frame
linear_compliance: The linear compliance of the joint
angular_compliance: The angular compliance of the joint
armature: Artificial inertia added around the joint axes
collision_filter_parent: Whether to filter collisions between shapes of the parent and child bodies
enabled: Whether the joint is enabled
Returns:
The index of the added joint
"""
if linear_axes is None:
linear_axes = []
if angular_axes is None:
angular_axes = []
if parent_xform is None:
parent_xform = wp.transform()
if child_xform is None:
child_xform = wp.transform()
return self.add_joint(
JOINT_D6,
parent,
child,
parent_xform=parent_xform,
child_xform=child_xform,
linear_axes=[JointAxis(a) for a in linear_axes],
angular_axes=[JointAxis(a) for a in angular_axes],
linear_compliance=linear_compliance,
angular_compliance=angular_compliance,
armature=armature,
name=name,
collision_filter_parent=collision_filter_parent,
enabled=enabled,
)
def plot_articulation(self, plot_shapes=True):
"""Plots the model's articulation."""
def joint_type_str(type):
if type == JOINT_FREE:
return "free"
elif type == JOINT_BALL:
return "ball"
elif type == JOINT_PRISMATIC:
return "prismatic"
elif type == JOINT_REVOLUTE:
return "revolute"
elif type == JOINT_D6:
return "D6"
elif type == JOINT_UNIVERSAL:
return "universal"
elif type == JOINT_COMPOUND:
return "compound"
elif type == JOINT_FIXED:
return "fixed"
elif type == JOINT_DISTANCE:
return "distance"
return "unknown"
vertices = ["world"] + self.body_name
if plot_shapes:
vertices += [f"shape_{i}" for i in range(self.shape_count)]
edges = []
edge_labels = []
for i in range(self.joint_count):
edges.append((self.joint_child[i] + 1, self.joint_parent[i] + 1))
edge_labels.append(f"{self.joint_name[i]}\n({joint_type_str(self.joint_type[i])})")
if plot_shapes:
for i in range(self.shape_count):
edges.append((len(self.body_name) + i + 1, self.shape_body[i] + 1))
wp.plot_graph(vertices, edges, edge_labels=edge_labels)
def collapse_fixed_joints(self, verbose=wp.config.verbose):
"""Removes fixed joints from the model and merges the bodies they connect. This is useful for simplifying the model for faster and more stable simulation."""
body_data = {}
body_children = {-1: []}
visited = {}
for i in range(self.body_count):
name = self.body_name[i]
body_data[i] = {
"shapes": self.body_shapes[i],
"q": self.body_q[i],
"qd": self.body_qd[i],
"mass": self.body_mass[i],
"inertia": self.body_inertia[i],
"inv_mass": self.body_inv_mass[i],
"inv_inertia": self.body_inv_inertia[i],
"com": self.body_com[i],
"name": name,
"original_id": i,
}
visited[i] = False
body_children[i] = []
joint_data = {}
for i in range(self.joint_count):
name = self.joint_name[i]
parent = self.joint_parent[i]
child = self.joint_child[i]
body_children[parent].append(child)
q_start = self.joint_q_start[i]
qd_start = self.joint_qd_start[i]
if i < self.joint_count - 1:
q_dim = self.joint_q_start[i + 1] - q_start
qd_dim = self.joint_qd_start[i + 1] - qd_start
else:
q_dim = len(self.joint_q) - q_start
qd_dim = len(self.joint_qd) - qd_start
data = {
"type": self.joint_type[i],
"q": self.joint_q[q_start : q_start + q_dim],
"qd": self.joint_qd[qd_start : qd_start + qd_dim],
"act": self.joint_act[qd_start : qd_start + qd_dim],
"armature": self.joint_armature[qd_start : qd_start + qd_dim],
"q_start": q_start,
"qd_start": qd_start,
"linear_compliance": self.joint_linear_compliance[i],
"angular_compliance": self.joint_angular_compliance[i],
"name": name,
"parent_xform": wp.transform_expand(self.joint_X_p[i]),
"child_xform": wp.transform_expand(self.joint_X_c[i]),
"enabled": self.joint_enabled[i],
"axes": [],
"axis_dim": self.joint_axis_dim[i],
"parent": parent,
"child": child,
"original_id": i,
}
num_lin_axes, num_ang_axes = self.joint_axis_dim[i]
start_ax = self.joint_axis_start[i]
for j in range(start_ax, start_ax + num_lin_axes + num_ang_axes):
data["axes"].append(
{
"axis": self.joint_axis[j],
"axis_mode": self.joint_axis_mode[j],
"target_ke": self.joint_target_ke[j],
"target_kd": self.joint_target_kd[j],
"limit_ke": self.joint_limit_ke[j],
"limit_kd": self.joint_limit_kd[j],
"limit_lower": self.joint_limit_lower[j],
"limit_upper": self.joint_limit_upper[j],
}
)
joint_data[(parent, child)] = data
# sort body children so we traverse the tree in the same order as the bodies are listed
for children in body_children.values():
children.sort(key=lambda x: body_data[x]["original_id"])
retained_joints = []
retained_bodies = []
body_remap = {-1: -1}
# depth first search over the joint graph
def dfs(parent_body: int, child_body: int, incoming_xform: wp.transform, last_dynamic_body: int):
nonlocal visited
nonlocal retained_joints
nonlocal retained_bodies
nonlocal body_data
nonlocal body_remap
joint = joint_data[(parent_body, child_body)]
if joint["type"] == JOINT_FIXED:
joint_xform = joint["parent_xform"] * wp.transform_inverse(joint["child_xform"])
incoming_xform = incoming_xform * joint_xform
parent_name = self.body_name[parent_body] if parent_body > -1 else "world"
child_name = self.body_name[child_body]
last_dynamic_body_name = self.body_name[last_dynamic_body] if last_dynamic_body > -1 else "world"
if verbose:
print(
f'Remove fixed joint {joint["name"]} between {parent_name} and {child_name}, '
f"merging {child_name} into {last_dynamic_body_name}"
)
child_id = body_data[child_body]["original_id"]
for shape in self.body_shapes[child_id]:
self.shape_transform[shape] = incoming_xform * self.shape_transform[shape]
if verbose:
print(
f" Shape {shape} moved to body {last_dynamic_body_name} with transform {self.shape_transform[shape]}"
)
if last_dynamic_body > -1:
self.shape_body[shape] = body_data[last_dynamic_body]["id"]
# add inertia to last_dynamic_body
m = body_data[child_body]["mass"]
com = body_data[child_body]["com"]
inertia = body_data[child_body]["inertia"]
body_data[last_dynamic_body]["inertia"] += wp.sim.transform_inertia(
m, inertia, incoming_xform.p, incoming_xform.q
)
body_data[last_dynamic_body]["mass"] += m
source_m = body_data[last_dynamic_body]["mass"]
source_com = body_data[last_dynamic_body]["com"]
body_data[last_dynamic_body]["com"] = (m * com + source_m * source_com) / (m + source_m)
body_data[last_dynamic_body]["shapes"].append(shape)
# indicate to recompute inverse mass, inertia for this body
body_data[last_dynamic_body]["inv_mass"] = None
else:
self.shape_body[shape] = -1
else:
joint["parent_xform"] = incoming_xform * joint["parent_xform"]
joint["parent"] = last_dynamic_body
last_dynamic_body = child_body
incoming_xform = wp.transform()
retained_joints.append(joint)
new_id = len(retained_bodies)
body_data[child_body]["id"] = new_id
retained_bodies.append(child_body)
for shape in body_data[child_body]["shapes"]:
self.shape_body[shape] = new_id
visited[parent_body] = True
if visited[child_body] or child_body not in body_children:
return
for child in body_children[child_body]:
if not visited[child]:
dfs(child_body, child, incoming_xform, last_dynamic_body)
for body in body_children[-1]:
if not visited[body]:
dfs(-1, body, wp.transform(), -1)
# repopulate the model
self.body_name.clear()
self.body_q.clear()
self.body_qd.clear()
self.body_mass.clear()
self.body_inertia.clear()
self.body_com.clear()
self.body_inv_mass.clear()
self.body_inv_inertia.clear()
self.body_shapes.clear()
for i in retained_bodies:
body = body_data[i]
new_id = len(self.body_name)
body_remap[body["original_id"]] = new_id
self.body_name.append(body["name"])
self.body_q.append(list(body["q"]))
self.body_qd.append(list(body["qd"]))
m = body["mass"]
inertia = body["inertia"]
self.body_mass.append(m)
self.body_inertia.append(inertia)
self.body_com.append(body["com"])
if body["inv_mass"] is None:
# recompute inverse mass and inertia
if m > 0.0:
self.body_inv_mass.append(1.0 / m)
self.body_inv_inertia.append(wp.inverse(inertia))
else:
self.body_inv_mass.append(0.0)
self.body_inv_inertia.append(wp.mat33(0.0))
else:
self.body_inv_mass.append(body["inv_mass"])
self.body_inv_inertia.append(body["inv_inertia"])
self.body_shapes[new_id] = body["shapes"]
body_remap[body["original_id"]] = new_id
# sort joints so they appear in the same order as before
retained_joints.sort(key=lambda x: x["original_id"])
self.joint_name.clear()
self.joint_type.clear()
self.joint_parent.clear()
self.joint_child.clear()
self.joint_q.clear()
self.joint_qd.clear()
self.joint_q_start.clear()
self.joint_qd_start.clear()
self.joint_enabled.clear()
self.joint_linear_compliance.clear()
self.joint_angular_compliance.clear()
self.joint_armature.clear()
self.joint_X_p.clear()
self.joint_X_c.clear()
self.joint_axis.clear()
self.joint_axis_mode.clear()
self.joint_target_ke.clear()
self.joint_target_kd.clear()
self.joint_limit_lower.clear()
self.joint_limit_upper.clear()
self.joint_limit_ke.clear()
self.joint_limit_kd.clear()
self.joint_axis_dim.clear()
self.joint_axis_start.clear()
self.joint_act.clear()
for joint in retained_joints:
self.joint_name.append(joint["name"])
self.joint_type.append(joint["type"])
self.joint_parent.append(body_remap[joint["parent"]])
self.joint_child.append(body_remap[joint["child"]])
self.joint_q_start.append(len(self.joint_q))
self.joint_qd_start.append(len(self.joint_qd))
self.joint_q.extend(joint["q"])
self.joint_qd.extend(joint["qd"])
self.joint_act.extend(joint["act"])
self.joint_armature.extend(joint["armature"])
self.joint_enabled.append(joint["enabled"])
self.joint_linear_compliance.append(joint["linear_compliance"])
self.joint_angular_compliance.append(joint["angular_compliance"])
self.joint_X_p.append(list(joint["parent_xform"]))
self.joint_X_c.append(list(joint["child_xform"]))
self.joint_axis_dim.append(joint["axis_dim"])
self.joint_axis_start.append(len(self.joint_axis))
for axis in joint["axes"]:
self.joint_axis.append(axis["axis"])
self.joint_axis_mode.append(axis["axis_mode"])
self.joint_target_ke.append(axis["target_ke"])
self.joint_target_kd.append(axis["target_kd"])
self.joint_limit_lower.append(axis["limit_lower"])
self.joint_limit_upper.append(axis["limit_upper"])
self.joint_limit_ke.append(axis["limit_ke"])
self.joint_limit_kd.append(axis["limit_kd"])
# muscles
def add_muscle(
self, bodies: List[int], positions: List[Vec3], f0: float, lm: float, lt: float, lmax: float, pen: float
) -> float:
"""Adds a muscle-tendon activation unit.
Args:
bodies: A list of body indices for each waypoint
positions: A list of positions of each waypoint in the body's local frame
f0: Force scaling
lm: Muscle length
lt: Tendon length
lmax: Maximally efficient muscle length
Returns:
The index of the muscle in the model
.. note:: The simulation support for muscles is in progress and not yet fully functional.
"""
n = len(bodies)
self.muscle_start.append(len(self.muscle_bodies))
self.muscle_params.append((f0, lm, lt, lmax, pen))
self.muscle_activations.append(0.0)
for i in range(n):
self.muscle_bodies.append(bodies[i])
self.muscle_points.append(positions[i])
# return the index of the muscle
return len(self.muscle_start) - 1
# shapes
def add_shape_plane(
self,
plane: Vec4 = (0.0, 1.0, 0.0, 0.0),
pos: Vec3 = None,
rot: Quat = None,
width: float = 10.0,
length: float = 10.0,
body: int = -1,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
thickness: float = None,
has_ground_collision: bool = False,
has_shape_collision: bool = True,
is_visible: bool = True,
collision_group: int = -1,
):
"""
Adds a plane collision shape.
If pos and rot are defined, the plane is assumed to have its normal as (0, 1, 0).
Otherwise, the plane equation defined through the `plane` argument is used.
Args:
plane: The plane equation in form a*x + b*y + c*z + d = 0
pos: The position of the plane in world coordinates
rot: The rotation of the plane in world coordinates
width: The extent along x of the plane (infinite if 0)
length: The extent along z of the plane (infinite if 0)
body: The body index to attach the shape to (-1 by default to keep the plane static)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
thickness: The thickness of the plane (0 by default) for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
is_visible: Whether the plane is visible
collision_group: The collision group of the shape
Returns:
The index of the added shape
"""
if pos is None or rot is None:
# compute position and rotation from plane equation
normal = np.array(plane[:3])
normal /= np.linalg.norm(normal)
pos = plane[3] * normal
if np.allclose(normal, (0.0, 1.0, 0.0)):
# no rotation necessary
rot = (0.0, 0.0, 0.0, 1.0)
else:
c = np.cross(normal, (0.0, 1.0, 0.0))
angle = np.arcsin(np.linalg.norm(c))
axis = np.abs(c) / np.linalg.norm(c)
rot = wp.quat_from_axis_angle(axis, angle)
scale = wp.vec3(width, length, 0.0)
return self._add_shape(
body,
pos,
rot,
GEO_PLANE,
scale,
None,
0.0,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
is_visible=is_visible,
collision_group=collision_group,
)
def add_shape_sphere(
self,
body,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds a sphere collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the sphere
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: Whether the sphere is solid or hollow
thickness: Thickness to use for computing inertia of a hollow sphere, and for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the sphere is visible
Returns:
The index of the added shape
"""
thickness = self.default_shape_thickness if thickness is None else thickness
return self._add_shape(
body,
wp.vec3(pos),
wp.quat(rot),
GEO_SPHERE,
wp.vec3(radius, 0.0, 0.0),
None,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness + radius,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def add_shape_box(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
hx: float = 0.5,
hy: float = 0.5,
hz: float = 0.5,
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds a box collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
hx: The half-extent along the x-axis
hy: The half-extent along the y-axis
hz: The half-extent along the z-axis
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: Whether the box is solid or hollow
thickness: Thickness to use for computing inertia of a hollow box, and for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the box is visible
Returns:
The index of the added shape
"""
return self._add_shape(
body,
wp.vec3(pos),
wp.quat(rot),
GEO_BOX,
wp.vec3(hx, hy, hz),
None,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def add_shape_capsule(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
half_height: float = 0.5,
up_axis: int = 1,
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds a capsule collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the capsule
half_height: The half length of the center cylinder along the up axis
up_axis: The axis along which the capsule is aligned (0=x, 1=y, 2=z)
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: Whether the capsule is solid or hollow
thickness: Thickness to use for computing inertia of a hollow capsule, and for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the capsule is visible
Returns:
The index of the added shape
"""
q = wp.quat(rot)
sqh = math.sqrt(0.5)
if up_axis == 0:
q = wp.mul(q, wp.quat(0.0, 0.0, -sqh, sqh))
elif up_axis == 2:
q = wp.mul(q, wp.quat(sqh, 0.0, 0.0, sqh))
thickness = self.default_shape_thickness if thickness is None else thickness
return self._add_shape(
body,
wp.vec3(pos),
wp.quat(q),
GEO_CAPSULE,
wp.vec3(radius, half_height, 0.0),
None,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness + radius,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def add_shape_cylinder(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
half_height: float = 0.5,
up_axis: int = 1,
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds a cylinder collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the cylinder
half_height: The half length of the cylinder along the up axis
up_axis: The axis along which the cylinder is aligned (0=x, 1=y, 2=z)
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: Whether the cylinder is solid or hollow
thickness: Thickness to use for computing inertia of a hollow cylinder, and for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the cylinder is visible
Note:
Cylinders are currently not supported in rigid body collision handling.
Returns:
The index of the added shape
"""
q = rot
sqh = math.sqrt(0.5)
if up_axis == 0:
q = wp.mul(rot, wp.quat(0.0, 0.0, -sqh, sqh))
elif up_axis == 2:
q = wp.mul(rot, wp.quat(sqh, 0.0, 0.0, sqh))
return self._add_shape(
body,
wp.vec3(pos),
wp.quat(q),
GEO_CYLINDER,
wp.vec3(radius, half_height, 0.0),
None,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def add_shape_cone(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
radius: float = 1.0,
half_height: float = 0.5,
up_axis: int = 1,
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds a cone collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the cone
half_height: The half length of the cone along the up axis
up_axis: The axis along which the cone is aligned (0=x, 1=y, 2=z)
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: Whether the cone is solid or hollow
thickness: Thickness to use for computing inertia of a hollow cone, and for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the cone is visible
Note:
Cones are currently not supported in rigid body collision handling.
Returns:
The index of the added shape
"""
q = rot
sqh = math.sqrt(0.5)
if up_axis == 0:
q = wp.mul(rot, wp.quat(0.0, 0.0, -sqh, sqh))
elif up_axis == 2:
q = wp.mul(rot, wp.quat(sqh, 0.0, 0.0, sqh))
return self._add_shape(
body,
wp.vec3(pos),
wp.quat(q),
GEO_CONE,
wp.vec3(radius, half_height, 0.0),
None,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def add_shape_mesh(
self,
body: int,
pos: Optional[Vec3] = None,
rot: Optional[Quat] = None,
mesh: Optional[Mesh] = None,
scale: Optional[Vec3] = None,
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds a triangle mesh collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
(None to use the default value ``wp.vec3(0.0, 0.0, 0.0)``)
rot: The rotation of the shape with respect to the parent frame
(None to use the default value ``wp.quat(0.0, 0.0, 0.0, 1.0)``)
mesh: The mesh object
scale: Scale to use for the collider. (None to use the default value ``wp.vec3(1.0, 1.0, 1.0)``)
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: If True, the mesh is solid, otherwise it is a hollow surface with the given wall thickness
thickness: Thickness to use for computing inertia of a hollow mesh, and for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the mesh is visible
Returns:
The index of the added shape
"""
if pos is None:
pos = wp.vec3(0.0, 0.0, 0.0)
if rot is None:
rot = wp.quat(0.0, 0.0, 0.0, 1.0)
if scale is None:
scale = wp.vec3(1.0, 1.0, 1.0)
return self._add_shape(
body,
pos,
rot,
GEO_MESH,
wp.vec3(scale[0], scale[1], scale[2]),
mesh,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def add_shape_sdf(
self,
body: int,
pos: Vec3 = (0.0, 0.0, 0.0),
rot: Quat = (0.0, 0.0, 0.0, 1.0),
sdf: SDF = None,
scale: Vec3 = (1.0, 1.0, 1.0),
density: float = None,
ke: float = None,
kd: float = None,
kf: float = None,
ka: float = None,
mu: float = None,
restitution: float = None,
is_solid: bool = True,
thickness: float = None,
has_ground_collision: bool = True,
has_shape_collision: bool = True,
collision_group: int = -1,
is_visible: bool = True,
):
"""Adds SDF collision shape to a body.
Args:
body: The index of the parent body this shape belongs to (use -1 for static shapes)
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
sdf: The sdf object
scale: Scale to use for the collider
density: The density of the shape (None to use the default value :attr:`default_shape_density`)
ke: The contact elastic stiffness (None to use the default value :attr:`default_shape_ke`)
kd: The contact damping stiffness (None to use the default value :attr:`default_shape_kd`)
kf: The contact friction stiffness (None to use the default value :attr:`default_shape_kf`)
ka: The contact adhesion distance (None to use the default value :attr:`default_shape_ka`)
mu: The coefficient of friction (None to use the default value :attr:`default_shape_mu`)
restitution: The coefficient of restitution (None to use the default value :attr:`default_shape_restitution`)
is_solid: If True, the SDF is solid, otherwise it is a hollow surface with the given wall thickness
thickness: Thickness to use for collision handling (None to use the default value :attr:`default_shape_thickness`)
has_ground_collision: If True, the shape will collide with the ground plane if `Model.ground` is True
has_shape_collision: If True, the shape will collide with other shapes
collision_group: The collision group of the shape
is_visible: Whether the shape is visible
Returns:
The index of the added shape
"""
return self._add_shape(
body,
wp.vec3(pos),
wp.quat(rot),
GEO_SDF,
wp.vec3(scale[0], scale[1], scale[2]),
sdf,
density,
ke,
kd,
kf,
ka,
mu,
restitution,
thickness,
is_solid,
has_ground_collision=has_ground_collision,
has_shape_collision=has_shape_collision,
collision_group=collision_group,
is_visible=is_visible,
)
def _shape_radius(self, type, scale, src):
"""
Calculates the radius of a sphere that encloses the shape, used for broadphase collision detection.
"""
if type == GEO_SPHERE:
return scale[0]
elif type == GEO_BOX:
return np.linalg.norm(scale)
elif type == GEO_CAPSULE or type == GEO_CYLINDER or type == GEO_CONE:
return scale[0] + scale[1]
elif type == GEO_MESH:
vmax = np.max(np.abs(src.vertices), axis=0) * np.max(scale)
return np.linalg.norm(vmax)
elif type == GEO_PLANE:
if scale[0] > 0.0 and scale[1] > 0.0:
# finite plane
return np.linalg.norm(scale)
else:
return 1.0e6
else:
return 10.0
def _add_shape(
self,
body,
pos,
rot,
type,
scale,
src=None,
density=None,
ke=None,
kd=None,
kf=None,
ka=None,
mu=None,
restitution=None,
thickness=None,
is_solid=True,
collision_group=-1,
collision_filter_parent=True,
has_ground_collision=True,
has_shape_collision=True,
is_visible=True,
):
self.shape_body.append(body)
shape = self.shape_count
if body in self.body_shapes:
# no contacts between shapes of the same body
for same_body_shape in self.body_shapes[body]:
self.shape_collision_filter_pairs.add((same_body_shape, shape))
self.body_shapes[body].append(shape)
else:
self.body_shapes[body] = [shape]
ke = ke if ke is not None else self.default_shape_ke
kd = kd if kd is not None else self.default_shape_kd
kf = kf if kf is not None else self.default_shape_kf
ka = ka if ka is not None else self.default_shape_ka
mu = mu if mu is not None else self.default_shape_mu
restitution = restitution if restitution is not None else self.default_shape_restitution
thickness = thickness if thickness is not None else self.default_shape_thickness
density = density if density is not None else self.default_shape_density
self.shape_transform.append(wp.transform(pos, rot))
self.shape_visible.append(is_visible)
self.shape_geo_type.append(type)
self.shape_geo_scale.append((scale[0], scale[1], scale[2]))
self.shape_geo_src.append(src)
self.shape_geo_thickness.append(thickness)
self.shape_geo_is_solid.append(is_solid)
self.shape_material_ke.append(ke)
self.shape_material_kd.append(kd)
self.shape_material_kf.append(kf)
self.shape_material_ka.append(ka)
self.shape_material_mu.append(mu)
self.shape_material_restitution.append(restitution)
self.shape_collision_group.append(collision_group)
if collision_group not in self.shape_collision_group_map:
self.shape_collision_group_map[collision_group] = []
self.last_collision_group = max(self.last_collision_group, collision_group)
self.shape_collision_group_map[collision_group].append(shape)
self.shape_collision_radius.append(self._shape_radius(type, scale, src))
if collision_filter_parent and body > -1 and body in self.joint_parents:
for parent_body in self.joint_parents[body]:
if parent_body > -1:
for parent_shape in self.body_shapes[parent_body]:
self.shape_collision_filter_pairs.add((parent_shape, shape))
if body == -1:
has_ground_collision = False
self.shape_ground_collision.append(has_ground_collision)
self.shape_shape_collision.append(has_shape_collision)
(m, c, I) = compute_shape_mass(type, scale, src, density, is_solid, thickness)
self._update_body_mass(body, m, I, pos + c, rot)
return shape
# particles
def add_particle(
self, pos: Vec3, vel: Vec3, mass: float, radius: float = None, flags: wp.uint32 = PARTICLE_FLAG_ACTIVE
) -> int:
"""Adds a single particle to the model
Args:
pos: The initial position of the particle
vel: The initial velocity of the particle
mass: The mass of the particle
radius: The radius of the particle used in collision handling. If None, the radius is set to the default value (:attr:`default_particle_radius`).
flags: The flags that control the dynamical behavior of the particle, see PARTICLE_FLAG_* constants
Note:
Set the mass equal to zero to create a 'kinematic' particle that does is not subject to dynamics.
Returns:
The index of the particle in the system
"""
self.particle_q.append(pos)
self.particle_qd.append(vel)
self.particle_mass.append(mass)
if radius is None:
radius = self.default_particle_radius
self.particle_radius.append(radius)
self.particle_flags.append(flags)
return len(self.particle_q) - 1
def add_spring(self, i: int, j, ke: float, kd: float, control: float):
"""Adds a spring between two particles in the system
Args:
i: The index of the first particle
j: The index of the second particle
ke: The elastic stiffness of the spring
kd: The damping stiffness of the spring
control: The actuation level of the spring
Note:
The spring is created with a rest-length based on the distance
between the particles in their initial configuration.
"""
self.spring_indices.append(i)
self.spring_indices.append(j)
self.spring_stiffness.append(ke)
self.spring_damping.append(kd)
self.spring_control.append(control)
# compute rest length
p = self.particle_q[i]
q = self.particle_q[j]
delta = np.subtract(p, q)
l = np.sqrt(np.dot(delta, delta))
self.spring_rest_length.append(l)
def add_triangle(
self,
i: int,
j: int,
k: int,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
) -> float:
"""Adds a triangular FEM element between three particles in the system.
Triangles are modeled as viscoelastic elements with elastic stiffness and damping
parameters specified on the model. See model.tri_ke, model.tri_kd.
Args:
i: The index of the first particle
j: The index of the second particle
k: The index of the third particle
Return:
The area of the triangle
Note:
The triangle is created with a rest-length based on the distance
between the particles in their initial configuration.
"""
# TODO: Expose elastic parameters on a per-element basis
# compute basis for 2D rest pose
p = self.particle_q[i]
q = self.particle_q[j]
r = self.particle_q[k]
qp = q - p
rp = r - p
# construct basis aligned with the triangle
n = wp.normalize(wp.cross(qp, rp))
e1 = wp.normalize(qp)
e2 = wp.normalize(wp.cross(n, e1))
R = np.array((e1, e2))
M = np.array((qp, rp))
D = R @ M.T
area = np.linalg.det(D) / 2.0
if area <= 0.0:
print("inverted or degenerate triangle element")
return 0.0
else:
inv_D = np.linalg.inv(D)
self.tri_indices.append((i, j, k))
self.tri_poses.append(inv_D.tolist())
self.tri_activations.append(0.0)
self.tri_materials.append((tri_ke, tri_ka, tri_kd, tri_drag, tri_lift))
return area
def add_triangles(
self,
i: List[int],
j: List[int],
k: List[int],
tri_ke: Optional[List[float]] = None,
tri_ka: Optional[List[float]] = None,
tri_kd: Optional[List[float]] = None,
tri_drag: Optional[List[float]] = None,
tri_lift: Optional[List[float]] = None,
) -> List[float]:
"""Adds triangular FEM elements between groups of three particles in the system.
Triangles are modeled as viscoelastic elements with elastic stiffness and damping
Parameters specified on the model. See model.tri_ke, model.tri_kd.
Args:
i: The indices of the first particle
j: The indices of the second particle
k: The indices of the third particle
Return:
The areas of the triangles
Note:
A triangle is created with a rest-length based on the distance
between the particles in their initial configuration.
"""
# compute basis for 2D rest pose
p = np.array(self.particle_q)[i]
q = np.array(self.particle_q)[j]
r = np.array(self.particle_q)[k]
qp = q - p
rp = r - p
def normalized(a):
l = np.linalg.norm(a, axis=-1, keepdims=True)
l[l == 0] = 1.0
return a / l
n = normalized(np.cross(qp, rp))
e1 = normalized(qp)
e2 = normalized(np.cross(n, e1))
R = np.concatenate((e1[..., None], e2[..., None]), axis=-1)
M = np.concatenate((qp[..., None], rp[..., None]), axis=-1)
D = np.matmul(R.transpose(0, 2, 1), M)
areas = np.linalg.det(D) / 2.0
areas[areas < 0.0] = 0.0
valid_inds = (areas > 0.0).nonzero()[0]
if len(valid_inds) < len(areas):
print("inverted or degenerate triangle elements")
D[areas == 0.0] = np.eye(2)[None, ...]
inv_D = np.linalg.inv(D)
inds = np.concatenate((i[valid_inds, None], j[valid_inds, None], k[valid_inds, None]), axis=-1)
self.tri_indices.extend(inds.tolist())
self.tri_poses.extend(inv_D[valid_inds].tolist())
self.tri_activations.extend([0.0] * len(valid_inds))
def init_if_none(arr, defaultValue):
if arr is None:
return [defaultValue] * len(areas)
return arr
tri_ke = init_if_none(tri_ke, self.default_tri_ke)
tri_ka = init_if_none(tri_ka, self.default_tri_ka)
tri_kd = init_if_none(tri_kd, self.default_tri_kd)
tri_drag = init_if_none(tri_drag, self.default_tri_drag)
tri_lift = init_if_none(tri_lift, self.default_tri_lift)
self.tri_materials.extend(
zip(
np.array(tri_ke)[valid_inds],
np.array(tri_ka)[valid_inds],
np.array(tri_kd)[valid_inds],
np.array(tri_drag)[valid_inds],
np.array(tri_lift)[valid_inds],
)
)
return areas.tolist()
def add_tetrahedron(
self, i: int, j: int, k: int, l: int, k_mu: float = 1.0e3, k_lambda: float = 1.0e3, k_damp: float = 0.0
) -> float:
"""Adds a tetrahedral FEM element between four particles in the system.
Tetrahedra are modeled as viscoelastic elements with a NeoHookean energy
density based on [Smith et al. 2018].
Args:
i: The index of the first particle
j: The index of the second particle
k: The index of the third particle
l: The index of the fourth particle
k_mu: The first elastic Lame parameter
k_lambda: The second elastic Lame parameter
k_damp: The element's damping stiffness
Return:
The volume of the tetrahedron
Note:
The tetrahedron is created with a rest-pose based on the particle's initial configuration
"""
# compute basis for 2D rest pose
p = np.array(self.particle_q[i])
q = np.array(self.particle_q[j])
r = np.array(self.particle_q[k])
s = np.array(self.particle_q[l])
qp = q - p
rp = r - p
sp = s - p
Dm = np.array((qp, rp, sp)).T
volume = np.linalg.det(Dm) / 6.0
if volume <= 0.0:
print("inverted tetrahedral element")
else:
inv_Dm = np.linalg.inv(Dm)
self.tet_indices.append((i, j, k, l))
self.tet_poses.append(inv_Dm.tolist())
self.tet_activations.append(0.0)
self.tet_materials.append((k_mu, k_lambda, k_damp))
return volume
def add_edge(
self,
i: int,
j: int,
k: int,
l: int,
rest: float = None,
edge_ke: float = default_edge_ke,
edge_kd: float = default_edge_kd,
):
"""Adds a bending edge element between four particles in the system.
Bending elements are designed to be between two connected triangles. Then
bending energy is based of [Bridson et al. 2002]. Bending stiffness is controlled
by the `model.tri_kb` parameter.
Args:
i: The index of the first particle
j: The index of the second particle
k: The index of the third particle
l: The index of the fourth particle
rest: The rest angle across the edge in radians, if not specified it will be computed
Note:
The edge lies between the particles indexed by 'k' and 'l' parameters with the opposing
vertices indexed by 'i' and 'j'. This defines two connected triangles with counter clockwise
winding: (i, k, l), (j, l, k).
"""
# compute rest angle
if rest is None:
x1 = self.particle_q[i]
x2 = self.particle_q[j]
x3 = self.particle_q[k]
x4 = self.particle_q[l]
n1 = wp.normalize(wp.cross(x3 - x1, x4 - x1))
n2 = wp.normalize(wp.cross(x4 - x2, x3 - x2))
e = wp.normalize(x4 - x3)
d = np.clip(np.dot(n2, n1), -1.0, 1.0)
angle = math.acos(d)
sign = np.sign(np.dot(np.cross(n2, n1), e))
rest = angle * sign
self.edge_indices.append((i, j, k, l))
self.edge_rest_angle.append(rest)
self.edge_bending_properties.append((edge_ke, edge_kd))
def add_edges(
self,
i,
j,
k,
l,
rest: Optional[List[float]] = None,
edge_ke: Optional[List[float]] = None,
edge_kd: Optional[List[float]] = None,
):
"""Adds bending edge elements between groups of four particles in the system.
Bending elements are designed to be between two connected triangles. Then
bending energy is based of [Bridson et al. 2002]. Bending stiffness is controlled
by the `model.tri_kb` parameter.
Args:
i: The indices of the first particle
j: The indices of the second particle
k: The indices of the third particle
l: The indices of the fourth particle
rest: The rest angles across the edges in radians, if not specified they will be computed
Note:
The edge lies between the particles indexed by 'k' and 'l' parameters with the opposing
vertices indexed by 'i' and 'j'. This defines two connected triangles with counter clockwise
winding: (i, k, l), (j, l, k).
"""
if rest is None:
# compute rest angle
x1 = np.array(self.particle_q)[i]
x2 = np.array(self.particle_q)[j]
x3 = np.array(self.particle_q)[k]
x4 = np.array(self.particle_q)[l]
def normalized(a):
l = np.linalg.norm(a, axis=-1, keepdims=True)
l[l == 0] = 1.0
return a / l
n1 = normalized(np.cross(x3 - x1, x4 - x1))
n2 = normalized(np.cross(x4 - x2, x3 - x2))
e = normalized(x4 - x3)
def dot(a, b):
return (a * b).sum(axis=-1)
d = np.clip(dot(n2, n1), -1.0, 1.0)
angle = np.arccos(d)
sign = np.sign(dot(np.cross(n2, n1), e))
rest = angle * sign
inds = np.concatenate((i[:, None], j[:, None], k[:, None], l[:, None]), axis=-1)
self.edge_indices.extend(inds.tolist())
self.edge_rest_angle.extend(rest.tolist())
def init_if_none(arr, defaultValue):
if arr is None:
return [defaultValue] * len(i)
return arr
edge_ke = init_if_none(edge_ke, self.default_edge_ke)
edge_kd = init_if_none(edge_kd, self.default_edge_kd)
self.edge_bending_properties.extend(zip(edge_ke, edge_kd))
def add_cloth_grid(
self,
pos: Vec3,
rot: Quat,
vel: Vec3,
dim_x: int,
dim_y: int,
cell_x: float,
cell_y: float,
mass: float,
reverse_winding: bool = False,
fix_left: bool = False,
fix_right: bool = False,
fix_top: bool = False,
fix_bottom: bool = False,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
edge_ke: float = default_edge_ke,
edge_kd: float = default_edge_kd,
add_springs: bool = False,
spring_ke: float = default_spring_ke,
spring_kd: float = default_spring_kd,
):
"""Helper to create a regular planar cloth grid
Creates a rectangular grid of particles with FEM triangles and bending elements
automatically.
Args:
pos: The position of the cloth in world space
rot: The orientation of the cloth in world space
vel: The velocity of the cloth in world space
dim_x_: The number of rectangular cells along the x-axis
dim_y: The number of rectangular cells along the y-axis
cell_x: The width of each cell in the x-direction
cell_y: The width of each cell in the y-direction
mass: The mass of each particle
reverse_winding: Flip the winding of the mesh
fix_left: Make the left-most edge of particles kinematic (fixed in place)
fix_right: Make the right-most edge of particles kinematic
fix_top: Make the top-most edge of particles kinematic
fix_bottom: Make the bottom-most edge of particles kinematic
"""
def grid_index(x, y, dim_x):
return y * dim_x + x
start_vertex = len(self.particle_q)
start_tri = len(self.tri_indices)
for y in range(0, dim_y + 1):
for x in range(0, dim_x + 1):
g = wp.vec3(x * cell_x, y * cell_y, 0.0)
p = wp.quat_rotate(rot, g) + pos
m = mass
if x == 0 and fix_left:
m = 0.0
elif x == dim_x and fix_right:
m = 0.0
elif y == 0 and fix_bottom:
m = 0.0
elif y == dim_y and fix_top:
m = 0.0
self.add_particle(p, vel, m)
if x > 0 and y > 0:
if reverse_winding:
tri1 = (
start_vertex + grid_index(x - 1, y - 1, dim_x + 1),
start_vertex + grid_index(x, y - 1, dim_x + 1),
start_vertex + grid_index(x, y, dim_x + 1),
)
tri2 = (
start_vertex + grid_index(x - 1, y - 1, dim_x + 1),
start_vertex + grid_index(x, y, dim_x + 1),
start_vertex + grid_index(x - 1, y, dim_x + 1),
)
self.add_triangle(*tri1, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
self.add_triangle(*tri2, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
else:
tri1 = (
start_vertex + grid_index(x - 1, y - 1, dim_x + 1),
start_vertex + grid_index(x, y - 1, dim_x + 1),
start_vertex + grid_index(x - 1, y, dim_x + 1),
)
tri2 = (
start_vertex + grid_index(x, y - 1, dim_x + 1),
start_vertex + grid_index(x, y, dim_x + 1),
start_vertex + grid_index(x - 1, y, dim_x + 1),
)
self.add_triangle(*tri1, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
self.add_triangle(*tri2, tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
end_tri = len(self.tri_indices)
# bending constraints, could create these explicitly for a grid but this
# is a good test of the adjacency structure
adj = wp.utils.MeshAdjacency(self.tri_indices[start_tri:end_tri], end_tri - start_tri)
spring_indices = set()
for _k, e in adj.edges.items():
# skip open edges
if e.f0 == -1 or e.f1 == -1:
continue
self.add_edge(
e.o0, e.o1, e.v0, e.v1, edge_ke=edge_ke, edge_kd=edge_kd
) # opposite 0, opposite 1, vertex 0, vertex 1
spring_indices.add((min(e.o0, e.o1), max(e.o0, e.o1)))
spring_indices.add((min(e.o0, e.v0), max(e.o0, e.v0)))
spring_indices.add((min(e.o0, e.v1), max(e.o0, e.v1)))
spring_indices.add((min(e.o1, e.v0), max(e.o1, e.v0)))
spring_indices.add((min(e.o1, e.v1), max(e.o1, e.v1)))
spring_indices.add((min(e.v0, e.v1), max(e.v0, e.v1)))
if add_springs:
for i, j in spring_indices:
self.add_spring(i, j, spring_ke, spring_kd, control=0.0)
def add_cloth_mesh(
self,
pos: Vec3,
rot: Quat,
scale: float,
vel: Vec3,
vertices: List[Vec3],
indices: List[int],
density: float,
edge_callback=None,
face_callback=None,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
edge_ke: float = default_edge_ke,
edge_kd: float = default_edge_kd,
add_springs: bool = False,
spring_ke: float = default_spring_ke,
spring_kd: float = default_spring_kd,
):
"""Helper to create a cloth model from a regular triangle mesh
Creates one FEM triangle element and one bending element for every face
and edge in the input triangle mesh
Args:
pos: The position of the cloth in world space
rot: The orientation of the cloth in world space
vel: The velocity of the cloth in world space
vertices: A list of vertex positions
indices: A list of triangle indices, 3 entries per-face
density: The density per-area of the mesh
edge_callback: A user callback when an edge is created
face_callback: A user callback when a face is created
Note:
The mesh should be two manifold.
"""
num_tris = int(len(indices) / 3)
start_vertex = len(self.particle_q)
start_tri = len(self.tri_indices)
# particles
for v in vertices:
p = wp.quat_rotate(rot, v * scale) + pos
self.add_particle(p, vel, 0.0)
# triangles
inds = start_vertex + np.array(indices)
inds = inds.reshape(-1, 3)
areas = self.add_triangles(
inds[:, 0],
inds[:, 1],
inds[:, 2],
[tri_ke] * num_tris,
[tri_ka] * num_tris,
[tri_kd] * num_tris,
[tri_drag] * num_tris,
[tri_lift] * num_tris,
)
for t in range(num_tris):
area = areas[t]
self.particle_mass[inds[t, 0]] += density * area / 3.0
self.particle_mass[inds[t, 1]] += density * area / 3.0
self.particle_mass[inds[t, 2]] += density * area / 3.0
end_tri = len(self.tri_indices)
adj = wp.utils.MeshAdjacency(self.tri_indices[start_tri:end_tri], end_tri - start_tri)
edgeinds = np.fromiter(
(x for e in adj.edges.values() if e.f0 != -1 and e.f1 != -1 for x in (e.o0, e.o1, e.v0, e.v1)),
int,
).reshape(-1, 4)
self.add_edges(
edgeinds[:, 0],
edgeinds[:, 1],
edgeinds[:, 2],
edgeinds[:, 0],
edge_ke=[edge_ke] * len(edgeinds),
edge_kd=[edge_kd] * len(edgeinds),
)
if add_springs:
spring_indices = set()
for i, j, k, l in edgeinds:
spring_indices.add((min(i, j), max(i, j)))
spring_indices.add((min(i, k), max(i, k)))
spring_indices.add((min(i, l), max(i, l)))
spring_indices.add((min(j, k), max(j, k)))
spring_indices.add((min(j, l), max(j, l)))
spring_indices.add((min(k, l), max(k, l)))
for i, j in spring_indices:
self.add_spring(i, j, spring_ke, spring_kd, control=0.0)
def add_particle_grid(
self,
pos: Vec3,
rot: Quat,
vel: Vec3,
dim_x: int,
dim_y: int,
dim_z: int,
cell_x: float,
cell_y: float,
cell_z: float,
mass: float,
jitter: float,
radius_mean: float = default_particle_radius,
radius_std: float = 0.0,
):
rng = np.random.default_rng()
for z in range(dim_z):
for y in range(dim_y):
for x in range(dim_x):
v = wp.vec3(x * cell_x, y * cell_y, z * cell_z)
m = mass
p = wp.quat_rotate(rot, v) + pos + wp.vec3(rng.random(3) * jitter)
if radius_std > 0.0:
r = radius_mean + np.random.randn() * radius_std
else:
r = radius_mean
self.add_particle(p, vel, m, r)
def add_soft_grid(
self,
pos: Vec3,
rot: Quat,
vel: Vec3,
dim_x: int,
dim_y: int,
dim_z: int,
cell_x: float,
cell_y: float,
cell_z: float,
density: float,
k_mu: float,
k_lambda: float,
k_damp: float,
fix_left: bool = False,
fix_right: bool = False,
fix_top: bool = False,
fix_bottom: bool = False,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
):
"""Helper to create a rectangular tetrahedral FEM grid
Creates a regular grid of FEM tetrahedra and surface triangles. Useful for example
to create beams and sheets. Each hexahedral cell is decomposed into 5
tetrahedral elements.
Args:
pos: The position of the solid in world space
rot: The orientation of the solid in world space
vel: The velocity of the solid in world space
dim_x_: The number of rectangular cells along the x-axis
dim_y: The number of rectangular cells along the y-axis
dim_z: The number of rectangular cells along the z-axis
cell_x: The width of each cell in the x-direction
cell_y: The width of each cell in the y-direction
cell_z: The width of each cell in the z-direction
density: The density of each particle
k_mu: The first elastic Lame parameter
k_lambda: The second elastic Lame parameter
k_damp: The damping stiffness
fix_left: Make the left-most edge of particles kinematic (fixed in place)
fix_right: Make the right-most edge of particles kinematic
fix_top: Make the top-most edge of particles kinematic
fix_bottom: Make the bottom-most edge of particles kinematic
"""
start_vertex = len(self.particle_q)
mass = cell_x * cell_y * cell_z * density
for z in range(dim_z + 1):
for y in range(dim_y + 1):
for x in range(dim_x + 1):
v = wp.vec3(x * cell_x, y * cell_y, z * cell_z)
m = mass
if fix_left and x == 0:
m = 0.0
if fix_right and x == dim_x:
m = 0.0
if fix_top and y == dim_y:
m = 0.0
if fix_bottom and y == 0:
m = 0.0
p = wp.quat_rotate(rot, v) + pos
self.add_particle(p, vel, m)
# dict of open faces
faces = {}
def add_face(i: int, j: int, k: int):
key = tuple(sorted((i, j, k)))
if key not in faces:
faces[key] = (i, j, k)
else:
del faces[key]
def add_tet(i: int, j: int, k: int, l: int):
self.add_tetrahedron(i, j, k, l, k_mu, k_lambda, k_damp)
add_face(i, k, j)
add_face(j, k, l)
add_face(i, j, l)
add_face(i, l, k)
def grid_index(x, y, z):
return (dim_x + 1) * (dim_y + 1) * z + (dim_x + 1) * y + x
for z in range(dim_z):
for y in range(dim_y):
for x in range(dim_x):
v0 = grid_index(x, y, z) + start_vertex
v1 = grid_index(x + 1, y, z) + start_vertex
v2 = grid_index(x + 1, y, z + 1) + start_vertex
v3 = grid_index(x, y, z + 1) + start_vertex
v4 = grid_index(x, y + 1, z) + start_vertex
v5 = grid_index(x + 1, y + 1, z) + start_vertex
v6 = grid_index(x + 1, y + 1, z + 1) + start_vertex
v7 = grid_index(x, y + 1, z + 1) + start_vertex
if (x & 1) ^ (y & 1) ^ (z & 1):
add_tet(v0, v1, v4, v3)
add_tet(v2, v3, v6, v1)
add_tet(v5, v4, v1, v6)
add_tet(v7, v6, v3, v4)
add_tet(v4, v1, v6, v3)
else:
add_tet(v1, v2, v5, v0)
add_tet(v3, v0, v7, v2)
add_tet(v4, v7, v0, v5)
add_tet(v6, v5, v2, v7)
add_tet(v5, v2, v7, v0)
# add triangles
for _k, v in faces.items():
self.add_triangle(v[0], v[1], v[2], tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
def add_soft_mesh(
self,
pos: Vec3,
rot: Quat,
scale: float,
vel: Vec3,
vertices: List[Vec3],
indices: List[int],
density: float,
k_mu: float,
k_lambda: float,
k_damp: float,
tri_ke: float = default_tri_ke,
tri_ka: float = default_tri_ka,
tri_kd: float = default_tri_kd,
tri_drag: float = default_tri_drag,
tri_lift: float = default_tri_lift,
):
"""Helper to create a tetrahedral model from an input tetrahedral mesh
Args:
pos: The position of the solid in world space
rot: The orientation of the solid in world space
vel: The velocity of the solid in world space
vertices: A list of vertex positions, array of 3D points
indices: A list of tetrahedron indices, 4 entries per-element, flattened array
density: The density per-area of the mesh
k_mu: The first elastic Lame parameter
k_lambda: The second elastic Lame parameter
k_damp: The damping stiffness
"""
num_tets = int(len(indices) / 4)
start_vertex = len(self.particle_q)
# dict of open faces
faces = {}
def add_face(i, j, k):
key = tuple(sorted((i, j, k)))
if key not in faces:
faces[key] = (i, j, k)
else:
del faces[key]
pos = wp.vec3(pos[0], pos[1], pos[2])
# add particles
for v in vertices:
v = wp.vec3(v[0], v[1], v[2])
p = wp.quat_rotate(rot, v * scale) + pos
self.add_particle(p, vel, 0.0)
# add tetrahedra
for t in range(num_tets):
v0 = start_vertex + indices[t * 4 + 0]
v1 = start_vertex + indices[t * 4 + 1]
v2 = start_vertex + indices[t * 4 + 2]
v3 = start_vertex + indices[t * 4 + 3]
volume = self.add_tetrahedron(v0, v1, v2, v3, k_mu, k_lambda, k_damp)
# distribute volume fraction to particles
if volume > 0.0:
self.particle_mass[v0] += density * volume / 4.0
self.particle_mass[v1] += density * volume / 4.0
self.particle_mass[v2] += density * volume / 4.0
self.particle_mass[v3] += density * volume / 4.0
# build open faces
add_face(v0, v2, v1)
add_face(v1, v2, v3)
add_face(v0, v1, v3)
add_face(v0, v3, v2)
# add triangles
for _k, v in faces.items():
try:
self.add_triangle(v[0], v[1], v[2], tri_ke, tri_ka, tri_kd, tri_drag, tri_lift)
except np.linalg.LinAlgError:
continue
# incrementally updates rigid body mass with additional mass and inertia expressed at a local to the body
def _update_body_mass(self, i, m, I, p, q):
if i == -1:
return
# find new COM
new_mass = self.body_mass[i] + m
if new_mass == 0.0: # no mass
return
new_com = (self.body_com[i] * self.body_mass[i] + p * m) / new_mass
# shift inertia to new COM
com_offset = new_com - self.body_com[i]
shape_offset = new_com - p
new_inertia = transform_inertia(
self.body_mass[i], self.body_inertia[i], com_offset, wp.quat_identity()
) + transform_inertia(m, I, shape_offset, q)
self.body_mass[i] = new_mass
self.body_inertia[i] = new_inertia
self.body_com[i] = new_com
if new_mass > 0.0:
self.body_inv_mass[i] = 1.0 / new_mass
else:
self.body_inv_mass[i] = 0.0
if any(x for x in new_inertia):
self.body_inv_inertia[i] = wp.inverse(new_inertia)
else:
self.body_inv_inertia[i] = new_inertia
def set_ground_plane(
self,
normal=None,
offset=0.0,
ke: float = default_shape_ke,
kd: float = default_shape_kd,
kf: float = default_shape_kf,
mu: float = default_shape_mu,
restitution: float = default_shape_restitution,
):
"""
Creates a ground plane for the world. If the normal is not specified,
the up_vector of the ModelBuilder is used.
"""
if normal is None:
normal = self.up_vector
self._ground_params = {
"plane": (*normal, offset),
"width": 0.0,
"length": 0.0,
"ke": ke,
"kd": kd,
"kf": kf,
"mu": mu,
"restitution": restitution,
}
def _create_ground_plane(self):
ground_id = self.add_shape_plane(**self._ground_params)
self._ground_created = True
# disable ground collisions as they will be treated separately
for i in range(self.shape_count - 1):
self.shape_collision_filter_pairs.add((i, ground_id))
def finalize(self, device=None, requires_grad=False) -> Model:
"""Convert this builder object to a concrete model for simulation.
After building simulation elements this method should be called to transfer
all data to device memory ready for simulation.
Args:
device: The simulation device to use, e.g.: 'cpu', 'cuda'
requires_grad: Whether to enable gradient computation for the model
Returns:
A model object.
"""
# ensure the env count is set correctly
self.num_envs = max(1, self.num_envs)
# add ground plane if not already created
if not self._ground_created:
self._create_ground_plane()
# construct particle inv masses
ms = np.array(self.particle_mass, dtype=np.float32)
# static particles (with zero mass) have zero inverse mass
particle_inv_mass = np.divide(1.0, ms, out=np.zeros_like(ms), where=ms != 0.0)
with wp.ScopedDevice(device):
# -------------------------------------
# construct Model (non-time varying) data
m = Model(device)
m.requires_grad = requires_grad
m.ground_plane_params = self._ground_params["plane"]
m.num_envs = self.num_envs
# ---------------------
# particles
# state (initial)
m.particle_q = wp.array(self.particle_q, dtype=wp.vec3, requires_grad=requires_grad)
m.particle_qd = wp.array(self.particle_qd, dtype=wp.vec3, requires_grad=requires_grad)
m.particle_mass = wp.array(self.particle_mass, dtype=wp.float32, requires_grad=requires_grad)
m.particle_inv_mass = wp.array(particle_inv_mass, dtype=wp.float32, requires_grad=requires_grad)
m.particle_radius = wp.array(self.particle_radius, dtype=wp.float32, requires_grad=requires_grad)
m.particle_flags = wp.array([flag_to_int(f) for f in self.particle_flags], dtype=wp.uint32)
m.particle_max_radius = np.max(self.particle_radius) if len(self.particle_radius) > 0 else 0.0
m.particle_max_velocity = self.particle_max_velocity
# hash-grid for particle interactions
m.particle_grid = wp.HashGrid(128, 128, 128)
# ---------------------
# collision geometry
m.shape_transform = wp.array(self.shape_transform, dtype=wp.transform, requires_grad=requires_grad)
m.shape_body = wp.array(self.shape_body, dtype=wp.int32)
m.shape_visible = wp.array(self.shape_visible, dtype=wp.bool)
m.body_shapes = self.body_shapes
# build list of ids for geometry sources (meshes, sdfs)
geo_sources = []
finalized_meshes = {} # do not duplicate meshes
for geo in self.shape_geo_src:
geo_hash = hash(geo) # avoid repeated hash computations
if geo:
if geo_hash not in finalized_meshes:
finalized_meshes[geo_hash] = geo.finalize(device=device)
geo_sources.append(finalized_meshes[geo_hash])
else:
# add null pointer
geo_sources.append(0)
m.shape_geo.type = wp.array(self.shape_geo_type, dtype=wp.int32)
m.shape_geo.source = wp.array(geo_sources, dtype=wp.uint64)
m.shape_geo.scale = wp.array(self.shape_geo_scale, dtype=wp.vec3, requires_grad=requires_grad)
m.shape_geo.is_solid = wp.array(self.shape_geo_is_solid, dtype=wp.uint8)
m.shape_geo.thickness = wp.array(self.shape_geo_thickness, dtype=wp.float32, requires_grad=requires_grad)
m.shape_geo_src = self.shape_geo_src # used for rendering
# store refs to geometry
m.geo_meshes = self.geo_meshes
m.geo_sdfs = self.geo_sdfs
m.shape_materials.ke = wp.array(self.shape_material_ke, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.kd = wp.array(self.shape_material_kd, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.kf = wp.array(self.shape_material_kf, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.ka = wp.array(self.shape_material_ka, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.mu = wp.array(self.shape_material_mu, dtype=wp.float32, requires_grad=requires_grad)
m.shape_materials.restitution = wp.array(
self.shape_material_restitution, dtype=wp.float32, requires_grad=requires_grad
)
m.shape_collision_filter_pairs = self.shape_collision_filter_pairs
m.shape_collision_group = self.shape_collision_group
m.shape_collision_group_map = self.shape_collision_group_map
m.shape_collision_radius = wp.array(
self.shape_collision_radius, dtype=wp.float32, requires_grad=requires_grad
)
m.shape_ground_collision = self.shape_ground_collision
m.shape_shape_collision = self.shape_shape_collision
# ---------------------
# springs
m.spring_indices = wp.array(self.spring_indices, dtype=wp.int32)
m.spring_rest_length = wp.array(self.spring_rest_length, dtype=wp.float32, requires_grad=requires_grad)
m.spring_stiffness = wp.array(self.spring_stiffness, dtype=wp.float32, requires_grad=requires_grad)
m.spring_damping = wp.array(self.spring_damping, dtype=wp.float32, requires_grad=requires_grad)
m.spring_control = wp.array(self.spring_control, dtype=wp.float32, requires_grad=requires_grad)
# ---------------------
# triangles
m.tri_indices = wp.array(self.tri_indices, dtype=wp.int32)
m.tri_poses = wp.array(self.tri_poses, dtype=wp.mat22, requires_grad=requires_grad)
m.tri_activations = wp.array(self.tri_activations, dtype=wp.float32, requires_grad=requires_grad)
m.tri_materials = wp.array(self.tri_materials, dtype=wp.float32, requires_grad=requires_grad)
# ---------------------
# edges
m.edge_indices = wp.array(self.edge_indices, dtype=wp.int32)
m.edge_rest_angle = wp.array(self.edge_rest_angle, dtype=wp.float32, requires_grad=requires_grad)
m.edge_bending_properties = wp.array(
self.edge_bending_properties, dtype=wp.float32, requires_grad=requires_grad
)
# ---------------------
# tetrahedra
m.tet_indices = wp.array(self.tet_indices, dtype=wp.int32)
m.tet_poses = wp.array(self.tet_poses, dtype=wp.mat33, requires_grad=requires_grad)
m.tet_activations = wp.array(self.tet_activations, dtype=wp.float32, requires_grad=requires_grad)
m.tet_materials = wp.array(self.tet_materials, dtype=wp.float32, requires_grad=requires_grad)
# -----------------------
# muscles
# close the muscle waypoint indices
muscle_start = copy.copy(self.muscle_start)
muscle_start.append(len(self.muscle_bodies))
m.muscle_start = wp.array(muscle_start, dtype=wp.int32)
m.muscle_params = wp.array(self.muscle_params, dtype=wp.float32, requires_grad=requires_grad)
m.muscle_bodies = wp.array(self.muscle_bodies, dtype=wp.int32)
m.muscle_points = wp.array(self.muscle_points, dtype=wp.vec3, requires_grad=requires_grad)
m.muscle_activations = wp.array(self.muscle_activations, dtype=wp.float32, requires_grad=requires_grad)
# --------------------------------------
# rigid bodies
m.body_q = wp.array(self.body_q, dtype=wp.transform, requires_grad=requires_grad)
m.body_qd = wp.array(self.body_qd, dtype=wp.spatial_vector, requires_grad=requires_grad)
m.body_inertia = wp.array(self.body_inertia, dtype=wp.mat33, requires_grad=requires_grad)
m.body_inv_inertia = wp.array(self.body_inv_inertia, dtype=wp.mat33, requires_grad=requires_grad)
m.body_mass = wp.array(self.body_mass, dtype=wp.float32, requires_grad=requires_grad)
m.body_inv_mass = wp.array(self.body_inv_mass, dtype=wp.float32, requires_grad=requires_grad)
m.body_com = wp.array(self.body_com, dtype=wp.vec3, requires_grad=requires_grad)
m.body_name = self.body_name
# joints
m.joint_type = wp.array(self.joint_type, dtype=wp.int32)
m.joint_parent = wp.array(self.joint_parent, dtype=wp.int32)
m.joint_child = wp.array(self.joint_child, dtype=wp.int32)
m.joint_X_p = wp.array(self.joint_X_p, dtype=wp.transform, requires_grad=requires_grad)
m.joint_X_c = wp.array(self.joint_X_c, dtype=wp.transform, requires_grad=requires_grad)
m.joint_axis_start = wp.array(self.joint_axis_start, dtype=wp.int32)
m.joint_axis_dim = wp.array(np.array(self.joint_axis_dim), dtype=wp.int32, ndim=2)
m.joint_axis = wp.array(self.joint_axis, dtype=wp.vec3, requires_grad=requires_grad)
m.joint_q = wp.array(self.joint_q, dtype=wp.float32, requires_grad=requires_grad)
m.joint_qd = wp.array(self.joint_qd, dtype=wp.float32, requires_grad=requires_grad)
m.joint_name = self.joint_name
# dynamics properties
m.joint_armature = wp.array(self.joint_armature, dtype=wp.float32, requires_grad=requires_grad)
m.joint_target_ke = wp.array(self.joint_target_ke, dtype=wp.float32, requires_grad=requires_grad)
m.joint_target_kd = wp.array(self.joint_target_kd, dtype=wp.float32, requires_grad=requires_grad)
m.joint_axis_mode = wp.array(self.joint_axis_mode, dtype=wp.int32)
m.joint_act = wp.array(self.joint_act, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_lower = wp.array(self.joint_limit_lower, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_upper = wp.array(self.joint_limit_upper, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_ke = wp.array(self.joint_limit_ke, dtype=wp.float32, requires_grad=requires_grad)
m.joint_limit_kd = wp.array(self.joint_limit_kd, dtype=wp.float32, requires_grad=requires_grad)
m.joint_linear_compliance = wp.array(
self.joint_linear_compliance, dtype=wp.float32, requires_grad=requires_grad
)
m.joint_angular_compliance = wp.array(
self.joint_angular_compliance, dtype=wp.float32, requires_grad=requires_grad
)
m.joint_enabled = wp.array(self.joint_enabled, dtype=wp.int32)
# 'close' the start index arrays with a sentinel value
joint_q_start = copy.copy(self.joint_q_start)
joint_q_start.append(self.joint_coord_count)
joint_qd_start = copy.copy(self.joint_qd_start)
joint_qd_start.append(self.joint_dof_count)
articulation_start = copy.copy(self.articulation_start)
articulation_start.append(self.joint_count)
m.joint_q_start = wp.array(joint_q_start, dtype=wp.int32)
m.joint_qd_start = wp.array(joint_qd_start, dtype=wp.int32)
m.articulation_start = wp.array(articulation_start, dtype=wp.int32)
# counts
m.joint_count = self.joint_count
m.joint_axis_count = self.joint_axis_count
m.joint_dof_count = self.joint_dof_count
m.joint_coord_count = self.joint_coord_count
m.particle_count = len(self.particle_q)
m.body_count = len(self.body_q)
m.shape_count = len(self.shape_geo_type)
m.tri_count = len(self.tri_poses)
m.tet_count = len(self.tet_poses)
m.edge_count = len(self.edge_rest_angle)
m.spring_count = len(self.spring_rest_length)
m.muscle_count = len(self.muscle_start)
m.articulation_count = len(self.articulation_start)
# contacts
if m.particle_count:
m.allocate_soft_contacts(self.soft_contact_max, requires_grad=requires_grad)
m.find_shape_contact_pairs()
if self.num_rigid_contacts_per_env is None:
contact_count, limited_contact_count = m.count_contact_points()
else:
contact_count = limited_contact_count = self.num_rigid_contacts_per_env * self.num_envs
if contact_count:
if wp.config.verbose:
print(f"Allocating {contact_count} rigid contacts.")
m.allocate_rigid_contacts(
count=contact_count, limited_contact_count=limited_contact_count, requires_grad=requires_grad
)
m.rigid_mesh_contact_max = self.rigid_mesh_contact_max
m.rigid_contact_margin = self.rigid_contact_margin
m.rigid_contact_torsional_friction = self.rigid_contact_torsional_friction
m.rigid_contact_rolling_friction = self.rigid_contact_rolling_friction
# enable ground plane
m.ground_plane = wp.array(self._ground_params["plane"], dtype=wp.float32, requires_grad=requires_grad)
m.gravity = np.array(self.up_vector) * self.gravity
m.enable_tri_collisions = False
return m
| 186,281 | Python | 40.636567 | 260 | 0.585041 |
NVIDIA/warp/warp/sim/integrator_euler.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""This module contains time-integration objects for simulating
models + state forward in time.
"""
import warp as wp
from .collide import triangle_closest_point_barycentric
from .integrator import Integrator
from .model import PARTICLE_FLAG_ACTIVE, Control, Model, ModelShapeGeometry, ModelShapeMaterials, State
from .particles import eval_particle_forces
from .utils import quat_decompose, quat_twist
@wp.kernel
def eval_springs(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
spring_indices: wp.array(dtype=int),
spring_rest_lengths: wp.array(dtype=float),
spring_stiffness: wp.array(dtype=float),
spring_damping: wp.array(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = spring_indices[tid * 2 + 0]
j = spring_indices[tid * 2 + 1]
ke = spring_stiffness[tid]
kd = spring_damping[tid]
rest = spring_rest_lengths[tid]
xi = x[i]
xj = x[j]
vi = v[i]
vj = v[j]
xij = xi - xj
vij = vi - vj
l = wp.length(xij)
l_inv = 1.0 / l
# normalized spring direction
dir = xij * l_inv
c = l - rest
dcdt = wp.dot(dir, vij)
# damping based on relative velocity
fs = dir * (ke * c + kd * dcdt)
wp.atomic_sub(f, i, fs)
wp.atomic_add(f, j, fs)
@wp.kernel
def eval_triangles(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
pose: wp.array(dtype=wp.mat22),
activation: wp.array(dtype=float),
materials: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
k_mu = materials[tid, 0]
k_lambda = materials[tid, 1]
k_damp = materials[tid, 2]
k_drag = materials[tid, 3]
k_lift = materials[tid, 4]
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
x0 = x[i] # point zero
x1 = x[j] # point one
x2 = x[k] # point two
v0 = v[i] # vel zero
v1 = v[j] # vel one
v2 = v[k] # vel two
x10 = x1 - x0 # barycentric coordinates (centered at p)
x20 = x2 - x0
v10 = v1 - v0
v20 = v2 - v0
Dm = pose[tid]
inv_rest_area = wp.determinant(Dm) * 2.0 # 1 / det(A) = det(A^-1)
rest_area = 1.0 / inv_rest_area
# scale stiffness coefficients to account for area
k_mu = k_mu * rest_area
k_lambda = k_lambda * rest_area
k_damp = k_damp * rest_area
# F = Xs*Xm^-1
F1 = x10 * Dm[0, 0] + x20 * Dm[1, 0]
F2 = x10 * Dm[0, 1] + x20 * Dm[1, 1]
# dFdt = Vs*Xm^-1
dFdt1 = v10 * Dm[0, 0] + v20 * Dm[1, 0]
dFdt2 = v10 * Dm[0, 1] + v20 * Dm[1, 1]
# deviatoric PK1 + damping term
P1 = F1 * k_mu + dFdt1 * k_damp
P2 = F2 * k_mu + dFdt2 * k_damp
# -----------------------------
# St. Venant-Kirchoff
# # Green strain, F'*F-I
# e00 = dot(f1, f1) - 1.0
# e10 = dot(f2, f1)
# e01 = dot(f1, f2)
# e11 = dot(f2, f2) - 1.0
# E = wp.mat22(e00, e01,
# e10, e11)
# # local forces (deviatoric part)
# T = wp.mul(E, wp.transpose(Dm))
# # spatial forces, F*T
# fq = (f1*T[0,0] + f2*T[1,0])*k_mu*2.0
# fr = (f1*T[0,1] + f2*T[1,1])*k_mu*2.0
# alpha = 1.0
# -----------------------------
# Baraff & Witkin, note this model is not isotropic
# c1 = length(f1) - 1.0
# c2 = length(f2) - 1.0
# f1 = normalize(f1)*c1*k1
# f2 = normalize(f2)*c2*k1
# fq = f1*Dm[0,0] + f2*Dm[0,1]
# fr = f1*Dm[1,0] + f2*Dm[1,1]
# -----------------------------
# Neo-Hookean (with rest stability)
# force = P*Dm'
f1 = P1 * Dm[0, 0] + P2 * Dm[0, 1]
f2 = P1 * Dm[1, 0] + P2 * Dm[1, 1]
alpha = 1.0 + k_mu / k_lambda
# -----------------------------
# Area Preservation
n = wp.cross(x10, x20)
area = wp.length(n) * 0.5
# actuation
act = activation[tid]
# J-alpha
c = area * inv_rest_area - alpha + act
# dJdx
n = wp.normalize(n)
dcdq = wp.cross(x20, n) * inv_rest_area * 0.5
dcdr = wp.cross(n, x10) * inv_rest_area * 0.5
f_area = k_lambda * c
# -----------------------------
# Area Damping
dcdt = wp.dot(dcdq, v1) + wp.dot(dcdr, v2) - wp.dot(dcdq + dcdr, v0)
f_damp = k_damp * dcdt
f1 = f1 + dcdq * (f_area + f_damp)
f2 = f2 + dcdr * (f_area + f_damp)
f0 = f1 + f2
# -----------------------------
# Lift + Drag
vmid = (v0 + v1 + v2) * 0.3333
vdir = wp.normalize(vmid)
f_drag = vmid * (k_drag * area * wp.abs(wp.dot(n, vmid)))
f_lift = n * (k_lift * area * (wp.HALF_PI - wp.acos(wp.dot(n, vdir)))) * wp.dot(vmid, vmid)
f0 = f0 - f_drag - f_lift
f1 = f1 + f_drag + f_lift
f2 = f2 + f_drag + f_lift
# apply forces
wp.atomic_add(f, i, f0)
wp.atomic_sub(f, j, f1)
wp.atomic_sub(f, k, f2)
# @wp.func
# def triangle_closest_point(a: wp.vec3, b: wp.vec3, c: wp.vec3, p: wp.vec3):
# ab = b - a
# ac = c - a
# ap = p - a
# d1 = wp.dot(ab, ap)
# d2 = wp.dot(ac, ap)
# if (d1 <= 0.0 and d2 <= 0.0):
# return a
# bp = p - b
# d3 = wp.dot(ab, bp)
# d4 = wp.dot(ac, bp)
# if (d3 >= 0.0 and d4 <= d3):
# return b
# vc = d1 * d4 - d3 * d2
# v = d1 / (d1 - d3)
# if (vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0):
# return a + ab * v
# cp = p - c
# d5 = dot(ab, cp)
# d6 = dot(ac, cp)
# if (d6 >= 0.0 and d5 <= d6):
# return c
# vb = d5 * d2 - d1 * d6
# w = d2 / (d2 - d6)
# if (vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0):
# return a + ac * w
# va = d3 * d6 - d5 * d4
# w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
# if (va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0):
# return b + (c - b) * w
# denom = 1.0 / (va + vb + vc)
# v = vb * denom
# w = vc * denom
# return a + ab * v + ac * w
@wp.kernel
def eval_triangles_contact(
# idx : wp.array(dtype=int), # list of indices for colliding particles
num_particles: int, # size of particles
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
materials: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
face_no = tid // num_particles # which face
particle_no = tid % num_particles # which particle
# k_mu = materials[face_no, 0]
# k_lambda = materials[face_no, 1]
# k_damp = materials[face_no, 2]
# k_drag = materials[face_no, 3]
# k_lift = materials[face_no, 4]
# at the moment, just one particle
pos = x[particle_no]
i = indices[face_no, 0]
j = indices[face_no, 1]
k = indices[face_no, 2]
if i == particle_no or j == particle_no or k == particle_no:
return
p = x[i] # point zero
q = x[j] # point one
r = x[k] # point two
# vp = v[i] # vel zero
# vq = v[j] # vel one
# vr = v[k] # vel two
# qp = q-p # barycentric coordinates (centered at p)
# rp = r-p
bary = triangle_closest_point_barycentric(p, q, r, pos)
closest = p * bary[0] + q * bary[1] + r * bary[2]
diff = pos - closest
dist = wp.dot(diff, diff)
n = wp.normalize(diff)
c = wp.min(dist - 0.01, 0.0) # 0 unless within 0.01 of surface
# c = wp.leaky_min(dot(n, x0)-0.01, 0.0, 0.0)
fn = n * c * 1e5
wp.atomic_sub(f, particle_no, fn)
# # apply forces (could do - f / 3 here)
wp.atomic_add(f, i, fn * bary[0])
wp.atomic_add(f, j, fn * bary[1])
wp.atomic_add(f, k, fn * bary[2])
@wp.kernel
def eval_triangles_body_contacts(
num_particles: int, # number of particles (size of contact_point)
x: wp.array(dtype=wp.vec3), # position of particles
v: wp.array(dtype=wp.vec3),
indices: wp.array(dtype=int), # triangle indices
body_x: wp.array(dtype=wp.vec3), # body body positions
body_r: wp.array(dtype=wp.quat),
body_v: wp.array(dtype=wp.vec3),
body_w: wp.array(dtype=wp.vec3),
contact_body: wp.array(dtype=int),
contact_point: wp.array(dtype=wp.vec3), # position of contact points relative to body
contact_dist: wp.array(dtype=float),
contact_mat: wp.array(dtype=int),
materials: wp.array(dtype=float),
# body_f : wp.array(dtype=wp.vec3),
# body_t : wp.array(dtype=wp.vec3),
tri_f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
face_no = tid // num_particles # which face
particle_no = tid % num_particles # which particle
# -----------------------
# load body body point
c_body = contact_body[particle_no]
c_point = contact_point[particle_no]
c_dist = contact_dist[particle_no]
c_mat = contact_mat[particle_no]
# hard coded surface parameter tensor layout (ke, kd, kf, mu)
ke = materials[c_mat * 4 + 0] # restitution coefficient
kd = materials[c_mat * 4 + 1] # damping coefficient
kf = materials[c_mat * 4 + 2] # friction coefficient
mu = materials[c_mat * 4 + 3] # coulomb friction
x0 = body_x[c_body] # position of colliding body
r0 = body_r[c_body] # orientation of colliding body
v0 = body_v[c_body]
w0 = body_w[c_body]
# transform point to world space
pos = x0 + wp.quat_rotate(r0, c_point)
# use x0 as center, everything is offset from center of mass
# moment arm
r = pos - x0 # basically just c_point in the new coordinates
rhat = wp.normalize(r)
pos = pos + rhat * c_dist # add on 'thickness' of shape, e.g.: radius of sphere/capsule
# contact point velocity
dpdt = v0 + wp.cross(w0, r) # this is body velocity cross offset, so it's the velocity of the contact point.
# -----------------------
# load triangle
i = indices[face_no * 3 + 0]
j = indices[face_no * 3 + 1]
k = indices[face_no * 3 + 2]
p = x[i] # point zero
q = x[j] # point one
r = x[k] # point two
vp = v[i] # vel zero
vq = v[j] # vel one
vr = v[k] # vel two
bary = triangle_closest_point_barycentric(p, q, r, pos)
closest = p * bary[0] + q * bary[1] + r * bary[2]
diff = pos - closest # vector from tri to point
dist = wp.dot(diff, diff) # squared distance
n = wp.normalize(diff) # points into the object
c = wp.min(dist - 0.05, 0.0) # 0 unless within 0.05 of surface
# c = wp.leaky_min(wp.dot(n, x0)-0.01, 0.0, 0.0)
# fn = n * c * 1e6 # points towards cloth (both n and c are negative)
# wp.atomic_sub(tri_f, particle_no, fn)
fn = c * ke # normal force (restitution coefficient * how far inside for ground) (negative)
vtri = vp * bary[0] + vq * bary[1] + vr * bary[2] # bad approximation for centroid velocity
vrel = vtri - dpdt
vn = wp.dot(n, vrel) # velocity component of body in negative normal direction
vt = vrel - n * vn # velocity component not in normal direction
# contact damping
fd = -wp.max(vn, 0.0) * kd * wp.step(c) # again, negative, into the ground
# # viscous friction
# ft = vt*kf
# Coulomb friction (box)
lower = mu * (fn + fd)
upper = -lower
nx = wp.cross(n, wp.vec3(0.0, 0.0, 1.0)) # basis vectors for tangent
nz = wp.cross(n, wp.vec3(1.0, 0.0, 0.0))
vx = wp.clamp(wp.dot(nx * kf, vt), lower, upper)
vz = wp.clamp(wp.dot(nz * kf, vt), lower, upper)
ft = (nx * vx + nz * vz) * (-wp.step(c)) # wp.vec3(vx, 0.0, vz)*wp.step(c)
# # Coulomb friction (smooth, but gradients are numerically unstable around |vt| = 0)
# #ft = wp.normalize(vt)*wp.min(kf*wp.length(vt), -mu*c*ke)
f_total = n * (fn + fd) + ft
wp.atomic_add(tri_f, i, f_total * bary[0])
wp.atomic_add(tri_f, j, f_total * bary[1])
wp.atomic_add(tri_f, k, f_total * bary[2])
@wp.kernel
def eval_bending(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
rest: wp.array(dtype=float),
bending_properties: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
ke = bending_properties[tid, 0]
kd = bending_properties[tid, 1]
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
rest_angle = rest[tid]
x1 = x[i]
x2 = x[j]
x3 = x[k]
x4 = x[l]
v1 = v[i]
v2 = v[j]
v3 = v[k]
v4 = v[l]
n1 = wp.cross(x3 - x1, x4 - x1) # normal to face 1
n2 = wp.cross(x4 - x2, x3 - x2) # normal to face 2
n1_length = wp.length(n1)
n2_length = wp.length(n2)
if n1_length < 1.0e-6 or n2_length < 1.0e-6:
return
rcp_n1 = 1.0 / n1_length
rcp_n2 = 1.0 / n2_length
cos_theta = wp.dot(n1, n2) * rcp_n1 * rcp_n2
n1 = n1 * rcp_n1 * rcp_n1
n2 = n2 * rcp_n2 * rcp_n2
e = x4 - x3
e_hat = wp.normalize(e)
e_length = wp.length(e)
s = wp.sign(wp.dot(wp.cross(n2, n1), e_hat))
angle = wp.acos(cos_theta) * s
d1 = n1 * e_length
d2 = n2 * e_length
d3 = n1 * wp.dot(x1 - x4, e_hat) + n2 * wp.dot(x2 - x4, e_hat)
d4 = n1 * wp.dot(x3 - x1, e_hat) + n2 * wp.dot(x3 - x2, e_hat)
# elastic
f_elastic = ke * (angle - rest_angle)
# damping
f_damp = kd * (wp.dot(d1, v1) + wp.dot(d2, v2) + wp.dot(d3, v3) + wp.dot(d4, v4))
# total force, proportional to edge length
f_total = -e_length * (f_elastic + f_damp)
wp.atomic_add(f, i, d1 * f_total)
wp.atomic_add(f, j, d2 * f_total)
wp.atomic_add(f, k, d3 * f_total)
wp.atomic_add(f, l, d4 * f_total)
@wp.kernel
def eval_tetrahedra(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
indices: wp.array2d(dtype=int),
pose: wp.array(dtype=wp.mat33),
activation: wp.array(dtype=float),
materials: wp.array2d(dtype=float),
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
i = indices[tid, 0]
j = indices[tid, 1]
k = indices[tid, 2]
l = indices[tid, 3]
act = activation[tid]
k_mu = materials[tid, 0]
k_lambda = materials[tid, 1]
k_damp = materials[tid, 2]
x0 = x[i]
x1 = x[j]
x2 = x[k]
x3 = x[l]
v0 = v[i]
v1 = v[j]
v2 = v[k]
v3 = v[l]
x10 = x1 - x0
x20 = x2 - x0
x30 = x3 - x0
v10 = v1 - v0
v20 = v2 - v0
v30 = v3 - v0
Ds = wp.mat33(x10, x20, x30)
Dm = pose[tid]
inv_rest_volume = wp.determinant(Dm) * 6.0
rest_volume = 1.0 / inv_rest_volume
alpha = 1.0 + k_mu / k_lambda - k_mu / (4.0 * k_lambda)
# scale stiffness coefficients to account for area
k_mu = k_mu * rest_volume
k_lambda = k_lambda * rest_volume
k_damp = k_damp * rest_volume
# F = Xs*Xm^-1
F = Ds * Dm
dFdt = wp.mat33(v10, v20, v30) * Dm
col1 = wp.vec3(F[0, 0], F[1, 0], F[2, 0])
col2 = wp.vec3(F[0, 1], F[1, 1], F[2, 1])
col3 = wp.vec3(F[0, 2], F[1, 2], F[2, 2])
# -----------------------------
# Neo-Hookean (with rest stability [Smith et al 2018])
Ic = wp.dot(col1, col1) + wp.dot(col2, col2) + wp.dot(col3, col3)
# deviatoric part
P = F * k_mu * (1.0 - 1.0 / (Ic + 1.0)) + dFdt * k_damp
H = P * wp.transpose(Dm)
f1 = wp.vec3(H[0, 0], H[1, 0], H[2, 0])
f2 = wp.vec3(H[0, 1], H[1, 1], H[2, 1])
f3 = wp.vec3(H[0, 2], H[1, 2], H[2, 2])
# -----------------------------
# C_sqrt
# alpha = 1.0
# r_s = wp.sqrt(wp.abs(dot(col1, col1) + dot(col2, col2) + dot(col3, col3) - 3.0))
# f1 = wp.vec3()
# f2 = wp.vec3()
# f3 = wp.vec3()
# if (r_s > 0.0):
# r_s_inv = 1.0/r_s
# C = r_s
# dCdx = F*wp.transpose(Dm)*r_s_inv*wp.sign(r_s)
# grad1 = vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# f1 = grad1*C*k_mu
# f2 = grad2*C*k_mu
# f3 = grad3*C*k_mu
# -----------------------------
# C_spherical
# alpha = 1.0
# r_s = wp.sqrt(dot(col1, col1) + dot(col2, col2) + dot(col3, col3))
# r_s_inv = 1.0/r_s
# C = r_s - wp.sqrt(3.0)
# dCdx = F*wp.transpose(Dm)*r_s_inv
# grad1 = vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# f1 = grad1*C*k_mu
# f2 = grad2*C*k_mu
# f3 = grad3*C*k_mu
# ----------------------------
# C_D
# alpha = 1.0
# r_s = wp.sqrt(dot(col1, col1) + dot(col2, col2) + dot(col3, col3))
# C = r_s*r_s - 3.0
# dCdx = F*wp.transpose(Dm)*2.0
# grad1 = vec3(dCdx[0,0], dCdx[1,0], dCdx[2,0])
# grad2 = vec3(dCdx[0,1], dCdx[1,1], dCdx[2,1])
# grad3 = vec3(dCdx[0,2], dCdx[1,2], dCdx[2,2])
# f1 = grad1*C*k_mu
# f2 = grad2*C*k_mu
# f3 = grad3*C*k_mu
# ----------------------------
# Hookean
# alpha = 1.0
# I = wp.mat33(wp.vec3(1.0, 0.0, 0.0),
# wp.vec3(0.0, 1.0, 0.0),
# wp.vec3(0.0, 0.0, 1.0))
# P = (F + wp.transpose(F) + I*(0.0-2.0))*k_mu
# H = P * wp.transpose(Dm)
# f1 = wp.vec3(H[0, 0], H[1, 0], H[2, 0])
# f2 = wp.vec3(H[0, 1], H[1, 1], H[2, 1])
# f3 = wp.vec3(H[0, 2], H[1, 2], H[2, 2])
# hydrostatic part
J = wp.determinant(F)
# print(J)
s = inv_rest_volume / 6.0
dJdx1 = wp.cross(x20, x30) * s
dJdx2 = wp.cross(x30, x10) * s
dJdx3 = wp.cross(x10, x20) * s
f_volume = (J - alpha + act) * k_lambda
f_damp = (wp.dot(dJdx1, v1) + wp.dot(dJdx2, v2) + wp.dot(dJdx3, v3)) * k_damp
f_total = f_volume + f_damp
f1 = f1 + dJdx1 * f_total
f2 = f2 + dJdx2 * f_total
f3 = f3 + dJdx3 * f_total
f0 = -(f1 + f2 + f3)
# apply forces
wp.atomic_sub(f, i, f0)
wp.atomic_sub(f, j, f1)
wp.atomic_sub(f, k, f2)
wp.atomic_sub(f, l, f3)
@wp.kernel
def eval_particle_ground_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
ke: float,
kd: float,
kf: float,
mu: float,
ground: wp.array(dtype=float),
# outputs
f: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
x = particle_x[tid]
v = particle_v[tid]
radius = particle_radius[tid]
n = wp.vec3(ground[0], ground[1], ground[2])
c = wp.min(wp.dot(n, x) + ground[3] - radius, 0.0)
vn = wp.dot(n, v)
jn = c * ke
if c >= 0.0:
return
jd = min(vn, 0.0) * kd
# contact force
fn = jn + jd
# friction force
vt = v - n * vn
vs = wp.length(vt)
if vs > 0.0:
vt = vt / vs
# Coulomb condition
ft = wp.min(vs * kf, mu * wp.abs(fn))
# total force
f[tid] = f[tid] - n * fn - vt * ft
@wp.kernel
def eval_particle_contacts(
particle_x: wp.array(dtype=wp.vec3),
particle_v: wp.array(dtype=wp.vec3),
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
particle_radius: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
body_com: wp.array(dtype=wp.vec3),
shape_body: wp.array(dtype=int),
shape_materials: ModelShapeMaterials,
particle_ke: float,
particle_kd: float,
particle_kf: float,
particle_mu: float,
particle_ka: float,
contact_count: wp.array(dtype=int),
contact_particle: wp.array(dtype=int),
contact_shape: wp.array(dtype=int),
contact_body_pos: wp.array(dtype=wp.vec3),
contact_body_vel: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_max: int,
# outputs
particle_f: wp.array(dtype=wp.vec3),
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
count = min(contact_max, contact_count[0])
if tid >= count:
return
shape_index = contact_shape[tid]
body_index = shape_body[shape_index]
particle_index = contact_particle[tid]
if (particle_flags[particle_index] & PARTICLE_FLAG_ACTIVE) == 0:
return
px = particle_x[particle_index]
pv = particle_v[particle_index]
X_wb = wp.transform_identity()
X_com = wp.vec3()
body_v_s = wp.spatial_vector()
if body_index >= 0:
X_wb = body_q[body_index]
X_com = body_com[body_index]
body_v_s = body_qd[body_index]
# body position in world space
bx = wp.transform_point(X_wb, contact_body_pos[tid])
r = bx - wp.transform_point(X_wb, X_com)
n = contact_normal[tid]
c = wp.dot(n, px - bx) - particle_radius[tid]
if c > particle_ka:
return
# take average material properties of shape and particle parameters
ke = 0.5 * (particle_ke + shape_materials.ke[shape_index])
kd = 0.5 * (particle_kd + shape_materials.kd[shape_index])
kf = 0.5 * (particle_kf + shape_materials.kf[shape_index])
mu = 0.5 * (particle_mu + shape_materials.mu[shape_index])
body_w = wp.spatial_top(body_v_s)
body_v = wp.spatial_bottom(body_v_s)
# compute the body velocity at the particle position
bv = body_v + wp.cross(body_w, r) + wp.transform_vector(X_wb, contact_body_vel[tid])
# relative velocity
v = pv - bv
# decompose relative velocity
vn = wp.dot(n, v)
vt = v - n * vn
# contact elastic
fn = n * c * ke
# contact damping
fd = n * wp.min(vn, 0.0) * kd
# viscous friction
# ft = vt*kf
# Coulomb friction (box)
# lower = mu * c * ke
# upper = -lower
# vx = wp.clamp(wp.dot(wp.vec3(kf, 0.0, 0.0), vt), lower, upper)
# vz = wp.clamp(wp.dot(wp.vec3(0.0, 0.0, kf), vt), lower, upper)
# ft = wp.vec3(vx, 0.0, vz)
# Coulomb friction (smooth, but gradients are numerically unstable around |vt| = 0)
ft = wp.normalize(vt) * wp.min(kf * wp.length(vt), abs(mu * c * ke))
f_total = fn + (fd + ft)
t_total = wp.cross(r, f_total)
wp.atomic_sub(particle_f, particle_index, f_total)
if body_index >= 0:
wp.atomic_add(body_f, body_index, wp.spatial_vector(t_total, f_total))
@wp.kernel
def eval_rigid_contacts(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
shape_materials: ModelShapeMaterials,
geo: ModelShapeGeometry,
shape_body: wp.array(dtype=int),
contact_count: wp.array(dtype=int),
contact_point0: wp.array(dtype=wp.vec3),
contact_point1: wp.array(dtype=wp.vec3),
contact_normal: wp.array(dtype=wp.vec3),
contact_shape0: wp.array(dtype=int),
contact_shape1: wp.array(dtype=int),
force_in_world_frame: bool,
# outputs
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
count = contact_count[0]
if tid >= count:
return
# retrieve contact thickness, compute average contact material properties
ke = 0.0 # contact normal force stiffness
kd = 0.0 # damping coefficient
kf = 0.0 # friction force stiffness
ka = 0.0 # adhesion distance
mu = 0.0 # friction coefficient
mat_nonzero = 0
thickness_a = 0.0
thickness_b = 0.0
shape_a = contact_shape0[tid]
shape_b = contact_shape1[tid]
if shape_a == shape_b:
return
body_a = -1
body_b = -1
if shape_a >= 0:
mat_nonzero += 1
ke += shape_materials.ke[shape_a]
kd += shape_materials.kd[shape_a]
kf += shape_materials.kf[shape_a]
ka += shape_materials.ka[shape_a]
mu += shape_materials.mu[shape_a]
thickness_a = geo.thickness[shape_a]
body_a = shape_body[shape_a]
if shape_b >= 0:
mat_nonzero += 1
ke += shape_materials.ke[shape_b]
kd += shape_materials.kd[shape_b]
kf += shape_materials.kf[shape_b]
ka += shape_materials.ka[shape_b]
mu += shape_materials.mu[shape_b]
thickness_b = geo.thickness[shape_b]
body_b = shape_body[shape_b]
if mat_nonzero > 0:
ke /= float(mat_nonzero)
kd /= float(mat_nonzero)
kf /= float(mat_nonzero)
ka /= float(mat_nonzero)
mu /= float(mat_nonzero)
# contact normal in world space
n = contact_normal[tid]
bx_a = contact_point0[tid]
bx_b = contact_point1[tid]
if body_a >= 0:
X_wb_a = body_q[body_a]
X_com_a = body_com[body_a]
bx_a = wp.transform_point(X_wb_a, bx_a) - thickness_a * n
r_a = bx_a - wp.transform_point(X_wb_a, X_com_a)
if body_b >= 0:
X_wb_b = body_q[body_b]
X_com_b = body_com[body_b]
bx_b = wp.transform_point(X_wb_b, bx_b) + thickness_b * n
r_b = bx_b - wp.transform_point(X_wb_b, X_com_b)
d = wp.dot(n, bx_a - bx_b)
if d >= ka:
return
# compute contact point velocity
bv_a = wp.vec3(0.0)
bv_b = wp.vec3(0.0)
if body_a >= 0:
body_v_s_a = body_qd[body_a]
body_w_a = wp.spatial_top(body_v_s_a)
body_v_a = wp.spatial_bottom(body_v_s_a)
if force_in_world_frame:
bv_a = body_v_a + wp.cross(body_w_a, bx_a)
else:
bv_a = body_v_a + wp.cross(body_w_a, r_a)
if body_b >= 0:
body_v_s_b = body_qd[body_b]
body_w_b = wp.spatial_top(body_v_s_b)
body_v_b = wp.spatial_bottom(body_v_s_b)
if force_in_world_frame:
bv_b = body_v_b + wp.cross(body_w_b, bx_b)
else:
bv_b = body_v_b + wp.cross(body_w_b, r_b)
# relative velocity
v = bv_a - bv_b
# print(v)
# decompose relative velocity
vn = wp.dot(n, v)
vt = v - n * vn
# contact elastic
fn = d * ke
# contact damping
fd = wp.min(vn, 0.0) * kd * wp.step(d)
# viscous friction
# ft = vt*kf
# Coulomb friction (box)
# lower = mu * d * ke
# upper = -lower
# vx = wp.clamp(wp.dot(wp.vec3(kf, 0.0, 0.0), vt), lower, upper)
# vz = wp.clamp(wp.dot(wp.vec3(0.0, 0.0, kf), vt), lower, upper)
# ft = wp.vec3(vx, 0.0, vz)
# Coulomb friction (smooth, but gradients are numerically unstable around |vt| = 0)
# ft = wp.normalize(vt)*wp.min(kf*wp.length(vt), abs(mu*d*ke))
ft = wp.vec3(0.0)
if d < 0.0:
ft = wp.normalize(vt) * wp.min(kf * wp.length(vt), -mu * (fn + fd))
f_total = n * (fn + fd) + ft
# f_total = n * fn
if body_a >= 0:
if force_in_world_frame:
wp.atomic_add(body_f, body_a, wp.spatial_vector(wp.cross(bx_a, f_total), f_total))
else:
wp.atomic_sub(body_f, body_a, wp.spatial_vector(wp.cross(r_a, f_total), f_total))
if body_b >= 0:
if force_in_world_frame:
wp.atomic_sub(body_f, body_b, wp.spatial_vector(wp.cross(bx_b, f_total), f_total))
else:
wp.atomic_add(body_f, body_b, wp.spatial_vector(wp.cross(r_b, f_total), f_total))
@wp.func
def eval_joint_force(
q: float,
qd: float,
act: float,
target_ke: float,
target_kd: float,
limit_lower: float,
limit_upper: float,
limit_ke: float,
limit_kd: float,
mode: wp.int32,
) -> float:
"""Joint force evaluation for a single degree of freedom."""
limit_f = 0.0
damping_f = 0.0
target_f = 0.0
if mode == wp.sim.JOINT_MODE_FORCE:
target_f = act
elif mode == wp.sim.JOINT_MODE_TARGET_POSITION:
target_f = target_ke * (act - q) - target_kd * qd
elif mode == wp.sim.JOINT_MODE_TARGET_VELOCITY:
target_f = target_ke * (act - qd)
# compute limit forces, damping only active when limit is violated
if q < limit_lower:
limit_f = limit_ke * (limit_lower - q)
damping_f = -limit_kd * qd
if mode == wp.sim.JOINT_MODE_TARGET_VELOCITY:
target_f = 0.0 # override target force when limit is violated
elif q > limit_upper:
limit_f = limit_ke * (limit_upper - q)
damping_f = -limit_kd * qd
if mode == wp.sim.JOINT_MODE_TARGET_VELOCITY:
target_f = 0.0 # override target force when limit is violated
return limit_f + damping_f + target_f
@wp.kernel
def eval_body_joints(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
joint_qd_start: wp.array(dtype=int),
joint_type: wp.array(dtype=int),
joint_enabled: wp.array(dtype=int),
joint_child: wp.array(dtype=int),
joint_parent: wp.array(dtype=int),
joint_X_p: wp.array(dtype=wp.transform),
joint_X_c: wp.array(dtype=wp.transform),
joint_axis: wp.array(dtype=wp.vec3),
joint_axis_start: wp.array(dtype=int),
joint_axis_dim: wp.array(dtype=int, ndim=2),
joint_axis_mode: wp.array(dtype=int),
joint_act: wp.array(dtype=float),
joint_target_ke: wp.array(dtype=float),
joint_target_kd: wp.array(dtype=float),
joint_limit_lower: wp.array(dtype=float),
joint_limit_upper: wp.array(dtype=float),
joint_limit_ke: wp.array(dtype=float),
joint_limit_kd: wp.array(dtype=float),
joint_attach_ke: float,
joint_attach_kd: float,
body_f: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
type = joint_type[tid]
# early out for free joints
if joint_enabled[tid] == 0 or type == wp.sim.JOINT_FREE:
return
c_child = joint_child[tid]
c_parent = joint_parent[tid]
X_pj = joint_X_p[tid]
X_cj = joint_X_c[tid]
X_wp = X_pj
r_p = wp.vec3()
w_p = wp.vec3()
v_p = wp.vec3()
# parent transform and moment arm
if c_parent >= 0:
X_wp = body_q[c_parent] * X_wp
r_p = wp.transform_get_translation(X_wp) - wp.transform_point(body_q[c_parent], body_com[c_parent])
twist_p = body_qd[c_parent]
w_p = wp.spatial_top(twist_p)
v_p = wp.spatial_bottom(twist_p) + wp.cross(w_p, r_p)
# child transform and moment arm
X_wc = body_q[c_child] * X_cj
r_c = wp.transform_get_translation(X_wc) - wp.transform_point(body_q[c_child], body_com[c_child])
twist_c = body_qd[c_child]
w_c = wp.spatial_top(twist_c)
v_c = wp.spatial_bottom(twist_c) + wp.cross(w_c, r_c)
# joint properties (for 1D joints)
# q_start = joint_q_start[tid]
# qd_start = joint_qd_start[tid]
axis_start = joint_axis_start[tid]
lin_axis_count = joint_axis_dim[tid, 0]
ang_axis_count = joint_axis_dim[tid, 1]
x_p = wp.transform_get_translation(X_wp)
x_c = wp.transform_get_translation(X_wc)
q_p = wp.transform_get_rotation(X_wp)
q_c = wp.transform_get_rotation(X_wc)
# translational error
x_err = x_c - x_p
r_err = wp.quat_inverse(q_p) * q_c
v_err = v_c - v_p
w_err = w_c - w_p
# total force/torque on the parent
t_total = wp.vec3()
f_total = wp.vec3()
# reduce angular damping stiffness for stability
angular_damping_scale = 0.01
if type == wp.sim.JOINT_FIXED:
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
t_total += (
wp.transform_vector(X_wp, ang_err) * joint_attach_ke + w_err * joint_attach_kd * angular_damping_scale
)
if type == wp.sim.JOINT_PRISMATIC:
axis = joint_axis[axis_start]
# world space joint axis
axis_p = wp.transform_vector(X_wp, axis)
# evaluate joint coordinates
q = wp.dot(x_err, axis_p)
qd = wp.dot(v_err, axis_p)
act = joint_act[axis_start]
f_total = axis_p * -eval_joint_force(
q,
qd,
act,
joint_target_ke[axis_start],
joint_target_kd[axis_start],
joint_limit_lower[axis_start],
joint_limit_upper[axis_start],
joint_limit_ke[axis_start],
joint_limit_kd[axis_start],
joint_axis_mode[axis_start],
)
# attachment dynamics
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
# project off any displacement along the joint axis
f_total += (x_err - q * axis_p) * joint_attach_ke + (v_err - qd * axis_p) * joint_attach_kd
t_total += (
wp.transform_vector(X_wp, ang_err) * joint_attach_ke + w_err * joint_attach_kd * angular_damping_scale
)
if type == wp.sim.JOINT_REVOLUTE:
axis = joint_axis[axis_start]
axis_p = wp.transform_vector(X_wp, axis)
axis_c = wp.transform_vector(X_wc, axis)
# swing twist decomposition
twist = quat_twist(axis, r_err)
q = wp.acos(twist[3]) * 2.0 * wp.sign(wp.dot(axis, wp.vec3(twist[0], twist[1], twist[2])))
qd = wp.dot(w_err, axis_p)
act = joint_act[axis_start]
t_total = axis_p * -eval_joint_force(
q,
qd,
act,
joint_target_ke[axis_start],
joint_target_kd[axis_start],
joint_limit_lower[axis_start],
joint_limit_upper[axis_start],
joint_limit_ke[axis_start],
joint_limit_kd[axis_start],
joint_axis_mode[axis_start],
)
# attachment dynamics
swing_err = wp.cross(axis_p, axis_c)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
t_total += swing_err * joint_attach_ke + (w_err - qd * axis_p) * joint_attach_kd * angular_damping_scale
if type == wp.sim.JOINT_BALL:
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
# TODO joint limits
# TODO expose target_kd or target_ke for ball joints
# t_total += target_kd * w_err + target_ke * wp.transform_vector(X_wp, ang_err)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
if type == wp.sim.JOINT_COMPOUND:
q_pc = wp.quat_inverse(q_p) * q_c
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# reconstruct rotation axes
axis_0 = wp.vec3(1.0, 0.0, 0.0)
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, wp.vec3(0.0, 0.0, 1.0))
# q_2 = wp.quat_from_axis_angle(axis_2, angles[2])
# q_w = q_p
axis_0 = wp.transform_vector(X_wp, axis_0)
axis_1 = wp.transform_vector(X_wp, axis_1)
axis_2 = wp.transform_vector(X_wp, axis_2)
# joint dynamics
# # TODO remove wp.quat_rotate(q_w, ...)?
# t_total += eval_joint_force(angles[0], wp.dot(wp.quat_rotate(q_w, axis_0), w_err), joint_target[axis_start+0], joint_target_ke[axis_start+0],joint_target_kd[axis_start+0], joint_act[axis_start+0], joint_limit_lower[axis_start+0], joint_limit_upper[axis_start+0], joint_limit_ke[axis_start+0], joint_limit_kd[axis_start+0], wp.quat_rotate(q_w, axis_0))
# t_total += eval_joint_force(angles[1], wp.dot(wp.quat_rotate(q_w, axis_1), w_err), joint_target[axis_start+1], joint_target_ke[axis_start+1],joint_target_kd[axis_start+1], joint_act[axis_start+1], joint_limit_lower[axis_start+1], joint_limit_upper[axis_start+1], joint_limit_ke[axis_start+1], joint_limit_kd[axis_start+1], wp.quat_rotate(q_w, axis_1))
# t_total += eval_joint_force(angles[2], wp.dot(wp.quat_rotate(q_w, axis_2), w_err), joint_target[axis_start+2], joint_target_ke[axis_start+2],joint_target_kd[axis_start+2], joint_act[axis_start+2], joint_limit_lower[axis_start+2], joint_limit_upper[axis_start+2], joint_limit_ke[axis_start+2], joint_limit_kd[axis_start+2], wp.quat_rotate(q_w, axis_2))
t_total += axis_0 * -eval_joint_force(
angles[0],
wp.dot(axis_0, w_err),
joint_act[axis_start + 0],
joint_target_ke[axis_start + 0],
joint_target_kd[axis_start + 0],
joint_limit_lower[axis_start + 0],
joint_limit_upper[axis_start + 0],
joint_limit_ke[axis_start + 0],
joint_limit_kd[axis_start + 0],
joint_axis_mode[axis_start + 0],
)
t_total += axis_1 * -eval_joint_force(
angles[1],
wp.dot(axis_1, w_err),
joint_act[axis_start + 1],
joint_target_ke[axis_start + 1],
joint_target_kd[axis_start + 1],
joint_limit_lower[axis_start + 1],
joint_limit_upper[axis_start + 1],
joint_limit_ke[axis_start + 1],
joint_limit_kd[axis_start + 1],
joint_axis_mode[axis_start + 1],
)
t_total += axis_2 * -eval_joint_force(
angles[2],
wp.dot(axis_2, w_err),
joint_act[axis_start + 2],
joint_target_ke[axis_start + 2],
joint_target_kd[axis_start + 2],
joint_limit_lower[axis_start + 2],
joint_limit_upper[axis_start + 2],
joint_limit_ke[axis_start + 2],
joint_limit_kd[axis_start + 2],
joint_axis_mode[axis_start + 2],
)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
if type == wp.sim.JOINT_UNIVERSAL:
q_pc = wp.quat_inverse(q_p) * q_c
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
# reconstruct rotation axes
axis_0 = wp.vec3(1.0, 0.0, 0.0)
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, wp.vec3(0.0, 1.0, 0.0))
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, wp.vec3(0.0, 0.0, 1.0))
axis_0 = wp.transform_vector(X_wp, axis_0)
axis_1 = wp.transform_vector(X_wp, axis_1)
axis_2 = wp.transform_vector(X_wp, axis_2)
# joint dynamics
t_total += axis_0 * -eval_joint_force(
angles[0],
wp.dot(axis_0, w_err),
joint_act[axis_start + 0],
joint_target_ke[axis_start + 0],
joint_target_kd[axis_start + 0],
joint_limit_lower[axis_start + 0],
joint_limit_upper[axis_start + 0],
joint_limit_ke[axis_start + 0],
joint_limit_kd[axis_start + 0],
joint_axis_mode[axis_start + 0],
)
t_total += axis_1 * -eval_joint_force(
angles[1],
wp.dot(axis_1, w_err),
joint_act[axis_start + 1],
joint_target_ke[axis_start + 1],
joint_target_kd[axis_start + 1],
joint_limit_lower[axis_start + 1],
joint_limit_upper[axis_start + 1],
joint_limit_ke[axis_start + 1],
joint_limit_kd[axis_start + 1],
joint_axis_mode[axis_start + 1],
)
# last axis (fixed)
t_total += axis_2 * -eval_joint_force(
angles[2],
wp.dot(axis_2, w_err),
0.0,
joint_attach_ke,
joint_attach_kd * angular_damping_scale,
0.0,
0.0,
0.0,
0.0,
wp.sim.JOINT_MODE_FORCE,
)
f_total += x_err * joint_attach_ke + v_err * joint_attach_kd
if type == wp.sim.JOINT_D6:
pos = wp.vec3(0.0)
vel = wp.vec3(0.0)
if lin_axis_count >= 1:
axis_0 = wp.transform_vector(X_wp, joint_axis[axis_start + 0])
q0 = wp.dot(x_err, axis_0)
qd0 = wp.dot(v_err, axis_0)
f_total += axis_0 * -eval_joint_force(
q0,
qd0,
joint_act[axis_start + 0],
joint_target_ke[axis_start + 0],
joint_target_kd[axis_start + 0],
joint_limit_lower[axis_start + 0],
joint_limit_upper[axis_start + 0],
joint_limit_ke[axis_start + 0],
joint_limit_kd[axis_start + 0],
joint_axis_mode[axis_start + 0],
)
pos += q0 * axis_0
vel += qd0 * axis_0
if lin_axis_count >= 2:
axis_1 = wp.transform_vector(X_wp, joint_axis[axis_start + 1])
q1 = wp.dot(x_err, axis_1)
qd1 = wp.dot(v_err, axis_1)
f_total += axis_1 * -eval_joint_force(
q1,
qd1,
joint_act[axis_start + 1],
joint_target_ke[axis_start + 1],
joint_target_kd[axis_start + 1],
joint_limit_lower[axis_start + 1],
joint_limit_upper[axis_start + 1],
joint_limit_ke[axis_start + 1],
joint_limit_kd[axis_start + 1],
joint_axis_mode[axis_start + 1],
)
pos += q1 * axis_1
vel += qd1 * axis_1
if lin_axis_count == 3:
axis_2 = wp.transform_vector(X_wp, joint_axis[axis_start + 2])
q2 = wp.dot(x_err, axis_2)
qd2 = wp.dot(v_err, axis_2)
f_total += axis_2 * -eval_joint_force(
q2,
qd2,
joint_act[axis_start + 2],
joint_target_ke[axis_start + 2],
joint_target_kd[axis_start + 2],
joint_limit_lower[axis_start + 2],
joint_limit_upper[axis_start + 2],
joint_limit_ke[axis_start + 2],
joint_limit_kd[axis_start + 2],
joint_axis_mode[axis_start + 2],
)
pos += q2 * axis_2
vel += qd2 * axis_2
f_total += (x_err - pos) * joint_attach_ke + (v_err - vel) * joint_attach_kd
if ang_axis_count == 0:
ang_err = wp.normalize(wp.vec3(r_err[0], r_err[1], r_err[2])) * wp.acos(r_err[3]) * 2.0
t_total += (
wp.transform_vector(X_wp, ang_err) * joint_attach_ke + w_err * joint_attach_kd * angular_damping_scale
)
i_0 = lin_axis_count + axis_start + 0
i_1 = lin_axis_count + axis_start + 1
i_2 = lin_axis_count + axis_start + 2
if ang_axis_count == 1:
axis = joint_axis[i_0]
axis_p = wp.transform_vector(X_wp, axis)
axis_c = wp.transform_vector(X_wc, axis)
# swing twist decomposition
twist = quat_twist(axis, r_err)
q = wp.acos(twist[3]) * 2.0 * wp.sign(wp.dot(axis, wp.vec3(twist[0], twist[1], twist[2])))
qd = wp.dot(w_err, axis_p)
t_total = axis_p * -eval_joint_force(
q,
qd,
joint_act[i_0],
joint_target_ke[i_0],
joint_target_kd[i_0],
joint_limit_lower[i_0],
joint_limit_upper[i_0],
joint_limit_ke[i_0],
joint_limit_kd[i_0],
joint_axis_mode[i_0],
)
# attachment dynamics
swing_err = wp.cross(axis_p, axis_c)
t_total += swing_err * joint_attach_ke + (w_err - qd * axis_p) * joint_attach_kd * angular_damping_scale
if ang_axis_count == 2:
q_pc = wp.quat_inverse(q_p) * q_c
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
orig_axis_0 = joint_axis[i_0]
orig_axis_1 = joint_axis[i_1]
orig_axis_2 = wp.cross(orig_axis_0, orig_axis_1)
# reconstruct rotation axes
axis_0 = orig_axis_0
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, orig_axis_1)
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, orig_axis_2)
axis_0 = wp.transform_vector(X_wp, axis_0)
axis_1 = wp.transform_vector(X_wp, axis_1)
axis_2 = wp.transform_vector(X_wp, axis_2)
# joint dynamics
t_total += axis_0 * -eval_joint_force(
angles[0],
wp.dot(axis_0, w_err),
joint_act[i_0],
joint_target_ke[i_0],
joint_target_kd[i_0],
joint_limit_lower[i_0],
joint_limit_upper[i_0],
joint_limit_ke[i_0],
joint_limit_kd[i_0],
joint_axis_mode[i_0],
)
t_total += axis_1 * -eval_joint_force(
angles[1],
wp.dot(axis_1, w_err),
joint_act[i_1],
joint_target_ke[i_1],
joint_target_kd[i_1],
joint_limit_lower[i_1],
joint_limit_upper[i_1],
joint_limit_ke[i_1],
joint_limit_kd[i_1],
joint_axis_mode[i_1],
)
# last axis (fixed)
t_total += axis_2 * -eval_joint_force(
angles[2],
wp.dot(axis_2, w_err),
0.0,
joint_attach_ke,
joint_attach_kd * angular_damping_scale,
0.0,
0.0,
0.0,
0.0,
wp.sim.JOINT_MODE_FORCE,
)
if ang_axis_count == 3:
q_pc = wp.quat_inverse(q_p) * q_c
# decompose to a compound rotation each axis
angles = quat_decompose(q_pc)
orig_axis_0 = joint_axis[i_0]
orig_axis_1 = joint_axis[i_1]
orig_axis_2 = joint_axis[i_2]
# reconstruct rotation axes
axis_0 = orig_axis_0
q_0 = wp.quat_from_axis_angle(axis_0, angles[0])
axis_1 = wp.quat_rotate(q_0, orig_axis_1)
q_1 = wp.quat_from_axis_angle(axis_1, angles[1])
axis_2 = wp.quat_rotate(q_1 * q_0, orig_axis_2)
axis_0 = wp.transform_vector(X_wp, axis_0)
axis_1 = wp.transform_vector(X_wp, axis_1)
axis_2 = wp.transform_vector(X_wp, axis_2)
t_total += axis_0 * -eval_joint_force(
angles[0],
wp.dot(axis_0, w_err),
joint_act[i_0],
joint_target_ke[i_0],
joint_target_kd[i_0],
joint_limit_lower[i_0],
joint_limit_upper[i_0],
joint_limit_ke[i_0],
joint_limit_kd[i_0],
joint_axis_mode[i_0],
)
t_total += axis_1 * -eval_joint_force(
angles[1],
wp.dot(axis_1, w_err),
joint_act[i_1],
joint_target_ke[i_1],
joint_target_kd[i_1],
joint_limit_lower[i_1],
joint_limit_upper[i_1],
joint_limit_ke[i_1],
joint_limit_kd[i_1],
joint_axis_mode[i_1],
)
t_total += axis_2 * -eval_joint_force(
angles[2],
wp.dot(axis_2, w_err),
joint_act[i_2],
joint_target_ke[i_2],
joint_target_kd[i_2],
joint_limit_lower[i_2],
joint_limit_upper[i_2],
joint_limit_ke[i_2],
joint_limit_kd[i_2],
joint_axis_mode[i_2],
)
# write forces
if c_parent >= 0:
wp.atomic_add(body_f, c_parent, wp.spatial_vector(t_total + wp.cross(r_p, f_total), f_total))
wp.atomic_sub(body_f, c_child, wp.spatial_vector(t_total + wp.cross(r_c, f_total), f_total))
@wp.func
def compute_muscle_force(
i: int,
body_X_s: wp.array(dtype=wp.transform),
body_v_s: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
muscle_links: wp.array(dtype=int),
muscle_points: wp.array(dtype=wp.vec3),
muscle_activation: float,
body_f_s: wp.array(dtype=wp.spatial_vector),
):
link_0 = muscle_links[i]
link_1 = muscle_links[i + 1]
if link_0 == link_1:
return 0
r_0 = muscle_points[i]
r_1 = muscle_points[i + 1]
xform_0 = body_X_s[link_0]
xform_1 = body_X_s[link_1]
pos_0 = wp.transform_point(xform_0, r_0 - body_com[link_0])
pos_1 = wp.transform_point(xform_1, r_1 - body_com[link_1])
n = wp.normalize(pos_1 - pos_0)
# todo: add passive elastic and viscosity terms
f = n * muscle_activation
wp.atomic_sub(body_f_s, link_0, wp.spatial_vector(f, wp.cross(pos_0, f)))
wp.atomic_add(body_f_s, link_1, wp.spatial_vector(f, wp.cross(pos_1, f)))
@wp.kernel
def eval_muscles(
body_X_s: wp.array(dtype=wp.transform),
body_v_s: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
muscle_start: wp.array(dtype=int),
muscle_params: wp.array(dtype=float),
muscle_links: wp.array(dtype=int),
muscle_points: wp.array(dtype=wp.vec3),
muscle_activation: wp.array(dtype=float),
# output
body_f_s: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
m_start = muscle_start[tid]
m_end = muscle_start[tid + 1] - 1
activation = muscle_activation[tid]
for i in range(m_start, m_end):
compute_muscle_force(i, body_X_s, body_v_s, body_com, muscle_links, muscle_points, activation, body_f_s)
def eval_spring_forces(model: Model, state: State, particle_f: wp.array):
if model.spring_count:
wp.launch(
kernel=eval_springs,
dim=model.spring_count,
inputs=[
state.particle_q,
state.particle_qd,
model.spring_indices,
model.spring_rest_length,
model.spring_stiffness,
model.spring_damping,
],
outputs=[particle_f],
device=model.device,
)
def eval_triangle_forces(model: Model, state: State, control: Control, particle_f: wp.array):
if model.tri_count:
wp.launch(
kernel=eval_triangles,
dim=model.tri_count,
inputs=[
state.particle_q,
state.particle_qd,
model.tri_indices,
model.tri_poses,
control.tri_activations,
model.tri_materials,
],
outputs=[particle_f],
device=model.device,
)
def eval_triangle_contact_forces(model: Model, state: State, particle_f: wp.array):
if model.enable_tri_collisions:
wp.launch(
kernel=eval_triangles_contact,
dim=model.tri_count * model.particle_count,
inputs=[
model.particle_count,
state.particle_q,
state.particle_qd,
model.tri_indices,
model.tri_materials,
],
outputs=[particle_f],
device=model.device,
)
def eval_bending_forces(model: Model, state: State, particle_f: wp.array):
if model.edge_count:
wp.launch(
kernel=eval_bending,
dim=model.edge_count,
inputs=[
state.particle_q,
state.particle_qd,
model.edge_indices,
model.edge_rest_angle,
model.edge_bending_properties,
],
outputs=[particle_f],
device=model.device,
)
def eval_particle_ground_contact_forces(model: Model, state: State, particle_f: wp.array):
if model.ground and model.particle_count:
wp.launch(
kernel=eval_particle_ground_contacts,
dim=model.particle_count,
inputs=[
state.particle_q,
state.particle_qd,
model.particle_radius,
model.particle_flags,
model.soft_contact_ke,
model.soft_contact_kd,
model.soft_contact_kf,
model.soft_contact_mu,
model.ground_plane,
],
outputs=[particle_f],
device=model.device,
)
def eval_tetrahedral_forces(model: Model, state: State, control: Control, particle_f: wp.array):
if model.tet_count:
wp.launch(
kernel=eval_tetrahedra,
dim=model.tet_count,
inputs=[
state.particle_q,
state.particle_qd,
model.tet_indices,
model.tet_poses,
control.tet_activations,
model.tet_materials,
],
outputs=[particle_f],
device=model.device,
)
def eval_body_contact_forces(model: Model, state: State, particle_f: wp.array):
if model.rigid_contact_max and (
model.ground and model.shape_ground_contact_pair_count or model.shape_contact_pair_count
):
wp.launch(
kernel=eval_rigid_contacts,
dim=model.rigid_contact_max,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.shape_materials,
model.shape_geo,
model.shape_body,
model.rigid_contact_count,
model.rigid_contact_point0,
model.rigid_contact_point1,
model.rigid_contact_normal,
model.rigid_contact_shape0,
model.rigid_contact_shape1,
False,
],
outputs=[state.body_f],
device=model.device,
)
def eval_body_joint_forces(model: Model, state: State, control: Control, body_f: wp.array):
if model.joint_count:
wp.launch(
kernel=eval_body_joints,
dim=model.joint_count,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.joint_qd_start,
model.joint_type,
model.joint_enabled,
model.joint_child,
model.joint_parent,
model.joint_X_p,
model.joint_X_c,
model.joint_axis,
model.joint_axis_start,
model.joint_axis_dim,
model.joint_axis_mode,
control.joint_act,
model.joint_target_ke,
model.joint_target_kd,
model.joint_limit_lower,
model.joint_limit_upper,
model.joint_limit_ke,
model.joint_limit_kd,
model.joint_attach_ke,
model.joint_attach_kd,
],
outputs=[body_f],
device=model.device,
)
def eval_particle_body_contact_forces(model: Model, state: State, particle_f: wp.array, body_f: wp.array):
if model.particle_count and model.shape_count > 1:
wp.launch(
kernel=eval_particle_contacts,
dim=model.soft_contact_max,
inputs=[
state.particle_q,
state.particle_qd,
state.body_q,
state.body_qd,
model.particle_radius,
model.particle_flags,
model.body_com,
model.shape_body,
model.shape_materials,
model.soft_contact_ke,
model.soft_contact_kd,
model.soft_contact_kf,
model.soft_contact_mu,
model.particle_adhesion,
model.soft_contact_count,
model.soft_contact_particle,
model.soft_contact_shape,
model.soft_contact_body_pos,
model.soft_contact_body_vel,
model.soft_contact_normal,
model.soft_contact_max,
],
# outputs
outputs=[particle_f, body_f],
device=model.device,
)
def eval_muscle_forces(model: Model, state: State, control: Control, body_f: wp.array):
if model.muscle_count:
wp.launch(
kernel=eval_muscles,
dim=model.muscle_count,
inputs=[
state.body_q,
state.body_qd,
model.body_com,
model.muscle_start,
model.muscle_params,
model.muscle_bodies,
model.muscle_points,
control.muscle_activations,
],
outputs=[body_f],
device=model.device,
)
def compute_forces(model: Model, state: State, control: Control, particle_f: wp.array, body_f: wp.array, dt: float):
# damped springs
eval_spring_forces(model, state, particle_f)
# triangle elastic and lift/drag forces
eval_triangle_forces(model, state, control, particle_f)
# triangle/triangle contacts
eval_triangle_contact_forces(model, state, particle_f)
# triangle bending
eval_bending_forces(model, state, particle_f)
# tetrahedral FEM
eval_tetrahedral_forces(model, state, control, particle_f)
# body joints
eval_body_joint_forces(model, state, control, body_f)
# particle-particle interactions
eval_particle_forces(model, state, particle_f)
# particle ground contacts
eval_particle_ground_contact_forces(model, state, particle_f)
# body contacts
eval_body_contact_forces(model, state, particle_f)
# particle shape contact
eval_particle_body_contact_forces(model, state, particle_f, body_f)
# muscles
if False:
eval_muscle_forces(model, state, control, body_f)
class SemiImplicitIntegrator(Integrator):
"""A semi-implicit integrator using symplectic Euler
After constructing `Model` and `State` objects this time-integrator
may be used to advance the simulation state forward in time.
Semi-implicit time integration is a variational integrator that
preserves energy, however it not unconditionally stable, and requires a time-step
small enough to support the required stiffness and damping forces.
See: https://en.wikipedia.org/wiki/Semi-implicit_Euler_method
Example
-------
.. code-block:: python
integrator = wp.SemiImplicitIntegrator()
# simulation loop
for i in range(100):
state = integrator.simulate(model, state_in, state_out, dt)
"""
def __init__(self, angular_damping: float = 0.05):
"""
Args:
angular_damping (float, optional): Angular damping factor. Defaults to 0.05.
"""
self.angular_damping = angular_damping
def simulate(self, model: Model, state_in: State, state_out: State, dt: float, control: Control = None):
with wp.ScopedTimer("simulate", False):
particle_f = None
body_f = None
if state_in.particle_count:
particle_f = state_in.particle_f
if state_in.body_count:
body_f = state_in.body_f
if control is None:
control = model.control(clone_variables=False)
compute_forces(model, state_in, control, particle_f, body_f, dt)
self.integrate_bodies(model, state_in, state_out, dt, self.angular_damping)
self.integrate_particles(model, state_in, state_out, dt)
return state_out
| 59,364 | Python | 29.334696 | 361 | 0.536419 |
NVIDIA/warp/warp/sim/import_urdf.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os
import xml.etree.ElementTree as ET
from typing import Union
import numpy as np
import warp as wp
from warp.sim.model import Mesh
def parse_urdf(
urdf_filename,
builder,
xform=None,
floating=False,
base_joint: Union[dict, str] = None,
density=1000.0,
stiffness=100.0,
damping=10.0,
armature=0.0,
contact_ke=1.0e4,
contact_kd=1.0e3,
contact_kf=1.0e2,
contact_ka=0.0,
contact_mu=0.25,
contact_restitution=0.5,
contact_thickness=0.0,
limit_ke=100.0,
limit_kd=10.0,
joint_limit_lower=-1e6,
joint_limit_upper=1e6,
scale=1.0,
parse_visuals_as_colliders=False,
force_show_colliders=False,
enable_self_collisions=True,
ignore_inertial_definitions=True,
ensure_nonstatic_links=True,
static_link_mass=1e-2,
collapse_fixed_joints=False,
):
"""
Parses a URDF file and adds the bodies and joints to the given ModelBuilder.
Args:
urdf_filename (str): The filename of the URDF file to parse.
builder (ModelBuilder): The :class:`ModelBuilder` to add the bodies and joints to.
xform (:ref:`transform <transform>`): The transform to apply to the root body.
floating (bool): If True, the root body is a free joint. If False, the root body is connected via a fixed joint to the world, unless a `base_joint` is defined.
base_joint (Union[str, dict]): The joint by which the root body is connected to the world. This can be either a string defining the joint axes of a D6 joint with comma-separated positional and angular axis names (e.g. "px,py,rz" for a D6 joint with linear axes in x, y and an angular axis in z) or a dict with joint parameters (see :meth:`ModelBuilder.add_joint`).
density (float): The density of the shapes in kg/m^3 which will be used to calculate the body mass and inertia.
stiffness (float): The stiffness of the joints.
damping (float): The damping of the joints.
armature (float): The armature of the joints (bias to add to the inertia diagonals that may stabilize the simulation).
contact_ke (float): The stiffness of the shape contacts (used by the Euler integrators).
contact_kd (float): The damping of the shape contacts (used by the Euler integrators).
contact_kf (float): The friction stiffness of the shape contacts (used by the Euler integrators).
contact_ka (float): The adhesion distance of the shape contacts (used by the Euler integrators).
contact_mu (float): The friction coefficient of the shape contacts.
contact_restitution (float): The restitution coefficient of the shape contacts.
contact_thickness (float): The thickness to add to the shape geometry.
limit_ke (float): The stiffness of the joint limits (used by the Euler integrators).
limit_kd (float): The damping of the joint limits (used by the Euler integrators).
joint_limit_lower (float): The default lower joint limit if not specified in the URDF.
joint_limit_upper (float): The default upper joint limit if not specified in the URDF.
scale (float): The scaling factor to apply to the imported mechanism.
parse_visuals_as_colliders (bool): If True, the geometry defined under the `<visual>` tags is used for collision handling instead of the `<collision>` geometries.
force_show_colliders (bool): If True, the collision shapes are always shown, even if there are visual shapes.
enable_self_collisions (bool): If True, self-collisions are enabled.
ignore_inertial_definitions (bool): If True, the inertial parameters defined in the URDF are ignored and the inertia is calculated from the shape geometry.
ensure_nonstatic_links (bool): If True, links with zero mass are given a small mass (see `static_link_mass`) to ensure they are dynamic.
static_link_mass (float): The mass to assign to links with zero mass (if `ensure_nonstatic_links` is set to True).
collapse_fixed_joints (bool): If True, fixed joints are removed and the respective bodies are merged.
"""
if xform is None:
xform = wp.transform()
file = ET.parse(urdf_filename)
root = file.getroot()
contact_vars = {
"ke": contact_ke,
"kd": contact_kd,
"kf": contact_kf,
"ka": contact_ka,
"mu": contact_mu,
"restitution": contact_restitution,
"thickness": contact_thickness,
}
def parse_transform(element):
if element is None or element.find("origin") is None:
return wp.transform()
origin = element.find("origin")
xyz = origin.get("xyz") or "0 0 0"
rpy = origin.get("rpy") or "0 0 0"
xyz = [float(x) * scale for x in xyz.split()]
rpy = [float(x) for x in rpy.split()]
return wp.transform(xyz, wp.quat_rpy(*rpy))
def parse_shapes(link, geoms, density, incoming_xform=None, visible=True, just_visual=False):
shapes = []
# add geometry
for geom_group in geoms:
geo = geom_group.find("geometry")
if geo is None:
continue
tf = parse_transform(geom_group)
if incoming_xform is not None:
tf = incoming_xform * tf
for box in geo.findall("box"):
size = box.get("size") or "1 1 1"
size = [float(x) for x in size.split()]
s = builder.add_shape_box(
body=link,
pos=wp.vec3(tf.p),
rot=wp.quat(tf.q),
hx=size[0] * 0.5 * scale,
hy=size[1] * 0.5 * scale,
hz=size[2] * 0.5 * scale,
density=density,
is_visible=visible,
has_ground_collision=not just_visual,
has_shape_collision=not just_visual,
**contact_vars,
)
shapes.append(s)
for sphere in geo.findall("sphere"):
s = builder.add_shape_sphere(
body=link,
pos=wp.vec3(tf.p),
rot=wp.quat(tf.q),
radius=float(sphere.get("radius") or "1") * scale,
density=density,
is_visible=visible,
has_ground_collision=not just_visual,
has_shape_collision=not just_visual,
**contact_vars,
)
shapes.append(s)
for cylinder in geo.findall("cylinder"):
s = builder.add_shape_capsule(
body=link,
pos=wp.vec3(tf.p),
rot=wp.quat(tf.q),
radius=float(cylinder.get("radius") or "1") * scale,
half_height=float(cylinder.get("length") or "1") * 0.5 * scale,
density=density,
up_axis=2, # cylinders in URDF are aligned with z-axis
is_visible=visible,
has_ground_collision=not just_visual,
has_shape_collision=not just_visual,
**contact_vars,
)
shapes.append(s)
for mesh in geo.findall("mesh"):
filename = mesh.get("filename")
if filename is None:
continue
if filename.startswith("package://"):
fn = filename.replace("package://", "")
package_name = fn.split("/")[0]
urdf_folder = os.path.dirname(urdf_filename)
# resolve file path from package name, i.e. find
# the package folder from the URDF folder
if package_name in urdf_folder:
filename = os.path.join(urdf_folder[: urdf_folder.index(package_name)], fn)
else:
wp.utils.warn(
f'Warning: package "{package_name}" not found in URDF folder while loading mesh at "{filename}"'
)
elif filename.startswith("http://") or filename.startswith("https://"):
# download mesh
import shutil
import tempfile
import requests
with tempfile.TemporaryDirectory() as tmpdir:
# get filename extension
extension = os.path.splitext(filename)[1]
tmpfile = os.path.join(tmpdir, "mesh" + extension)
with requests.get(filename, stream=True) as r:
with open(tmpfile, "wb") as f:
shutil.copyfileobj(r.raw, f)
filename = tmpfile
else:
filename = os.path.join(os.path.dirname(urdf_filename), filename)
if not os.path.exists(filename):
wp.utils.warn(f"Warning: mesh file {filename} does not exist")
continue
import trimesh
# use force='mesh' to load the mesh as a trimesh object
# with baked in transforms, e.g. from COLLADA files
m = trimesh.load(filename, force="mesh")
scaling = mesh.get("scale") or "1 1 1"
scaling = np.array([float(x) * scale for x in scaling.split()])
if hasattr(m, "geometry"):
# multiple meshes are contained in a scene
for geom in m.geometry.values():
vertices = np.array(geom.vertices, dtype=np.float32) * scaling
faces = np.array(geom.faces.flatten(), dtype=np.int32)
mesh = Mesh(vertices, faces)
s = builder.add_shape_mesh(
body=link,
pos=wp.vec3(tf.p),
rot=wp.quat(tf.q),
mesh=mesh,
density=density,
is_visible=visible,
has_ground_collision=not just_visual,
has_shape_collision=not just_visual,
**contact_vars,
)
shapes.append(s)
else:
# a single mesh
vertices = np.array(m.vertices, dtype=np.float32) * scaling
faces = np.array(m.faces.flatten(), dtype=np.int32)
mesh = Mesh(vertices, faces)
s = builder.add_shape_mesh(
body=link,
pos=wp.vec3(tf.p),
rot=wp.quat(tf.q),
mesh=mesh,
density=density,
is_visible=visible,
has_ground_collision=not just_visual,
has_shape_collision=not just_visual,
**contact_vars,
)
shapes.append(s)
return shapes
# maps from link name -> link index
link_index = {}
visual_shapes = []
builder.add_articulation()
start_shape_count = len(builder.shape_geo_type)
# add links
for _i, urdf_link in enumerate(root.findall("link")):
name = urdf_link.get("name")
link = builder.add_body(origin=wp.transform_identity(), armature=armature, name=name)
# add ourselves to the index
link_index[name] = link
visuals = urdf_link.findall("visual")
colliders = urdf_link.findall("collision")
if parse_visuals_as_colliders:
colliders = visuals
else:
s = parse_shapes(link, visuals, density=0.0, just_visual=True)
visual_shapes.extend(s)
show_colliders = force_show_colliders
if parse_visuals_as_colliders:
show_colliders = True
elif len(visuals) == 0:
# we need to show the collision shapes since there are no visual shapes
show_colliders = True
parse_shapes(link, colliders, density=density, visible=show_colliders)
m = builder.body_mass[link]
if not ignore_inertial_definitions and urdf_link.find("inertial") is not None:
# overwrite inertial parameters if defined
inertial = urdf_link.find("inertial")
inertial_frame = parse_transform(inertial)
com = inertial_frame.p
I_m = np.zeros((3, 3))
I_m[0, 0] = float(inertial.find("inertia").get("ixx") or "0") * scale**2
I_m[1, 1] = float(inertial.find("inertia").get("iyy") or "0") * scale**2
I_m[2, 2] = float(inertial.find("inertia").get("izz") or "0") * scale**2
I_m[0, 1] = float(inertial.find("inertia").get("ixy") or "0") * scale**2
I_m[0, 2] = float(inertial.find("inertia").get("ixz") or "0") * scale**2
I_m[1, 2] = float(inertial.find("inertia").get("iyz") or "0") * scale**2
I_m[1, 0] = I_m[0, 1]
I_m[2, 0] = I_m[0, 2]
I_m[2, 1] = I_m[1, 2]
rot = wp.quat_to_matrix(inertial_frame.q)
I_m = rot @ wp.mat33(I_m)
m = float(inertial.find("mass").get("value") or "0")
builder.body_mass[link] = m
builder.body_inv_mass[link] = 1.0 / m
builder.body_com[link] = com
builder.body_inertia[link] = I_m
builder.body_inv_inertia[link] = wp.inverse(I_m)
if m == 0.0 and ensure_nonstatic_links:
# set the mass to something nonzero to ensure the body is dynamic
m = static_link_mass
# cube with side length 0.5
I_m = wp.mat33(np.eye(3)) * m / 12.0 * (0.5 * scale) ** 2 * 2.0
I_m += wp.mat33(armature * np.eye(3))
builder.body_mass[link] = m
builder.body_inv_mass[link] = 1.0 / m
builder.body_inertia[link] = I_m
builder.body_inv_inertia[link] = wp.inverse(I_m)
end_shape_count = len(builder.shape_geo_type)
# find joints per body
body_children = {name: [] for name in link_index.keys()}
# mapping from parent, child link names to joint
parent_child_joint = {}
joints = []
for joint in root.findall("joint"):
parent = joint.find("parent").get("link")
child = joint.find("child").get("link")
body_children[parent].append(child)
joint_data = {
"name": joint.get("name"),
"parent": parent,
"child": child,
"type": joint.get("type"),
"origin": parse_transform(joint),
"damping": damping,
"friction": 0.0,
"limit_lower": joint_limit_lower,
"limit_upper": joint_limit_upper,
}
if joint.find("axis") is not None:
joint_data["axis"] = joint.find("axis").get("xyz")
joint_data["axis"] = np.array([float(x) for x in joint_data["axis"].split()])
if joint.find("dynamics") is not None:
dynamics = joint.find("dynamics")
joint_data["damping"] = float(dynamics.get("damping") or str(damping))
joint_data["friction"] = float(dynamics.get("friction") or "0")
if joint.find("limit") is not None:
limit = joint.find("limit")
joint_data["limit_lower"] = float(limit.get("lower") or "-1e6")
joint_data["limit_upper"] = float(limit.get("upper") or "1e6")
if joint.find("mimic") is not None:
mimic = joint.find("mimic")
joint_data["mimic_joint"] = mimic.get("joint")
joint_data["mimic_multiplier"] = float(mimic.get("multiplier") or "1")
joint_data["mimic_offset"] = float(mimic.get("offset") or "0")
parent_child_joint[(parent, child)] = joint_data
joints.append(joint_data)
# topological sorting of joints because the FK solver will resolve body transforms
# in joint order and needs the parent link transform to be resolved before the child
visited = {name: False for name in link_index.keys()}
sorted_joints = []
# depth-first search
def dfs(joint):
link = joint["child"]
if visited[link]:
return
visited[link] = True
for child in body_children[link]:
if not visited[child]:
dfs(parent_child_joint[(link, child)])
sorted_joints.insert(0, joint)
# start DFS from each unvisited joint
for joint in joints:
if not visited[joint["parent"]]:
dfs(joint)
# add base joint
if len(sorted_joints) > 0:
base_link_name = sorted_joints[0]["parent"]
else:
base_link_name = next(iter(link_index.keys()))
root = link_index[base_link_name]
if base_joint is not None:
# in case of a given base joint, the position is applied first, the rotation only
# after the base joint itself to not rotate its axis
base_parent_xform = wp.transform(xform.p, wp.quat_identity())
base_child_xform = wp.transform((0.0, 0.0, 0.0), wp.quat_inverse(xform.q))
if isinstance(base_joint, str):
axes = base_joint.lower().split(",")
axes = [ax.strip() for ax in axes]
linear_axes = [ax[-1] for ax in axes if ax[0] in {"l", "p"}]
angular_axes = [ax[-1] for ax in axes if ax[0] in {"a", "r"}]
axes = {
"x": [1.0, 0.0, 0.0],
"y": [0.0, 1.0, 0.0],
"z": [0.0, 0.0, 1.0],
}
builder.add_joint_d6(
linear_axes=[wp.sim.JointAxis(axes[a]) for a in linear_axes],
angular_axes=[wp.sim.JointAxis(axes[a]) for a in angular_axes],
parent_xform=base_parent_xform,
child_xform=base_child_xform,
parent=-1,
child=root,
name="base_joint",
)
elif isinstance(base_joint, dict):
base_joint["parent"] = -1
base_joint["child"] = root
base_joint["parent_xform"] = base_parent_xform
base_joint["child_xform"] = base_child_xform
base_joint["name"] = "base_joint"
builder.add_joint(**base_joint)
else:
raise ValueError(
"base_joint must be a comma-separated string of joint axes or a dict with joint parameters"
)
elif floating:
builder.add_joint_free(root, name="floating_base")
# set dofs to transform
start = builder.joint_q_start[root]
builder.joint_q[start + 0] = xform.p[0]
builder.joint_q[start + 1] = xform.p[1]
builder.joint_q[start + 2] = xform.p[2]
builder.joint_q[start + 3] = xform.q[0]
builder.joint_q[start + 4] = xform.q[1]
builder.joint_q[start + 5] = xform.q[2]
builder.joint_q[start + 6] = xform.q[3]
else:
builder.add_joint_fixed(-1, root, parent_xform=xform, name="fixed_base")
# add joints, in topological order starting from root body
for joint in sorted_joints:
parent = link_index[joint["parent"]]
child = link_index[joint["child"]]
if child == -1:
# we skipped the insertion of the child body
continue
lower = joint["limit_lower"]
upper = joint["limit_upper"]
joint_damping = joint["damping"]
parent_xform = joint["origin"]
child_xform = wp.transform_identity()
joint_mode = wp.sim.JOINT_MODE_FORCE
if stiffness > 0.0:
joint_mode = wp.sim.JOINT_MODE_TARGET_POSITION
joint_params = {
"parent": parent,
"child": child,
"parent_xform": parent_xform,
"child_xform": child_xform,
"name": joint["name"],
"armature": armature,
}
if joint["type"] == "revolute" or joint["type"] == "continuous":
builder.add_joint_revolute(
axis=joint["axis"],
target_ke=stiffness,
target_kd=joint_damping,
limit_lower=lower,
limit_upper=upper,
limit_ke=limit_ke,
limit_kd=limit_kd,
mode=joint_mode,
**joint_params,
)
elif joint["type"] == "prismatic":
builder.add_joint_prismatic(
axis=joint["axis"],
target_ke=stiffness,
target_kd=joint_damping,
limit_lower=lower * scale,
limit_upper=upper * scale,
limit_ke=limit_ke,
limit_kd=limit_kd,
mode=joint_mode,
**joint_params,
)
elif joint["type"] == "fixed":
builder.add_joint_fixed(**joint_params)
elif joint["type"] == "floating":
builder.add_joint_free(**joint_params)
elif joint["type"] == "planar":
# find plane vectors perpendicular to axis
axis = np.array(joint["axis"])
axis /= np.linalg.norm(axis)
# create helper vector that is not parallel to the axis
helper = np.array([1, 0, 0]) if np.allclose(axis, [0, 1, 0]) else np.array([0, 1, 0])
u = np.cross(helper, axis)
u /= np.linalg.norm(u)
v = np.cross(axis, u)
v /= np.linalg.norm(v)
builder.add_joint_d6(
linear_axes=[
wp.sim.JointAxis(
u, limit_lower=lower * scale, limit_upper=upper * scale, limit_ke=limit_ke, limit_kd=limit_kd
),
wp.sim.JointAxis(
v, limit_lower=lower * scale, limit_upper=upper * scale, limit_ke=limit_ke, limit_kd=limit_kd
),
],
**joint_params,
)
else:
raise Exception("Unsupported joint type: " + joint["type"])
for i in range(start_shape_count, end_shape_count):
for j in visual_shapes:
builder.shape_collision_filter_pairs.add((i, j))
if not enable_self_collisions:
for i in range(start_shape_count, end_shape_count):
for j in range(i + 1, end_shape_count):
builder.shape_collision_filter_pairs.add((i, j))
if collapse_fixed_joints:
builder.collapse_fixed_joints()
| 23,095 | Python | 42.009311 | 372 | 0.542368 |
NVIDIA/warp/warp/sim/inertia.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Helper functions for computing rigid body inertia properties."""
import math
from typing import List, Union
import numpy as np
import warp as wp
@wp.func
def triangle_inertia(
p: wp.vec3,
q: wp.vec3,
r: wp.vec3,
density: float,
com: wp.vec3,
# outputs
mass: wp.array(dtype=float, ndim=1),
inertia: wp.array(dtype=wp.mat33, ndim=1),
):
pcom = p - com
qcom = q - com
rcom = r - com
Dm = wp.mat33(pcom[0], qcom[0], rcom[0], pcom[1], qcom[1], rcom[1], pcom[2], qcom[2], rcom[2])
volume = wp.abs(wp.determinant(Dm) / 6.0)
# accumulate mass
wp.atomic_add(mass, 0, 4.0 * density * volume)
alpha = wp.sqrt(5.0) / 5.0
mid = (com + p + q + r) / 4.0
off_mid = mid - com
# displacement of quadrature point from COM
d0 = alpha * (p - mid) + off_mid
d1 = alpha * (q - mid) + off_mid
d2 = alpha * (r - mid) + off_mid
d3 = alpha * (com - mid) + off_mid
# accumulate inertia
identity = wp.mat33(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
I = wp.dot(d0, d0) * identity - wp.outer(d0, d0)
I += wp.dot(d1, d1) * identity - wp.outer(d1, d1)
I += wp.dot(d2, d2) * identity - wp.outer(d2, d2)
I += wp.dot(d3, d3) * identity - wp.outer(d3, d3)
wp.atomic_add(inertia, 0, (density * volume) * I)
return volume
@wp.kernel
def compute_solid_mesh_inertia(
# inputs
com: wp.vec3,
weight: float,
indices: wp.array(dtype=int, ndim=1),
vertices: wp.array(dtype=wp.vec3, ndim=1),
# outputs
mass: wp.array(dtype=float, ndim=1),
inertia: wp.array(dtype=wp.mat33, ndim=1),
volume: wp.array(dtype=float, ndim=1),
):
i = wp.tid()
p = vertices[indices[i * 3 + 0]]
q = vertices[indices[i * 3 + 1]]
r = vertices[indices[i * 3 + 2]]
vol = triangle_inertia(p, q, r, weight, com, mass, inertia)
wp.atomic_add(volume, 0, vol)
@wp.kernel
def compute_hollow_mesh_inertia(
# inputs
com: wp.vec3,
density: float,
indices: wp.array(dtype=int, ndim=1),
vertices: wp.array(dtype=wp.vec3, ndim=1),
thickness: wp.array(dtype=float, ndim=1),
# outputs
mass: wp.array(dtype=float, ndim=1),
inertia: wp.array(dtype=wp.mat33, ndim=1),
volume: wp.array(dtype=float, ndim=1),
):
tid = wp.tid()
i = indices[tid * 3 + 0]
j = indices[tid * 3 + 1]
k = indices[tid * 3 + 2]
vi = vertices[i]
vj = vertices[j]
vk = vertices[k]
normal = -wp.normalize(wp.cross(vj - vi, vk - vi))
ti = normal * thickness[i]
tj = normal * thickness[j]
tk = normal * thickness[k]
# wedge vertices
vi0 = vi - ti
vi1 = vi + ti
vj0 = vj - tj
vj1 = vj + tj
vk0 = vk - tk
vk1 = vk + tk
triangle_inertia(vi0, vj0, vk0, density, com, mass, inertia)
triangle_inertia(vj0, vk1, vk0, density, com, mass, inertia)
triangle_inertia(vj0, vj1, vk1, density, com, mass, inertia)
triangle_inertia(vj0, vi1, vj1, density, com, mass, inertia)
triangle_inertia(vj0, vi0, vi1, density, com, mass, inertia)
triangle_inertia(vj1, vi1, vk1, density, com, mass, inertia)
triangle_inertia(vi1, vi0, vk0, density, com, mass, inertia)
triangle_inertia(vi1, vk0, vk1, density, com, mass, inertia)
# compute volume
a = wp.length(wp.cross(vj - vi, vk - vi)) * 0.5
vol = a * (thickness[i] + thickness[j] + thickness[k]) / 3.0
wp.atomic_add(volume, 0, vol)
def compute_sphere_inertia(density: float, r: float) -> tuple:
"""Helper to compute mass and inertia of a solid sphere
Args:
density: The sphere density
r: The sphere radius
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
v = 4.0 / 3.0 * math.pi * r * r * r
m = density * v
Ia = 2.0 / 5.0 * m * r * r
I = wp.mat33([[Ia, 0.0, 0.0], [0.0, Ia, 0.0], [0.0, 0.0, Ia]])
return (m, wp.vec3(), I)
def compute_capsule_inertia(density: float, r: float, h: float) -> tuple:
"""Helper to compute mass and inertia of a solid capsule extending along the y-axis
Args:
density: The capsule density
r: The capsule radius
h: The capsule height (full height of the interior cylinder)
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
ms = density * (4.0 / 3.0) * math.pi * r * r * r
mc = density * math.pi * r * r * h
# total mass
m = ms + mc
# adapted from ODE
Ia = mc * (0.25 * r * r + (1.0 / 12.0) * h * h) + ms * (0.4 * r * r + 0.375 * r * h + 0.25 * h * h)
Ib = (mc * 0.5 + ms * 0.4) * r * r
I = wp.mat33([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ia]])
return (m, wp.vec3(), I)
def compute_cylinder_inertia(density: float, r: float, h: float) -> tuple:
"""Helper to compute mass and inertia of a solid cylinder extending along the y-axis
Args:
density: The cylinder density
r: The cylinder radius
h: The cylinder height (extent along the y-axis)
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
m = density * math.pi * r * r * h
Ia = 1 / 12 * m * (3 * r * r + h * h)
Ib = 1 / 2 * m * r * r
I = wp.mat33([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ia]])
return (m, wp.vec3(), I)
def compute_cone_inertia(density: float, r: float, h: float) -> tuple:
"""Helper to compute mass and inertia of a solid cone extending along the y-axis
Args:
density: The cone density
r: The cone radius
h: The cone height (extent along the y-axis)
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
m = density * math.pi * r * r * h / 3.0
Ia = 1 / 20 * m * (3 * r * r + 2 * h * h)
Ib = 3 / 10 * m * r * r
I = wp.mat33([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ia]])
return (m, wp.vec3(), I)
def compute_box_inertia(density: float, w: float, h: float, d: float) -> tuple:
"""Helper to compute mass and inertia of a solid box
Args:
density: The box density
w: The box width along the x-axis
h: The box height along the y-axis
d: The box depth along the z-axis
Returns:
A tuple of (mass, inertia) with inertia specified around the origin
"""
v = w * h * d
m = density * v
Ia = 1.0 / 12.0 * m * (h * h + d * d)
Ib = 1.0 / 12.0 * m * (w * w + d * d)
Ic = 1.0 / 12.0 * m * (w * w + h * h)
I = wp.mat33([[Ia, 0.0, 0.0], [0.0, Ib, 0.0], [0.0, 0.0, Ic]])
return (m, wp.vec3(), I)
def compute_mesh_inertia(
density: float, vertices: list, indices: list, is_solid: bool = True, thickness: Union[List[float], float] = 0.001
) -> tuple:
"""Computes mass, center of mass, 3x3 inertia matrix, and volume for a mesh."""
com = wp.vec3(np.mean(vertices, 0))
indices = np.array(indices).flatten()
num_tris = len(indices) // 3
# compute signed inertia for each tetrahedron
# formed with the interior point, using an order-2
# quadrature: https://www.sciencedirect.com/science/article/pii/S0377042712001604#br000040
# Allocating for mass and inertia
I_warp = wp.zeros(1, dtype=wp.mat33)
mass_warp = wp.zeros(1, dtype=float)
vol_warp = wp.zeros(1, dtype=float)
if is_solid:
weight = 0.25
# alpha = math.sqrt(5.0) / 5.0
wp.launch(
kernel=compute_solid_mesh_inertia,
dim=num_tris,
inputs=[
com,
weight,
wp.array(indices, dtype=int),
wp.array(vertices, dtype=wp.vec3),
],
outputs=[mass_warp, I_warp, vol_warp],
)
else:
weight = 0.25 * density
if isinstance(thickness, float):
thickness = [thickness] * len(vertices)
wp.launch(
kernel=compute_hollow_mesh_inertia,
dim=num_tris,
inputs=[
com,
weight,
wp.array(indices, dtype=int),
wp.array(vertices, dtype=wp.vec3),
wp.array(thickness, dtype=float),
],
outputs=[mass_warp, I_warp, vol_warp],
)
# Extract mass and inertia and save to class attributes.
mass = float(mass_warp.numpy()[0] * density)
I = wp.mat33(*(I_warp.numpy()[0] * density))
volume = float(vol_warp.numpy()[0])
return mass, com, I, volume
def transform_inertia(m, I, p, q):
R = wp.quat_to_matrix(q)
# Steiner's theorem
return R @ I @ wp.transpose(R) + m * (wp.dot(p, p) * wp.mat33(np.eye(3)) - wp.outer(p, p))
| 9,074 | Python | 27.62776 | 118 | 0.573837 |
NVIDIA/warp/warp/sim/integrator.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import warp as wp
from .model import PARTICLE_FLAG_ACTIVE, Control, Model, State
@wp.kernel
def integrate_particles(
x: wp.array(dtype=wp.vec3),
v: wp.array(dtype=wp.vec3),
f: wp.array(dtype=wp.vec3),
w: wp.array(dtype=float),
particle_flags: wp.array(dtype=wp.uint32),
gravity: wp.vec3,
dt: float,
v_max: float,
x_new: wp.array(dtype=wp.vec3),
v_new: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
if (particle_flags[tid] & PARTICLE_FLAG_ACTIVE) == 0:
return
x0 = x[tid]
v0 = v[tid]
f0 = f[tid]
inv_mass = w[tid]
# simple semi-implicit Euler. v1 = v0 + a dt, x1 = x0 + v1 dt
v1 = v0 + (f0 * inv_mass + gravity * wp.step(-inv_mass)) * dt
# enforce velocity limit to prevent instability
v1_mag = wp.length(v1)
if v1_mag > v_max:
v1 *= v_max / v1_mag
x1 = x0 + v1 * dt
x_new[tid] = x1
v_new[tid] = v1
@wp.func
def integrate_rigid_body(
q: wp.transform,
qd: wp.spatial_vector,
f: wp.spatial_vector,
com: wp.vec3,
inertia: wp.mat33,
inv_mass: float,
inv_inertia: wp.mat33,
gravity: wp.vec3,
angular_damping: float,
dt: float,
):
# unpack transform
x0 = wp.transform_get_translation(q)
r0 = wp.transform_get_rotation(q)
# unpack spatial twist
w0 = wp.spatial_top(qd)
v0 = wp.spatial_bottom(qd)
# unpack spatial wrench
t0 = wp.spatial_top(f)
f0 = wp.spatial_bottom(f)
x_com = x0 + wp.quat_rotate(r0, com)
# linear part
v1 = v0 + (f0 * inv_mass + gravity * wp.nonzero(inv_mass)) * dt
x1 = x_com + v1 * dt
# angular part (compute in body frame)
wb = wp.quat_rotate_inv(r0, w0)
tb = wp.quat_rotate_inv(r0, t0) - wp.cross(wb, inertia * wb) # coriolis forces
w1 = wp.quat_rotate(r0, wb + inv_inertia * tb * dt)
r1 = wp.normalize(r0 + wp.quat(w1, 0.0) * r0 * 0.5 * dt)
# angular damping
w1 *= 1.0 - angular_damping * dt
q_new = wp.transform(x1 - wp.quat_rotate(r1, com), r1)
qd_new = wp.spatial_vector(w1, v1)
return q_new, qd_new
# semi-implicit Euler integration
@wp.kernel
def integrate_bodies(
body_q: wp.array(dtype=wp.transform),
body_qd: wp.array(dtype=wp.spatial_vector),
body_f: wp.array(dtype=wp.spatial_vector),
body_com: wp.array(dtype=wp.vec3),
m: wp.array(dtype=float),
I: wp.array(dtype=wp.mat33),
inv_m: wp.array(dtype=float),
inv_I: wp.array(dtype=wp.mat33),
gravity: wp.vec3,
angular_damping: float,
dt: float,
# outputs
body_q_new: wp.array(dtype=wp.transform),
body_qd_new: wp.array(dtype=wp.spatial_vector),
):
tid = wp.tid()
# positions
q = body_q[tid]
qd = body_qd[tid]
f = body_f[tid]
# masses
inv_mass = inv_m[tid] # 1 / mass
inertia = I[tid]
inv_inertia = inv_I[tid] # inverse of 3x3 inertia matrix
com = body_com[tid]
q_new, qd_new = integrate_rigid_body(
q,
qd,
f,
com,
inertia,
inv_mass,
inv_inertia,
gravity,
angular_damping,
dt,
)
body_q_new[tid] = q_new
body_qd_new[tid] = qd_new
class Integrator:
"""
Generic base class for integrators. Provides methods to integrate rigid bodies and particles.
"""
def integrate_bodies(
self,
model: Model,
state_in: State,
state_out: State,
dt: float,
angular_damping: float = 0.0,
):
"""
Integrate the rigid bodies of the model.
Args:
model (Model): The model to integrate.
state_in (State): The input state.
state_out (State): The output state.
dt (float): The time step (typically in seconds).
angular_damping (float, optional): The angular damping factor. Defaults to 0.0.
"""
if model.body_count:
wp.launch(
kernel=integrate_bodies,
dim=model.body_count,
inputs=[
state_in.body_q,
state_in.body_qd,
state_in.body_f,
model.body_com,
model.body_mass,
model.body_inertia,
model.body_inv_mass,
model.body_inv_inertia,
model.gravity,
angular_damping,
dt,
],
outputs=[state_out.body_q, state_out.body_qd],
device=model.device,
)
def integrate_particles(
self,
model: Model,
state_in: State,
state_out: State,
dt: float,
):
"""
Integrate the particles of the model.
Args:
model (Model): The model to integrate.
state_in (State): The input state.
state_out (State): The output state.
dt (float): The time step (typically in seconds).
"""
if model.particle_count:
wp.launch(
kernel=integrate_particles,
dim=model.particle_count,
inputs=[
state_in.particle_q,
state_in.particle_qd,
state_in.particle_f,
model.particle_inv_mass,
model.particle_flags,
model.gravity,
dt,
model.particle_max_velocity,
],
outputs=[state_out.particle_q, state_out.particle_qd],
device=model.device,
)
def simulate(self, model: Model, state_in: State, state_out: State, dt: float, control: Control = None):
"""
Simulate the model for a given time step using the given control input.
Args:
model (Model): The model to simulate.
state_in (State): The input state.
state_out (State): The output state.
dt (float): The time step (typically in seconds).
control (Control): The control input. Defaults to `None` which means the control values from the :class:`Model` are used.
"""
raise NotImplementedError()
| 6,652 | Python | 27.310638 | 133 | 0.555021 |
NVIDIA/warp/warp/fem/polynomial.py | import math
from enum import Enum
import numpy as np
class Polynomial(Enum):
"""Polynomial family defining interpolation nodes over an interval"""
GAUSS_LEGENDRE = 0
"""Gauss--Legendre 1D polynomial family (does not include endpoints)"""
LOBATTO_GAUSS_LEGENDRE = 1
"""Lobatto--Gauss--Legendre 1D polynomial family (includes endpoints)"""
EQUISPACED_CLOSED = 2
"""Closed 1D polynomial family with uniformly distributed nodes (includes endpoints)"""
EQUISPACED_OPEN = 3
"""Open 1D polynomial family with uniformly distributed nodes (does not include endpoints)"""
def __str__(self):
return self.name
def is_closed(family: Polynomial):
"""Whether the polynomial roots include interval endpoints"""
return family == Polynomial.LOBATTO_GAUSS_LEGENDRE or family == Polynomial.EQUISPACED_CLOSED
def _gauss_legendre_quadrature_1d(n: int):
if n == 1:
coords = [0.0]
weights = [2.0]
elif n == 2:
coords = [-math.sqrt(1.0 / 3), math.sqrt(1.0 / 3)]
weights = [1.0, 1.0]
elif n == 3:
coords = [0.0, -math.sqrt(3.0 / 5.0), math.sqrt(3.0 / 5.0)]
weights = [8.0 / 9.0, 5.0 / 9.0, 5.0 / 9.0]
elif n == 4:
c_a = math.sqrt(3.0 / 7.0 - 2.0 / 7.0 * math.sqrt(6.0 / 5.0))
c_b = math.sqrt(3.0 / 7.0 + 2.0 / 7.0 * math.sqrt(6.0 / 5.0))
w_a = (18.0 + math.sqrt(30.0)) / 36.0
w_b = (18.0 - math.sqrt(30.0)) / 36.0
coords = [c_a, -c_a, c_b, -c_b]
weights = [w_a, w_a, w_b, w_b]
elif n == 5:
c_a = 1.0 / 3.0 * math.sqrt(5.0 - 2.0 * math.sqrt(10.0 / 7.0))
c_b = 1.0 / 3.0 * math.sqrt(5.0 + 2.0 * math.sqrt(10.0 / 7.0))
w_a = (322.0 + 13.0 * math.sqrt(70.0)) / 900.0
w_b = (322.0 - 13.0 * math.sqrt(70.0)) / 900.0
coords = [0.0, c_a, -c_a, c_b, -c_b]
weights = [128.0 / 225.0, w_a, w_a, w_b, w_b]
else:
raise NotImplementedError
# Shift from [-1, 1] to [0, 1]
weights = 0.5 * np.array(weights)
coords = 0.5 * np.array(coords) + 0.5
return coords, weights
def _lobatto_gauss_legendre_quadrature_1d(n: int):
if n == 2:
coords = [-1.0, 1.0]
weights = [1.0, 1.0]
elif n == 3:
coords = [-1.0, 0.0, 1.0]
weights = [1.0 / 3.0, 4.0 / 3.0, 1.0 / 3.0]
elif n == 4:
coords = [-1.0, -1.0 / math.sqrt(5.0), 1.0 / math.sqrt(5.0), 1.0]
weights = [1.0 / 6.0, 5.0 / 6.0, 5.0 / 6.0, 1.0 / 6.0]
elif n == 5:
coords = [-1.0, -math.sqrt(3.0 / 7.0), 0.0, math.sqrt(3.0 / 7.0), 1.0]
weights = [1.0 / 10.0, 49.0 / 90.0, 32.0 / 45.0, 49.0 / 90.0, 1.0 / 10.0]
else:
raise NotImplementedError
# Shift from [-1, 1] to [0, 1]
weights = 0.5 * np.array(weights)
coords = 0.5 * np.array(coords) + 0.5
return coords, weights
def _uniform_open_quadrature_1d(n: int):
step = 1.0 / (n + 1)
coords = np.linspace(step, 1.0 - step, n)
weights = np.full(n, 1.0 / (n + 1))
# Boundaries have 3/2 the weight
weights[0] = 1.5 / (n + 1)
weights[-1] = 1.5 / (n + 1)
return coords, weights
def _uniform_closed_quadrature_1d(n: int):
coords = np.linspace(0.0, 1.0, n)
weights = np.full(n, 1.0 / (n - 1))
# Boundaries have half the weight
weights[0] = 0.5 / (n - 1)
weights[-1] = 0.5 / (n - 1)
return coords, weights
def _open_newton_cotes_quadrature_1d(n: int):
step = 1.0 / (n + 1)
coords = np.linspace(step, 1.0 - step, n)
# Weisstein, Eric W. "Newton-Cotes Formulas." From MathWorld--A Wolfram Web Resource.
# https://mathworld.wolfram.com/Newton-CotesFormulas.html
if n == 1:
weights = np.array([1.0])
elif n == 2:
weights = np.array([0.5, 0.5])
elif n == 3:
weights = np.array([2.0, -1.0, 2.0]) / 3.0
elif n == 4:
weights = np.array([11.0, 1.0, 1.0, 11.0]) / 24.0
elif n == 5:
weights = np.array([11.0, -14.0, 26.0, -14.0, 11.0]) / 20.0
elif n == 6:
weights = np.array([611.0, -453.0, 562.0, 562.0, -453.0, 611.0]) / 1440.0
elif n == 7:
weights = np.array([460.0, -954.0, 2196.0, -2459.0, 2196.0, -954.0, 460.0]) / 945.0
else:
raise NotImplementedError
return coords, weights
def _closed_newton_cotes_quadrature_1d(n: int):
coords = np.linspace(0.0, 1.0, n)
# OEIS: A093735, A093736
if n == 2:
weights = np.array([1.0, 1.0]) / 2.0
elif n == 3:
weights = np.array([1.0, 4.0, 1.0]) / 3.0
elif n == 4:
weights = np.array([3.0, 9.0, 9.0, 3.0]) / 8.0
elif n == 5:
weights = np.array([14.0, 64.0, 24.0, 64.0, 14.0]) / 45.0
elif n == 6:
weights = np.array([95.0 / 288.0, 125.0 / 96.0, 125.0 / 144.0, 125.0 / 144.0, 125.0 / 96.0, 95.0 / 288.0])
elif n == 7:
weights = np.array([41, 54, 27, 68, 27, 54, 41], dtype=float) / np.array(
[140, 35, 140, 35, 140, 35, 140], dtype=float
)
elif n == 8:
weights = np.array(
[
5257,
25039,
343,
20923,
20923,
343,
25039,
5257,
]
) / np.array(
[
17280,
17280,
640,
17280,
17280,
640,
17280,
17280,
],
dtype=float,
)
else:
raise NotImplementedError
# Normalize with interval length
weights = weights / (n - 1)
return coords, weights
def quadrature_1d(point_count: int, family: Polynomial):
"""Return quadrature points and weights for the given family and point count"""
if family == Polynomial.GAUSS_LEGENDRE:
return _gauss_legendre_quadrature_1d(point_count)
if family == Polynomial.LOBATTO_GAUSS_LEGENDRE:
return _lobatto_gauss_legendre_quadrature_1d(point_count)
if family == Polynomial.EQUISPACED_CLOSED:
return _closed_newton_cotes_quadrature_1d(point_count)
if family == Polynomial.EQUISPACED_OPEN:
return _open_newton_cotes_quadrature_1d(point_count)
raise NotImplementedError
def lagrange_scales(coords: np.array):
"""Return the scaling factors for Lagrange polynomials with roots at coords"""
lagrange_scale = np.empty_like(coords)
for i in range(len(coords)):
deltas = coords[i] - coords
deltas[i] = 1.0
lagrange_scale[i] = 1.0 / np.prod(deltas)
return lagrange_scale
| 6,565 | Python | 29.539535 | 114 | 0.529322 |
NVIDIA/warp/warp/fem/cache.py | import bisect
import re
from copy import copy
from typing import Any, Callable, Dict, Optional, Tuple, Union
import warp as wp
_kernel_cache = {}
_struct_cache = {}
_func_cache = {}
_key_re = re.compile("[^0-9a-zA-Z_]+")
def _make_key(obj, suffix: str, use_qualified_name):
base_name = f"{obj.__module__}.{obj.__qualname__}" if use_qualified_name else obj.__name__
return _key_re.sub("", f"{base_name}_{suffix}")
def get_func(func, suffix: str, use_qualified_name: bool = False):
key = _make_key(func, suffix, use_qualified_name)
if key not in _func_cache:
_func_cache[key] = wp.Function(
func=func,
key=key,
namespace="",
module=wp.get_module(
func.__module__,
),
)
return _func_cache[key]
def dynamic_func(suffix: str, use_qualified_name=False):
def wrap_func(func: Callable):
return get_func(func, suffix=suffix, use_qualified_name=use_qualified_name)
return wrap_func
def get_kernel(
func,
suffix: str,
use_qualified_name: bool = False,
kernel_options: Dict[str, Any] = None,
):
if kernel_options is None:
kernel_options = {}
key = _make_key(func, suffix, use_qualified_name)
if key not in _kernel_cache:
# Avoid creating too long file names -- can lead to issues on Windows
# We could hash the key, but prefer to keep it human-readable
module_name = f"{func.__module__}.dyn.{key}"
module_name = module_name[:128] if len(module_name) > 128 else module_name
module = wp.get_module(module_name)
module.options = copy(wp.get_module(func.__module__).options)
module.options.update(kernel_options)
_kernel_cache[key] = wp.Kernel(func=func, key=key, module=module)
return _kernel_cache[key]
def dynamic_kernel(suffix: str, use_qualified_name=False, kernel_options: Dict[str, Any] = None):
if kernel_options is None:
kernel_options = {}
def wrap_kernel(func: Callable):
return get_kernel(func, suffix=suffix, use_qualified_name=use_qualified_name, kernel_options=kernel_options)
return wrap_kernel
def get_struct(struct: type, suffix: str, use_qualified_name: bool = False):
key = _make_key(struct, suffix, use_qualified_name)
# used in codegen
struct.__qualname__ = key
if key not in _struct_cache:
module = wp.get_module(struct.__module__)
_struct_cache[key] = wp.codegen.Struct(
cls=struct,
key=key,
module=module,
)
return _struct_cache[key]
def dynamic_struct(suffix: str, use_qualified_name=False):
def wrap_struct(struct: type):
return get_struct(struct, suffix=suffix, use_qualified_name=use_qualified_name)
return wrap_struct
def get_integrand_function(
integrand: "warp.fem.operator.Integrand", # noqa: F821
suffix: str,
func=None,
annotations=None,
code_transformers=None,
):
if code_transformers is None:
code_transformers = []
key = _make_key(integrand.func, suffix, use_qualified_name=True)
if key not in _func_cache:
_func_cache[key] = wp.Function(
func=integrand.func if func is None else func,
key=key,
namespace="",
module=integrand.module,
overloaded_annotations=annotations,
code_transformers=code_transformers,
)
return _func_cache[key]
def get_integrand_kernel(
integrand: "warp.fem.operator.Integrand", # noqa: F821
suffix: str,
kernel_fn: Optional[Callable] = None,
kernel_options: Dict[str, Any] = None,
code_transformers=None,
):
if kernel_options is None:
kernel_options = {}
if code_transformers is None:
code_transformers = []
key = _make_key(integrand.func, suffix, use_qualified_name=True)
if key not in _kernel_cache:
if kernel_fn is None:
return None
module = wp.get_module(f"{integrand.module.name}.{integrand.name}")
module.options = copy(integrand.module.options)
module.options.update(kernel_options)
_kernel_cache[key] = wp.Kernel(func=kernel_fn, key=key, module=module, code_transformers=code_transformers)
return _kernel_cache[key]
def cached_arg_value(func: Callable):
"""Decorator to be applied to member methods assembling Arg structs, so that the result gets
automatically cached for the lifetime of the parent object
"""
cache_attr = f"_{func.__name__}_cache"
def get_arg(obj, device):
if not hasattr(obj, cache_attr):
setattr(obj, cache_attr, {})
cache = getattr(obj, cache_attr, {})
device = wp.get_device(device)
if device.ordinal not in cache:
cache[device.ordinal] = func(obj, device)
return cache[device.ordinal]
return get_arg
_cached_vec_types = {}
_cached_mat_types = {}
def cached_vec_type(length, dtype):
key = (length, dtype)
if key not in _cached_vec_types:
_cached_vec_types[key] = wp.vec(length=length, dtype=dtype)
return _cached_vec_types[key]
def cached_mat_type(shape, dtype):
key = (*shape, dtype)
if key not in _cached_mat_types:
_cached_mat_types[key] = wp.mat(shape=shape, dtype=dtype)
return _cached_mat_types[key]
class Temporary:
"""Handle over a temporary array from a :class:`TemporaryStore`.
The array will be automatically returned to the temporary pool for reuse upon destruction of this object, unless
the temporary is explicitly detached from the pool using :meth:`detach`.
The temporary may also be explicitly returned to the pool before destruction using :meth:`release`.
"""
def __init__(self, array: wp.array, pool: Optional["TemporaryStore.Pool"] = None, shape=None, dtype=None):
self._raw_array = array
self._array_view = array
self._pool = pool
if shape is not None or dtype is not None:
self._view_as(shape=shape, dtype=dtype)
def detach(self) -> wp.array:
"""Detaches the temporary so it is never returned to the pool"""
if self._pool is not None:
self._pool.detach(self._raw_array)
self._pool = None
return self._array_view
def release(self):
"""Returns the temporary array to the pool"""
if self._pool is not None:
self._pool.redeem(self._raw_array)
self._pool = None
@property
def array(self) -> wp.array:
"""View of the array with desired shape and data type."""
return self._array_view
def _view_as(self, shape, dtype) -> "Temporary":
def _view_reshaped_truncated(array):
view = wp.types.array(
ptr=array.ptr,
dtype=dtype,
shape=shape,
device=array.device,
pinned=array.pinned,
capacity=array.capacity,
copy=False,
grad=None if array.grad is None else _view_reshaped_truncated(array.grad),
)
view._ref = array
return view
self._array_view = _view_reshaped_truncated(self._raw_array)
return self
def __del__(self):
self.release()
class TemporaryStore:
"""
Shared pool of temporary arrays that will be persisted and reused across invocations of ``warp.fem`` functions.
A :class:`TemporaryStore` instance may either be passed explicitly to ``warp.fem`` functions that accept such an argument, for instance :func:`.integrate.integrate`,
or can be set globally as the default store using :func:`set_default_temporary_store`.
By default, there is no default temporary store, so that temporary allocations are not persisted.
"""
_default_store: "TemporaryStore" = None
class Pool:
def __init__(self, dtype, device, pinned: bool):
self.dtype = dtype
self.device = device
self.pinned = pinned
self._pool = [] # Currently available arrays for borrowing, ordered by size
self._pool_sizes = [] # Sizes of available arrays for borrowing, ascending
self._allocs = {} # All allocated arrays, including borrowed ones
def borrow(self, shape, dtype, requires_grad: bool):
size = 1
if isinstance(shape, int):
shape = (shape,)
for d in shape:
size *= d
index = bisect.bisect_left(
a=self._pool_sizes,
x=size,
)
if index < len(self._pool):
# Big enough array found, remove from pool
array = self._pool.pop(index)
self._pool_sizes.pop(index)
if requires_grad and array.grad is None:
array.requires_grad = True
return Temporary(pool=self, array=array, shape=shape, dtype=dtype)
# No big enough array found, allocate new one
if len(self._pool) > 0:
grow_factor = 1.5
size = max(int(self._pool_sizes[-1] * grow_factor), size)
array = wp.empty(
shape=(size,), dtype=self.dtype, pinned=self.pinned, device=self.device, requires_grad=requires_grad
)
self._allocs[array.ptr] = array
return Temporary(pool=self, array=array, shape=shape, dtype=dtype)
def redeem(self, array):
# Insert back array into available pool
index = bisect.bisect_left(
a=self._pool_sizes,
x=array.size,
)
self._pool.insert(index, array)
self._pool_sizes.insert(index, array.size)
def detach(self, array):
del self._allocs[array.ptr]
def __init__(self):
self.clear()
def clear(self):
self._temporaries = {}
def borrow(self, shape, dtype, pinned: bool = False, device=None, requires_grad: bool = False) -> Temporary:
dtype = wp.types.type_to_warp(dtype)
device = wp.get_device(device)
type_length = wp.types.type_length(dtype)
key = (dtype._type_, type_length, pinned, device.ordinal)
pool = self._temporaries.get(key, None)
if pool is None:
value_type = (
cached_vec_type(length=type_length, dtype=wp.types.type_scalar_type(dtype))
if type_length > 1
else dtype
)
pool = TemporaryStore.Pool(value_type, device, pinned=pinned)
self._temporaries[key] = pool
return pool.borrow(dtype=dtype, shape=shape, requires_grad=requires_grad)
def set_default_temporary_store(temporary_store: Optional[TemporaryStore]):
"""Globally sets the default :class:`TemporaryStore` instance to use for temporary allocations in ``warp.fem`` functions.
If the default temporary store is set to ``None``, temporary allocations are not persisted unless a :class:`TemporaryStore` is provided at a per-function granularity.
"""
TemporaryStore._default_store = temporary_store
def borrow_temporary(
temporary_store: Optional[TemporaryStore],
shape: Union[int, Tuple[int]],
dtype: type,
pinned: bool = False,
requires_grad: bool = False,
device=None,
) -> Temporary:
"""
Borrows and returns a temporary array with specified attributes from a shared pool.
If an array with sufficient capacity and matching desired attributes is already available in the pool, it will be returned.
Otherwise, a new allocation will be performed.
Args:
temporary_store: the shared pool to borrow the temporary from. If `temporary_store` is ``None``, the global default temporary store, if set, will be used.
shape: desired dimensions for the temporary array
dtype: desired data type for the temporary array
pinned: whether a pinned allocation is desired
device: device on which the memory should be allocated; if ``None``, the current device will be used.
"""
if temporary_store is None:
temporary_store = TemporaryStore._default_store
if temporary_store is None:
return Temporary(
array=wp.empty(shape=shape, dtype=dtype, pinned=pinned, device=device, requires_grad=requires_grad)
)
return temporary_store.borrow(shape=shape, dtype=dtype, device=device, pinned=pinned, requires_grad=requires_grad)
def borrow_temporary_like(
array: Union[wp.array, Temporary],
temporary_store: Optional[TemporaryStore],
) -> Temporary:
"""
Borrows and returns a temporary array with the same attributes as another array or temporary.
Args:
array: Warp or temporary array to read the desired attributes from
temporary_store: the shared pool to borrow the temporary from. If `temporary_store` is ``None``, the global default temporary store, if set, will be used.
"""
if isinstance(array, Temporary):
array = array.array
return borrow_temporary(
temporary_store=temporary_store,
shape=array.shape,
dtype=array.dtype,
pinned=array.pinned,
device=array.device,
requires_grad=array.requires_grad,
)
| 13,321 | Python | 31.975247 | 170 | 0.622251 |
NVIDIA/warp/warp/fem/__init__.py | from .cache import TemporaryStore, borrow_temporary, borrow_temporary_like, set_default_temporary_store
from .dirichlet import normalize_dirichlet_projector, project_linear_system
from .domain import BoundarySides, Cells, FrontierSides, GeometryDomain, Sides
from .field import DiscreteField, FieldLike, make_restriction, make_test, make_trial
from .geometry import (
ExplicitGeometryPartition,
Geometry,
GeometryPartition,
Grid2D,
Grid3D,
Hexmesh,
LinearGeometryPartition,
Nanogrid,
Quadmesh2D,
Tetmesh,
Trimesh2D,
)
from .integrate import integrate, interpolate
from .operator import (
D,
at_node,
average,
curl,
deformation_gradient,
degree,
div,
div_outer,
grad,
grad_average,
grad_jump,
grad_outer,
inner,
integrand,
jump,
lookup,
measure,
measure_ratio,
normal,
outer,
position,
)
from .polynomial import Polynomial
from .quadrature import ExplicitQuadrature, NodalQuadrature, PicQuadrature, Quadrature, RegularQuadrature
from .space import (
BasisSpace,
DofMapper,
ElementBasis,
FunctionSpace,
PointBasisSpace,
SkewSymmetricTensorMapper,
SpacePartition,
SpaceRestriction,
SpaceTopology,
SymmetricTensorMapper,
make_collocated_function_space,
make_polynomial_basis_space,
make_polynomial_space,
make_space_partition,
make_space_restriction,
)
from .types import Coords, Domain, ElementIndex, Field, Sample
| 1,500 | Python | 23.209677 | 105 | 0.72 |
NVIDIA/warp/warp/fem/utils.py | from typing import Any, Tuple
import numpy as np
import warp as wp
from warp.fem.cache import (
Temporary,
TemporaryStore,
borrow_temporary,
borrow_temporary_like,
)
from warp.utils import array_scan, radix_sort_pairs, runlength_encode
@wp.func
def generalized_outer(x: Any, y: Any):
"""Generalized outer product allowing for the first argument to be a scalar"""
return wp.outer(x, y)
@wp.func
def generalized_outer(x: wp.float32, y: wp.vec2):
return x * y
@wp.func
def generalized_outer(x: wp.float32, y: wp.vec3):
return x * y
@wp.func
def generalized_inner(x: Any, y: Any):
"""Generalized inner product allowing for the first argument to be a tensor"""
return wp.dot(x, y)
@wp.func
def generalized_inner(x: wp.mat22, y: wp.vec2):
return x[0] * y[0] + x[1] * y[1]
@wp.func
def generalized_inner(x: wp.mat33, y: wp.vec3):
return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]
@wp.func
def apply_right(x: Any, y: Any):
"""Performs x y multiplication with y a square matrix and x either a row-vector or a matrix.
Will be removed once native @ operator is implemented.
"""
return x * y
@wp.func
def apply_right(x: wp.vec2, y: wp.mat22):
return x[0] * y[0] + x[1] * y[1]
@wp.func
def apply_right(x: wp.vec3, y: wp.mat33):
return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]
@wp.func
def unit_element(template_type: Any, coord: int):
"""Returns a instance of `template_type` with a single coordinate set to 1 in the canonical basis"""
t = type(template_type)(0.0)
t[coord] = 1.0
return t
@wp.func
def unit_element(template_type: wp.float32, coord: int):
return 1.0
@wp.func
def unit_element(template_type: wp.mat22, coord: int):
t = wp.mat22(0.0)
row = coord // 2
col = coord - 2 * row
t[row, col] = 1.0
return t
@wp.func
def unit_element(template_type: wp.mat33, coord: int):
t = wp.mat33(0.0)
row = coord // 3
col = coord - 3 * row
t[row, col] = 1.0
return t
@wp.func
def symmetric_part(x: Any):
"""Symmetric part of a square tensor"""
return 0.5 * (x + wp.transpose(x))
@wp.func
def skew_part(x: wp.mat22):
"""Skew part of a 2x2 tensor as corresponding rotation angle"""
return 0.5 * (x[1, 0] - x[0, 1])
@wp.func
def skew_part(x: wp.mat33):
"""Skew part of a 3x3 tensor as the corresponding rotation vector"""
a = 0.5 * (x[2, 1] - x[1, 2])
b = 0.5 * (x[0, 2] - x[2, 0])
c = 0.5 * (x[1, 0] - x[0, 1])
return wp.vec3(a, b, c)
def compress_node_indices(
node_count: int, node_indices: wp.array(dtype=int), temporary_store: TemporaryStore = None
) -> Tuple[Temporary, Temporary, int, Temporary]:
"""
Compress an unsorted list of node indices into:
- a node_offsets array, giving for each node the start offset of corresponding indices in sorted_array_indices
- a sorted_array_indices array, listing the indices in the input array corresponding to each node
- the number of unique node indices
- a unique_node_indices array containing the sorted list of unique node indices (i.e. the list of indices i for which node_offsets[i] < node_offsets[i+1])
"""
index_count = node_indices.size
sorted_node_indices_temp = borrow_temporary(
temporary_store, shape=2 * index_count, dtype=int, device=node_indices.device
)
sorted_array_indices_temp = borrow_temporary_like(sorted_node_indices_temp, temporary_store)
sorted_node_indices = sorted_node_indices_temp.array
sorted_array_indices = sorted_array_indices_temp.array
wp.copy(dest=sorted_node_indices, src=node_indices, count=index_count)
indices_per_element = 1 if node_indices.ndim == 1 else node_indices.shape[-1]
wp.launch(
kernel=_iota_kernel,
dim=index_count,
inputs=[sorted_array_indices, indices_per_element],
device=sorted_array_indices.device,
)
# Sort indices
radix_sort_pairs(sorted_node_indices, sorted_array_indices, count=index_count)
# Build prefix sum of number of elements per node
unique_node_indices_temp = borrow_temporary(
temporary_store, shape=index_count, dtype=int, device=node_indices.device
)
node_element_counts_temp = borrow_temporary(
temporary_store, shape=index_count, dtype=int, device=node_indices.device
)
unique_node_indices = unique_node_indices_temp.array
node_element_counts = node_element_counts_temp.array
unique_node_count_dev = borrow_temporary(temporary_store, shape=(1,), dtype=int, device=sorted_node_indices.device)
runlength_encode(
sorted_node_indices,
unique_node_indices,
node_element_counts,
value_count=index_count,
run_count=unique_node_count_dev.array,
)
# Transfer unique node count to host
if node_indices.device.is_cuda:
unique_node_count_host = borrow_temporary(temporary_store, shape=(1,), dtype=int, pinned=True, device="cpu")
wp.copy(src=unique_node_count_dev.array, dest=unique_node_count_host.array, count=1)
wp.synchronize_stream(wp.get_stream(node_indices.device))
unique_node_count_dev.release()
unique_node_count = int(unique_node_count_host.array.numpy()[0])
unique_node_count_host.release()
else:
unique_node_count = int(unique_node_count_dev.array.numpy()[0])
unique_node_count_dev.release()
# Scatter seen run counts to global array of element count per node
node_offsets_temp = borrow_temporary(
temporary_store, shape=(node_count + 1), device=node_element_counts.device, dtype=int
)
node_offsets = node_offsets_temp.array
node_offsets.zero_()
wp.launch(
kernel=_scatter_node_counts,
dim=unique_node_count,
inputs=[node_element_counts, unique_node_indices, node_offsets],
device=node_offsets.device,
)
# Prefix sum of number of elements per node
array_scan(node_offsets, node_offsets, inclusive=True)
sorted_node_indices_temp.release()
node_element_counts_temp.release()
return node_offsets_temp, sorted_array_indices_temp, unique_node_count, unique_node_indices_temp
def masked_indices(
mask: wp.array, missing_index=-1, temporary_store: TemporaryStore = None
) -> Tuple[Temporary, Temporary]:
"""
From an array of boolean masks (must be either 0 or 1), returns:
- The list of indices for which the mask is 1
- A map associating to each element of the input mask array its local index if non-zero, or missing_index if zero.
"""
offsets_temp = borrow_temporary_like(mask, temporary_store)
offsets = offsets_temp.array
wp.utils.array_scan(mask, offsets, inclusive=True)
# Get back total counts on host
if offsets.device.is_cuda:
masked_count_temp = borrow_temporary(temporary_store, shape=1, dtype=int, pinned=True, device="cpu")
wp.copy(dest=masked_count_temp.array, src=offsets, src_offset=offsets.shape[0] - 1, count=1)
wp.synchronize_stream(wp.get_stream(offsets.device))
masked_count = int(masked_count_temp.array.numpy()[0])
masked_count_temp.release()
else:
masked_count = int(offsets.numpy()[-1])
# Convert counts to indices
indices_temp = borrow_temporary(temporary_store, shape=masked_count, device=mask.device, dtype=int)
wp.launch(
kernel=_masked_indices_kernel,
dim=offsets.shape,
inputs=[missing_index, mask, offsets, indices_temp.array, offsets],
device=mask.device,
)
return indices_temp, offsets_temp
def array_axpy(x: wp.array, y: wp.array, alpha: float = 1.0, beta: float = 1.0):
"""Performs y = alpha*x + beta*y"""
dtype = wp.types.type_scalar_type(x.dtype)
alpha = dtype(alpha)
beta = dtype(beta)
if not wp.types.types_equal(x.dtype, y.dtype) or x.shape != y.shape or x.device != y.device:
raise ValueError("x and y arrays must have same dat atype, shape and device")
wp.launch(kernel=_array_axpy_kernel, dim=x.shape, device=x.device, inputs=[x, y, alpha, beta])
@wp.kernel
def _iota_kernel(indices: wp.array(dtype=int), divisor: int):
indices[wp.tid()] = wp.tid() // divisor
@wp.kernel
def _scatter_node_counts(
unique_counts: wp.array(dtype=int), unique_node_indices: wp.array(dtype=int), node_counts: wp.array(dtype=int)
):
i = wp.tid()
node_counts[1 + unique_node_indices[i]] = unique_counts[i]
@wp.kernel
def _masked_indices_kernel(
missing_index: int,
mask: wp.array(dtype=int),
offsets: wp.array(dtype=int),
masked_to_global: wp.array(dtype=int),
global_to_masked: wp.array(dtype=int),
):
i = wp.tid()
if mask[i] == 0:
global_to_masked[i] = missing_index
else:
masked_idx = offsets[i] - 1
global_to_masked[i] = masked_idx
masked_to_global[masked_idx] = i
@wp.kernel
def _array_axpy_kernel(x: wp.array(dtype=Any), y: wp.array(dtype=Any), alpha: Any, beta: Any):
i = wp.tid()
y[i] = beta * y[i] + alpha * x[i]
def grid_to_tris(Nx: int, Ny: int):
"""Constructs a triangular mesh topology by dividing each cell of a dense 2D grid into two triangles.
The resulting triangles will be oriented counter-clockwise assuming that `y` is the fastest moving index direction
Args:
Nx: Resolution of the grid along `x` dimension
Ny: Resolution of the grid along `y` dimension
Returns:
Array of shape (2 * Nx * Ny, 3) containing vertex indices for each triangle
"""
cx, cy = np.meshgrid(np.arange(Nx, dtype=int), np.arange(Ny, dtype=int), indexing="ij")
vidx = np.transpose(
np.array(
[
(Ny + 1) * cx + cy,
(Ny + 1) * (cx + 1) + cy,
(Ny + 1) * (cx + 1) + (cy + 1),
(Ny + 1) * cx + cy,
(Ny + 1) * (cx + 1) + (cy + 1),
(Ny + 1) * (cx) + (cy + 1),
]
)
).reshape((-1, 3))
return vidx
def grid_to_tets(Nx: int, Ny: int, Nz: int):
"""Constructs a tetrahedral mesh topology by diving each cell of a dense 3D grid into five tetrahedrons
The resulting tets have positive volume assuming that `z` is the fastest moving index direction
Args:
Nx: Resolution of the grid along `x` dimension
Ny: Resolution of the grid along `y` dimension
Nz: Resolution of the grid along `z` dimension
Returns:
Array of shape (5 * Nx * Ny * Nz, 4) containing vertex indices for each tet
"""
# Global node indices for each cell
cx, cy, cz = np.meshgrid(
np.arange(Nx, dtype=int), np.arange(Ny, dtype=int), np.arange(Nz, dtype=int), indexing="ij"
)
grid_vidx = np.array(
[
(Ny + 1) * (Nz + 1) * cx + (Nz + 1) * cy + cz,
(Ny + 1) * (Nz + 1) * cx + (Nz + 1) * cy + cz + 1,
(Ny + 1) * (Nz + 1) * cx + (Nz + 1) * (cy + 1) + cz,
(Ny + 1) * (Nz + 1) * cx + (Nz + 1) * (cy + 1) + cz + 1,
(Ny + 1) * (Nz + 1) * (cx + 1) + (Nz + 1) * cy + cz,
(Ny + 1) * (Nz + 1) * (cx + 1) + (Nz + 1) * cy + cz + 1,
(Ny + 1) * (Nz + 1) * (cx + 1) + (Nz + 1) * (cy + 1) + cz,
(Ny + 1) * (Nz + 1) * (cx + 1) + (Nz + 1) * (cy + 1) + cz + 1,
]
)
# decompose grid cells into 5 tets
tet_vidx = np.array(
[
[0, 1, 2, 4],
[3, 2, 1, 7],
[5, 1, 7, 4],
[6, 7, 4, 2],
[4, 1, 2, 7],
]
)
# Convert to 3d index coordinates
vidx_coords = np.array(
[
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1],
]
)
tet_coords = vidx_coords[tet_vidx]
# Symmetry bits for each cell
ox, oy, oz = np.meshgrid(
np.arange(Nx, dtype=int) % 2, np.arange(Ny, dtype=int) % 2, np.arange(Nz, dtype=int) % 2, indexing="ij"
)
tet_coords = np.broadcast_to(tet_coords, shape=(*ox.shape, *tet_coords.shape))
# Flip coordinates according to symmetry
ox_bk = np.broadcast_to(ox.reshape(*ox.shape, 1, 1), tet_coords.shape[:-1])
oy_bk = np.broadcast_to(oy.reshape(*oy.shape, 1, 1), tet_coords.shape[:-1])
oz_bk = np.broadcast_to(oz.reshape(*oz.shape, 1, 1), tet_coords.shape[:-1])
tet_coords_x = tet_coords[..., 0] ^ ox_bk
tet_coords_y = tet_coords[..., 1] ^ oy_bk
tet_coords_z = tet_coords[..., 2] ^ oz_bk
# Back to local vertex indices
corner_indices = 4 * tet_coords_x + 2 * tet_coords_y + tet_coords_z
# Now go from cell-local to global node indices
# There must be a nicer way than this, but for small grids this works
corner_indices = corner_indices.reshape(-1, 4)
grid_vidx = grid_vidx.reshape((8, -1, 1))
grid_vidx = np.broadcast_to(grid_vidx, shape=(8, grid_vidx.shape[1], 5))
grid_vidx = grid_vidx.reshape((8, -1))
node_indices = np.arange(corner_indices.shape[0])
tet_grid_vidx = np.transpose(
[
grid_vidx[corner_indices[:, 0], node_indices],
grid_vidx[corner_indices[:, 1], node_indices],
grid_vidx[corner_indices[:, 2], node_indices],
grid_vidx[corner_indices[:, 3], node_indices],
]
)
return tet_grid_vidx
def grid_to_quads(Nx: int, Ny: int):
"""Constructs a quadrilateral mesh topology from a dense 2D grid
The resulting quads will be indexed counter-clockwise
Args:
Nx: Resolution of the grid along `x` dimension
Ny: Resolution of the grid along `y` dimension
Returns:
Array of shape (Nx * Ny, 4) containing vertex indices for each quadrilateral
"""
quad_vtx = np.array(
[
[0, 0],
[1, 0],
[1, 1],
[0, 1],
]
).T
quads = np.stack(np.meshgrid(np.arange(0, Nx), np.arange(0, Ny), indexing="ij"))
quads_vtx_shape = (*quads.shape, quad_vtx.shape[1])
quads_vtx = np.broadcast_to(quads.reshape(*quads.shape, 1), quads_vtx_shape) + np.broadcast_to(
quad_vtx.reshape(2, 1, 1, quad_vtx.shape[1]), quads_vtx_shape
)
quad_vtx_indices = quads_vtx[0] * (Ny + 1) + quads_vtx[1]
return quad_vtx_indices.reshape(-1, 4)
def grid_to_hexes(Nx: int, Ny: int, Nz: int):
"""Constructs a hexahedral mesh topology from a dense 3D grid
The resulting hexes will be indexed following usual convention assuming that `z` is the fastest moving index direction
(counter-clockwise bottom vertices, then counter-clockwise top vertices)
Args:
Nx: Resolution of the grid along `x` dimension
Ny: Resolution of the grid along `y` dimension
Nz: Resolution of the grid along `z` dimension
Returns:
Array of shape (Nx * Ny * Nz, 8) containing vertex indices for each hexaedron
"""
hex_vtx = np.array(
[
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1],
]
).T
hexes = np.stack(np.meshgrid(np.arange(0, Nx), np.arange(0, Ny), np.arange(0, Nz), indexing="ij"))
hexes_vtx_shape = (*hexes.shape, hex_vtx.shape[1])
hexes_vtx = np.broadcast_to(hexes.reshape(*hexes.shape, 1), hexes_vtx_shape) + np.broadcast_to(
hex_vtx.reshape(3, 1, 1, 1, hex_vtx.shape[1]), hexes_vtx_shape
)
hexes_vtx_indices = hexes_vtx[0] * (Nz + 1) * (Ny + 1) + hexes_vtx[1] * (Nz + 1) + hexes_vtx[2]
return hexes_vtx_indices.reshape(-1, 8)
| 15,630 | Python | 30.514113 | 159 | 0.603391 |
NVIDIA/warp/warp/fem/domain.py | from enum import Enum
from typing import Union
import warp as wp
import warp.codegen
import warp.context
from warp.fem.geometry import (
Element,
Geometry,
GeometryPartition,
WholeGeometryPartition,
)
GeometryOrPartition = Union[Geometry, GeometryPartition]
class GeometryDomain:
"""Interface class for domains, i.e. (partial) views of elements in a Geometry"""
class ElementKind(Enum):
"""Possible kinds of elements contained in a domain"""
CELL = 0
SIDE = 1
def __init__(self, geometry: GeometryOrPartition):
if isinstance(geometry, GeometryPartition):
self.geometry_partition = geometry
else:
self.geometry_partition = WholeGeometryPartition(geometry)
self.geometry = self.geometry_partition.geometry
@property
def name(self) -> str:
return f"{self.geometry_partition.name}_{self.__class__.__name__}"
def __str__(self) -> str:
return self.name
def __eq__(self, other) -> bool:
return self.__class__ == other.__class__ and self.geometry_partition == other.geometry_partition
@property
def element_kind(self) -> ElementKind:
"""Kind of elements that this domain contains (cells or sides)"""
raise NotImplementedError
@property
def dimension(self) -> int:
"""Dimension of the elements of the domain"""
raise NotImplementedError
def element_count(self) -> int:
"""Number of elements in the domain"""
raise NotImplementedError
def geometry_element_count(self) -> int:
"""Number of elements in the underlying geometry"""
return self.geometry.cell_count()
def reference_element(self) -> Element:
"""Protypical element"""
raise NotImplementedError
def element_index_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
"""Value of the argument to be passed to device functions"""
raise NotImplementedError
def element_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
"""Value of the argument to be passed to device functions"""
raise NotImplementedError
ElementIndexArg: warp.codegen.Struct
"""Structure containing arguments to be passed to device functions computing element indices"""
element_index: wp.Function
"""Device function for retrieving an ElementIndex from a linearized index"""
ElementArg: warp.codegen.Struct
"""Structure containing arguments to be passed to device functions computing element geometry"""
element_measure: wp.Function
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
element_measure_ratio: wp.Function
"""Device function returning the ratio of the measure of a side to that of its neighbour cells"""
element_position: wp.Function
"""Device function returning the element position at a sample point"""
element_deformation_gradient: wp.Function
"""Device function returning the gradient of the position with respect to the element's reference space"""
element_normal: wp.Function
"""Device function returning the element normal at a sample point"""
element_lookup: wp.Function
"""Device function returning the sample point corresponding to a world position"""
class Cells(GeometryDomain):
"""A Domain containing all cells of the geometry or geometry partition"""
def __init__(self, geometry: GeometryOrPartition):
super().__init__(geometry)
@property
def element_kind(self) -> GeometryDomain.ElementKind:
return GeometryDomain.ElementKind.CELL
@property
def dimension(self) -> int:
return self.geometry.dimension
def reference_element(self) -> Element:
return self.geometry.reference_cell()
def element_count(self) -> int:
return self.geometry_partition.cell_count()
def geometry_element_count(self) -> int:
return self.geometry.cell_count()
@property
def ElementIndexArg(self) -> warp.codegen.Struct:
return self.geometry_partition.CellArg
def element_index_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry_partition.cell_arg_value(device)
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.cell_index
def element_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry.cell_arg_value(device)
@property
def ElementArg(self) -> warp.codegen.Struct:
return self.geometry.CellArg
@property
def element_position(self) -> wp.Function:
return self.geometry.cell_position
@property
def element_deformation_gradient(self) -> wp.Function:
return self.geometry.cell_deformation_gradient
@property
def element_measure(self) -> wp.Function:
return self.geometry.cell_measure
@property
def element_measure_ratio(self) -> wp.Function:
return self.geometry.cell_measure_ratio
@property
def eval_normal(self) -> wp.Function:
return self.geometry.cell_normal
@property
def element_lookup(self) -> wp.Function:
return self.geometry.cell_lookup
class Sides(GeometryDomain):
"""A Domain containing all (interior and boundary) sides of the geometry or geometry partition"""
def __init__(self, geometry: GeometryOrPartition):
self.geometry = geometry
super().__init__(geometry)
@property
def element_kind(self) -> GeometryDomain.ElementKind:
return GeometryDomain.ElementKind.SIDE
@property
def dimension(self) -> int:
return self.geometry.dimension - 1
def reference_element(self) -> Element:
return self.geometry.reference_side()
def element_count(self) -> int:
return self.geometry_partition.side_count()
def geometry_element_count(self) -> int:
return self.geometry.side_count()
@property
def ElementIndexArg(self) -> warp.codegen.Struct:
return self.geometry_partition.SideArg
def element_index_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry_partition.side_arg_value(device)
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.side_index
@property
def ElementArg(self) -> warp.codegen.Struct:
return self.geometry.SideArg
def element_arg_value(self, device: warp.context.Devicelike) -> warp.codegen.StructInstance:
return self.geometry.side_arg_value(device)
@property
def element_position(self) -> wp.Function:
return self.geometry.side_position
@property
def element_deformation_gradient(self) -> wp.Function:
return self.geometry.side_deformation_gradient
@property
def element_measure(self) -> wp.Function:
return self.geometry.side_measure
@property
def element_measure_ratio(self) -> wp.Function:
return self.geometry.side_measure_ratio
@property
def eval_normal(self) -> wp.Function:
return self.geometry.side_normal
class BoundarySides(Sides):
"""A Domain containing boundary sides of the geometry or geometry partition"""
def __init__(self, geometry: GeometryOrPartition):
super().__init__(geometry)
def element_count(self) -> int:
return self.geometry_partition.boundary_side_count()
def geometry_element_count(self) -> int:
return self.geometry.boundary_side_count()
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.boundary_side_index
class FrontierSides(Sides):
"""A Domain containing frontier sides of the geometry partition (sides shared with at least another partition)"""
def __init__(self, geometry: GeometryOrPartition):
super().__init__(geometry)
def element_count(self) -> int:
return self.geometry_partition.frontier_side_count()
def geometry_element_count(self) -> int:
raise RuntimeError("Frontier sides not defined at the geometry level")
@property
def element_index(self) -> wp.Function:
return self.geometry_partition.frontier_side_index
| 8,366 | Python | 30.813688 | 117 | 0.687306 |
NVIDIA/warp/warp/fem/operator.py | import inspect
from typing import Any, Callable
import warp as wp
from warp.fem import utils
from warp.fem.types import Domain, Field, Sample
class Integrand:
"""An integrand is a device function containing arbitrary expressions over Field and Domain variables.
It will get transformed to a proper warp.Function by resolving concrete Field types at call time.
"""
def __init__(self, func: Callable):
self.func = func
self.name = wp.codegen.make_full_qualified_name(self.func)
self.module = wp.get_module(self.func.__module__)
self.argspec = inspect.getfullargspec(self.func)
class Operator:
"""
Operators provide syntaxic sugar over Field and Domain evaluation functions and arguments
"""
def __init__(self, func: Callable, resolver: Callable):
self.func = func
self.resolver = resolver
def integrand(func: Callable):
"""Decorator for functions to be integrated (or interpolated) using warp.fem"""
itg = Integrand(func)
itg.__doc__ = func.__doc__
return itg
def operator(resolver: Callable):
"""Decorator for functions operating on Field-like or Domain-like data inside warp.fem integrands"""
def wrap_operator(func: Callable):
op = Operator(func, resolver)
op.__doc__ = func.__doc__
return op
return wrap_operator
# Domain operators
@operator(resolver=lambda dmn: dmn.element_position)
def position(domain: Domain, s: Sample):
"""Evaluates the world position of the sample point `s`"""
pass
@operator(resolver=lambda dmn: dmn.eval_normal)
def normal(domain: Domain, s: Sample):
"""Evaluates the element normal at the sample point `s`. Null for interior points."""
pass
@operator(resolver=lambda dmn: dmn.element_deformation_gradient)
def deformation_gradient(domain: Domain, s: Sample):
"""Evaluates the gradient of the domain position with respect to the element reference space at the sample point `s`"""
pass
@operator(resolver=lambda dmn: dmn.element_lookup)
def lookup(domain: Domain, x: Any) -> Sample:
"""Looks-up the sample point corresponding to a world position `x`, projecting to the closest point on the domain.
Arg:
x: world position of the point to look-up in the geometry
guess: (optional) :class:`Sample` initial guess, may help perform the query
Notes:
Currently this operator is only fully supported for :class:`Grid2D` and :class:`Grid3D` geometries.
For :class:`TriangleMesh2D` and :class:`Tetmesh` geometries, the operator requires providing `guess`.
"""
pass
@operator(resolver=lambda dmn: dmn.element_measure)
def measure(domain: Domain, s: Sample) -> float:
"""Returns the measure (volume, area, or length) determinant of an element at a sample point `s`"""
pass
@operator(resolver=lambda dmn: dmn.element_measure_ratio)
def measure_ratio(domain: Domain, s: Sample) -> float:
"""Returns the maximum ratio between the measure of this element and that of higher-dimensional neighbours."""
pass
# Field operators
# On a side, inner and outer are such that normal goes from inner to outer
@operator(resolver=lambda f: f.eval_inner)
def inner(f: Field, s: Sample):
"""Evaluates the field at a sample point `s`. On oriented sides, uses the inner element"""
pass
@operator(resolver=lambda f: f.eval_grad_inner)
def grad(f: Field, s: Sample):
"""Evaluates the field gradient at a sample point `s`. On oriented sides, uses the inner element"""
pass
@operator(resolver=lambda f: f.eval_div_inner)
def div(f: Field, s: Sample):
"""Evaluates the field divergence at a sample point `s`. On oriented sides, uses the inner element"""
pass
@operator(resolver=lambda f: f.eval_outer)
def outer(f: Field, s: Sample):
"""Evaluates the field at a sample point `s`. On oriented sides, uses the outer element. On interior points and on domain boundaries, this is equivalent to :func:`inner`."""
pass
@operator(resolver=lambda f: f.eval_grad_outer)
def grad_outer(f: Field, s: Sample):
"""Evaluates the field gradient at a sample point `s`. On oriented sides, uses the outer element. On interior points and on domain boundaries, this is equivalent to :func:`grad`."""
pass
@operator(resolver=lambda f: f.eval_grad_outer)
def div_outer(f: Field, s: Sample):
"""Evaluates the field divergence at a sample point `s`. On oriented sides, uses the outer element. On interior points and on domain boundaries, this is equivalent to :func:`div`."""
pass
@operator(resolver=lambda f: f.eval_degree)
def degree(f: Field):
"""Polynomial degree of a field"""
pass
@operator(resolver=lambda f: f.at_node)
def at_node(f: Field, s: Sample):
"""For a Test or Trial field, returns a copy of the Sample `s` moved to the coordinates of the node being evaluated"""
pass
# Common derived operators, for convenience
@integrand
def D(f: Field, s: Sample):
"""Symmetric part of the (inner) gradient of the field at `s`"""
return utils.symmetric_part(grad(f, s))
@integrand
def curl(f: Field, s: Sample):
"""Skew part of the (inner) gradient of the field at `s`, as a vector such that ``wp.cross(curl(u), v) = skew(grad(u)) v``"""
return utils.skew_part(grad(f, s))
@integrand
def jump(f: Field, s: Sample):
"""Jump between inner and outer element values on an interior side. Zero for interior points or domain boundaries"""
return inner(f, s) - outer(f, s)
@integrand
def average(f: Field, s: Sample):
"""Average between inner and outer element values"""
return 0.5 * (inner(f, s) + outer(f, s))
@integrand
def grad_jump(f: Field, s: Sample):
"""Jump between inner and outer element gradients on an interior side. Zero for interior points or domain boundaries"""
return grad(f, s) - grad_outer(f, s)
@integrand
def grad_average(f: Field, s: Sample):
"""Average between inner and outer element gradients"""
return 0.5 * (grad(f, s) + grad_outer(f, s))
# Set default call operators for argument types, so that field(s) = inner(field, s) and domain(s) = position(domain, s)
Field.call_operator = inner
Domain.call_operator = position
| 6,207 | Python | 31.502618 | 186 | 0.697116 |
NVIDIA/warp/warp/fem/dirichlet.py | from typing import Any, Optional
import warp as wp
from warp.sparse import BsrMatrix, bsr_assign, bsr_axpy, bsr_copy, bsr_mm, bsr_mv
from warp.types import type_is_matrix, type_length
from .utils import array_axpy
def normalize_dirichlet_projector(projector_matrix: BsrMatrix, fixed_value: Optional[wp.array] = None):
"""
Scale projector so that it becomes idempotent, and apply the same scaling to fixed_value if provided
"""
if projector_matrix.nrow < projector_matrix.nnz or projector_matrix.ncol != projector_matrix.nrow:
raise ValueError("Projector must be a square diagonal matrix, with at most one non-zero block per row")
# Cast blocks to matrix type if necessary
projector_values = projector_matrix.values
if not type_is_matrix(projector_values.dtype):
projector_values = wp.array(
data=None,
ptr=projector_values.ptr,
capacity=projector_values.capacity,
device=projector_values.device,
dtype=wp.mat(shape=projector_matrix.block_shape, dtype=projector_matrix.scalar_type),
shape=projector_values.shape[0],
)
if fixed_value is None:
wp.launch(
kernel=_normalize_dirichlet_projector_kernel,
dim=projector_matrix.nrow,
device=projector_values.device,
inputs=[projector_matrix.offsets, projector_matrix.columns, projector_values],
)
else:
if fixed_value.shape[0] != projector_matrix.nrow:
raise ValueError("Fixed value array must be of length equal to the number of rows of blocks")
if type_length(fixed_value.dtype) == 1:
# array of scalars, convert to 1d array of vectors
fixed_value = wp.array(
data=None,
ptr=fixed_value.ptr,
capacity=fixed_value.capacity,
device=fixed_value.device,
dtype=wp.vec(length=projector_matrix.block_shape[0], dtype=projector_matrix.scalar_type),
shape=fixed_value.shape[0],
)
wp.launch(
kernel=_normalize_dirichlet_projector_and_values_kernel,
dim=projector_matrix.nrow,
device=projector_values.device,
inputs=[projector_matrix.offsets, projector_matrix.columns, projector_values, fixed_value],
)
def project_system_rhs(
system_matrix: BsrMatrix, system_rhs: wp.array, projector_matrix: BsrMatrix, fixed_value: Optional[wp.array] = None
):
"""Projects the right-hand-side of a linear system to enforce Dirichlet boundary conditions
``rhs = (I - projector) * ( rhs - system * projector * fixed_value) + projector * fixed_value``
"""
rhs_tmp = wp.empty_like(system_rhs)
rhs_tmp.assign(system_rhs)
if fixed_value is None:
system_rhs.zero_()
else:
bsr_mv(A=projector_matrix, x=fixed_value, y=system_rhs, alpha=1.0, beta=0.0)
bsr_mv(A=system_matrix, x=system_rhs, y=rhs_tmp, alpha=-1.0, beta=1.0)
# here rhs_tmp = system_rhs - system_matrix * projector * fixed_value
# system_rhs = projector * fixed_value
array_axpy(x=rhs_tmp, y=system_rhs, alpha=1.0, beta=1.0)
bsr_mv(A=projector_matrix, x=rhs_tmp, y=system_rhs, alpha=-1.0, beta=1.0)
def project_system_matrix(system_matrix: BsrMatrix, projector_matrix: BsrMatrix):
"""Projects the right-hand-side of a linear system to enforce Dirichlet boundary conditions
``system = (I - projector) * system * (I - projector) + projector``
"""
complement_system = bsr_copy(system_matrix)
bsr_mm(x=projector_matrix, y=system_matrix, z=complement_system, alpha=-1.0, beta=1.0)
bsr_assign(dest=system_matrix, src=complement_system)
bsr_axpy(x=projector_matrix, y=system_matrix)
bsr_mm(x=complement_system, y=projector_matrix, z=system_matrix, alpha=-1.0, beta=1.0)
def project_linear_system(
system_matrix: BsrMatrix,
system_rhs: wp.array,
projector_matrix: BsrMatrix,
fixed_value: Optional[wp.array] = None,
normalize_projector=True,
):
"""
Projects both the left-hand-side and right-hand-side of a linear system to enforce Dirichlet boundary conditions
If normalize_projector is True, first apply scaling so that the projector_matrix is idempotent
"""
if normalize_projector:
normalize_dirichlet_projector(projector_matrix, fixed_value)
project_system_rhs(system_matrix, system_rhs, projector_matrix, fixed_value)
project_system_matrix(system_matrix, projector_matrix)
@wp.kernel
def _normalize_dirichlet_projector_kernel(
offsets: wp.array(dtype=int),
columns: wp.array(dtype=int),
block_values: wp.array(dtype=Any),
):
row = wp.tid()
beg = offsets[row]
end = offsets[row + 1]
if beg == end:
return
diag = wp.lower_bound(columns, beg, end, row)
if diag < end and columns[diag] == row:
P = block_values[diag]
P_sq = P * P
trace_P = wp.trace(P)
trace_P_sq = wp.trace(P_sq)
if wp.nonzero(trace_P_sq):
scale = trace_P / trace_P_sq
block_values[diag] = scale * P
else:
block_values[diag] = P - P
@wp.kernel
def _normalize_dirichlet_projector_and_values_kernel(
offsets: wp.array(dtype=int),
columns: wp.array(dtype=int),
block_values: wp.array(dtype=Any),
fixed_values: wp.array(dtype=Any),
):
row = wp.tid()
beg = offsets[row]
end = offsets[row + 1]
if beg == end:
return
diag = wp.lower_bound(columns, beg, end, row)
if diag < end and columns[diag] == row:
P = block_values[diag]
P_sq = P * P
trace_P = wp.trace(P)
trace_P_sq = wp.trace(P_sq)
if wp.nonzero(trace_P_sq):
scale = trace_P / trace_P_sq
block_values[diag] = scale * P
fixed_values[row] = scale * fixed_values[row]
else:
block_values[diag] = P - P
fixed_values[row] = fixed_values[row] - fixed_values[row]
| 6,037 | Python | 32.731843 | 119 | 0.638893 |
NVIDIA/warp/warp/fem/types.py | import warp as wp
# kept to avoid breaking existing example code, no longer used internally
vec2i = wp.vec2i
vec3i = wp.vec3i
vec4i = wp.vec4i
Coords = wp.vec3
OUTSIDE = wp.constant(-1.0e8)
ElementIndex = int
QuadraturePointIndex = int
NodeIndex = int
NULL_ELEMENT_INDEX = wp.constant(-1)
NULL_QP_INDEX = wp.constant(-1)
NULL_NODE_INDEX = wp.constant(-1)
DofIndex = wp.vec2i
"""Opaque descriptor for indexing degrees of freedom within elements"""
NULL_DOF_INDEX = wp.constant(DofIndex(-1, -1))
@wp.func
def get_node_index_in_element(dof_idx: DofIndex):
return dof_idx[0]
@wp.func
def get_node_coord(dof_idx: DofIndex):
return dof_idx[1]
@wp.struct
class NodeElementIndex:
domain_element_index: ElementIndex
node_index_in_element: int
@wp.struct
class Sample:
"""Per-sample point context for evaluating fields and related operators in integrands"""
element_index: ElementIndex
"""Index of the geometry element the sample point is in"""
element_coords: Coords
"""Coordinates of the sample point inside the element"""
qp_index: QuadraturePointIndex = NULL_QP_INDEX
"""If the sample corresponds to a quadrature point, its global index"""
qp_weight: float = 0.0
"""If the sample corresponds to a quadrature point, its weight"""
test_dof: DofIndex = NULL_DOF_INDEX
"""For linear of bilinear form assembly, index of the test degree-of-freedom currently being considered"""
trial_dof: DofIndex = NULL_DOF_INDEX
"""For bilinear form assembly, index of the trial degree-of-freedom currently being considered"""
@wp.func
def make_free_sample(element_index: ElementIndex, element_coords: Coords):
"""Returns a :class:`Sample` that is not associated to any quadrature point or dof"""
return Sample(element_index, element_coords, NULL_QP_INDEX, 0.0, NULL_DOF_INDEX, NULL_DOF_INDEX)
class Field:
"""
Tag for field-like integrand arguments
"""
call_operator: "warp.fem.operator.Operator" = None # noqa: F821 Set in operator.py
class Domain:
"""
Tag for domain-like integrand arguments
"""
call_operator: "warp.fem.operator.Operator" = None # noqa: F821 Set in operator.py
| 2,188 | Python | 27.064102 | 110 | 0.713437 |
NVIDIA/warp/warp/fem/integrate.py | import ast
from typing import Any, Dict, List, Optional, Set, Union
import warp as wp
from warp.codegen import get_annotations
from warp.fem import cache
from warp.fem.domain import GeometryDomain
from warp.fem.field import (
DiscreteField,
FieldLike,
FieldRestriction,
SpaceField,
TestField,
TrialField,
make_restriction,
)
from warp.fem.operator import Integrand, Operator
from warp.fem.quadrature import Quadrature, RegularQuadrature
from warp.fem.types import NULL_DOF_INDEX, OUTSIDE, DofIndex, Domain, Field, Sample, make_free_sample
from warp.sparse import BsrMatrix, bsr_set_from_triplets, bsr_zeros
from warp.types import type_length
from warp.utils import array_cast
def _resolve_path(func, node):
"""
Resolves variable and path from ast node/attribute (adapted from warp.codegen)
"""
modules = []
while isinstance(node, ast.Attribute):
modules.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
modules.append(node.id)
# reverse list since ast presents it backward order
path = [*reversed(modules)]
if len(path) == 0:
return None, path
# try and evaluate object path
try:
# Look up the closure info and append it to adj.func.__globals__
# in case you want to define a kernel inside a function and refer
# to variables you've declared inside that function:
capturedvars = dict(zip(func.__code__.co_freevars, [c.cell_contents for c in (func.__closure__ or [])]))
vars_dict = {**func.__globals__, **capturedvars}
func = eval(".".join(path), vars_dict)
return func, path
except (NameError, AttributeError):
pass
return None, path
def _path_to_ast_attribute(name: str) -> ast.Attribute:
path = name.split(".")
path.reverse()
node = ast.Name(id=path.pop(), ctx=ast.Load())
while len(path):
node = ast.Attribute(
value=node,
attr=path.pop(),
ctx=ast.Load(),
)
return node
class IntegrandTransformer(ast.NodeTransformer):
def __init__(self, integrand: Integrand, field_args: Dict[str, FieldLike]):
self._integrand = integrand
self._field_args = field_args
def visit_Call(self, call: ast.Call):
call = self.generic_visit(call)
callee = getattr(call.func, "id", None)
if callee in self._field_args:
# Shortcut for evaluating fields as f(x...)
field = self._field_args[callee]
arg_type = self._integrand.argspec.annotations[callee]
operator = arg_type.call_operator
call.func = ast.Attribute(
value=_path_to_ast_attribute(f"{arg_type.__module__}.{arg_type.__qualname__}"),
attr="call_operator",
ctx=ast.Load(),
)
call.args = [ast.Name(id=callee, ctx=ast.Load())] + call.args
self._replace_call_func(call, operator, field)
return call
func, _ = _resolve_path(self._integrand.func, call.func)
if isinstance(func, Operator) and len(call.args) > 0:
# Evaluating operators as op(field, x, ...)
callee = getattr(call.args[0], "id", None)
if callee in self._field_args:
field = self._field_args[callee]
self._replace_call_func(call, func, field)
if isinstance(func, Integrand):
key = self._translate_callee(func, call.args)
call.func = ast.Attribute(
value=call.func,
attr=key,
ctx=ast.Load(),
)
# print(ast.dump(call, indent=4))
return call
def _replace_call_func(self, call: ast.Call, operator: Operator, field: FieldLike):
try:
pointer = operator.resolver(field)
setattr(operator, pointer.key, pointer)
except AttributeError as e:
raise ValueError(f"Operator {operator.func.__name__} is not defined for field {field.name}") from e
call.func = ast.Attribute(value=call.func, attr=pointer.key, ctx=ast.Load())
def _translate_callee(self, callee: Integrand, args: List[ast.AST]):
# Get field types for call site arguments
call_site_field_args = []
for arg in args:
name = getattr(arg, "id", None)
if name in self._field_args:
call_site_field_args.append(self._field_args[name])
call_site_field_args.reverse()
# Pass to callee in same order
callee_field_args = {}
for arg in callee.argspec.args:
arg_type = callee.argspec.annotations[arg]
if arg_type in (Field, Domain):
callee_field_args[arg] = call_site_field_args.pop()
return _translate_integrand(callee, callee_field_args).key
def _translate_integrand(integrand: Integrand, field_args: Dict[str, FieldLike]) -> wp.Function:
# Specialize field argument types
argspec = integrand.argspec
annotations = {}
for arg in argspec.args:
arg_type = argspec.annotations[arg]
if arg_type == Field:
annotations[arg] = field_args[arg].ElementEvalArg
elif arg_type == Domain:
annotations[arg] = field_args[arg].ElementArg
else:
annotations[arg] = arg_type
# Transform field evaluation calls
transformer = IntegrandTransformer(integrand, field_args)
suffix = "_".join([f.name for f in field_args.values()])
func = cache.get_integrand_function(
integrand=integrand,
suffix=suffix,
annotations=annotations,
code_transformers=[transformer],
)
key = func.key
setattr(integrand, key, integrand.module.functions[key])
return getattr(integrand, key)
def _get_integrand_field_arguments(
integrand: Integrand,
fields: Dict[str, FieldLike],
domain: GeometryDomain = None,
):
# parse argument types
field_args = {}
value_args = {}
domain_name = None
sample_name = None
argspec = integrand.argspec
for arg in argspec.args:
arg_type = argspec.annotations[arg]
if arg_type == Field:
if arg not in fields:
raise ValueError(f"Missing field for argument '{arg}' of integrand '{integrand.name}'")
field_args[arg] = fields[arg]
elif arg_type == Domain:
domain_name = arg
field_args[arg] = domain
elif arg_type == Sample:
sample_name = arg
else:
value_args[arg] = arg_type
return field_args, value_args, domain_name, sample_name
def _check_field_compat(
integrand: Integrand,
fields: Dict[str, FieldLike],
field_args: Dict[str, FieldLike],
domain: GeometryDomain = None,
):
# Check field compatilibity
for name, field in fields.items():
if name not in field_args:
raise ValueError(
f"Passed field argument '{name}' does not match any parameter of integrand '{integrand.name}'"
)
if isinstance(field, SpaceField) and domain is not None:
space = field.space
if space.geometry != domain.geometry:
raise ValueError(f"Field '{name}' must be defined on the same geometry as the integration domain")
if space.dimension != domain.dimension:
raise ValueError(
f"Field '{name}' dimension ({space.dimension}) does not match that of the integration domain ({domain.dimension}). Maybe a forgotten `.trace()`?"
)
def _populate_value_struct(ValueStruct: wp.codegen.Struct, values: Dict[str, Any], integrand_name: str):
value_struct_values = ValueStruct()
for k, v in values.items():
try:
setattr(value_struct_values, k, v)
except Exception as err:
if k not in ValueStruct.vars:
raise ValueError(
f"Passed value argument '{k}' does not match any of the integrand '{integrand_name}' parameters"
) from err
raise ValueError(
f"Passed value argument '{k}' of type '{wp.types.type_repr(v)}' is incompatible with the integrand '{integrand_name}' parameter of type '{wp.types.type_repr(ValueStruct.vars[k].type)}'"
) from err
missing_values = ValueStruct.vars.keys() - values.keys()
if missing_values:
wp.utils.warn(
f"Missing values for parameter(s) '{', '.join(missing_values)}' of the integrand '{integrand_name}', will be zero-initialized"
)
return value_struct_values
def _get_test_and_trial_fields(
fields: Dict[str, FieldLike],
):
test = None
trial = None
test_name = None
trial_name = None
for name, field in fields.items():
if not isinstance(field, FieldLike):
raise ValueError(f"Passed field argument '{name}' is not a proper Field")
if isinstance(field, TestField):
if test is not None:
raise ValueError(f"More than one test field argument: '{test_name}' and '{name}'")
test = field
test_name = name
elif isinstance(field, TrialField):
if trial is not None:
raise ValueError(f"More than one trial field argument: '{trial_name}' and '{name}'")
trial = field
trial_name = name
if trial is not None:
if test is None:
raise ValueError("A trial field cannot be provided without a test field")
if test.domain != trial.domain:
raise ValueError("Incompatible test and trial domains")
return test, test_name, trial, trial_name
def _gen_field_struct(field_args: Dict[str, FieldLike]):
class Fields:
pass
annotations = get_annotations(Fields)
for name, arg in field_args.items():
if isinstance(arg, GeometryDomain):
continue
setattr(Fields, name, arg.EvalArg())
annotations[name] = arg.EvalArg
try:
Fields.__annotations__ = annotations
except AttributeError:
Fields.__dict__.__annotations__ = annotations
suffix = "_".join([f"{name}_{arg_struct.cls.__qualname__}" for name, arg_struct in annotations.items()])
return cache.get_struct(Fields, suffix=suffix)
def _gen_value_struct(value_args: Dict[str, type]):
class Values:
pass
annotations = get_annotations(Values)
for name, arg_type in value_args.items():
setattr(Values, name, None)
annotations[name] = arg_type
def arg_type_name(arg_type):
if isinstance(arg_type, wp.codegen.Struct):
return arg_type_name(arg_type.cls)
return getattr(arg_type, "__name__", str(arg_type))
def arg_type_name(arg_type):
if isinstance(arg_type, wp.codegen.Struct):
return arg_type_name(arg_type.cls)
return getattr(arg_type, "__name__", str(arg_type))
try:
Values.__annotations__ = annotations
except AttributeError:
Values.__dict__.__annotations__ = annotations
suffix = "_".join([f"{name}_{arg_type_name(arg_type)}" for name, arg_type in annotations.items()])
return cache.get_struct(Values, suffix=suffix)
def _get_trial_arg():
pass
def _get_test_arg():
pass
class _FieldWrappers:
pass
def _register_integrand_field_wrappers(integrand_func: wp.Function, fields: Dict[str, FieldLike]):
integrand_func._field_wrappers = _FieldWrappers()
for name, field in fields.items():
setattr(integrand_func._field_wrappers, name, field.ElementEvalArg)
class PassFieldArgsToIntegrand(ast.NodeTransformer):
def __init__(
self,
arg_names: List[str],
field_args: Set[str],
value_args: Set[str],
sample_name: str,
domain_name: str,
test_name: str = None,
trial_name: str = None,
func_name: str = "integrand_func",
fields_var_name: str = "fields",
values_var_name: str = "values",
domain_var_name: str = "domain_arg",
sample_var_name: str = "sample",
field_wrappers_attr: str = "_field_wrappers",
):
self._arg_names = arg_names
self._field_args = field_args
self._value_args = value_args
self._domain_name = domain_name
self._sample_name = sample_name
self._func_name = func_name
self._test_name = test_name
self._trial_name = trial_name
self._fields_var_name = fields_var_name
self._values_var_name = values_var_name
self._domain_var_name = domain_var_name
self._sample_var_name = sample_var_name
self._field_wrappers_attr = field_wrappers_attr
def visit_Call(self, call: ast.Call):
call = self.generic_visit(call)
callee = getattr(call.func, "id", None)
if callee == self._func_name:
# Replace function arguments with ours generated structs
call.args.clear()
for arg in self._arg_names:
if arg == self._domain_name:
call.args.append(
ast.Name(id=self._domain_var_name, ctx=ast.Load()),
)
elif arg == self._sample_name:
call.args.append(
ast.Name(id=self._sample_var_name, ctx=ast.Load()),
)
elif arg in self._field_args:
call.args.append(
ast.Call(
func=ast.Attribute(
value=ast.Attribute(
value=ast.Name(id=self._func_name, ctx=ast.Load()),
attr=self._field_wrappers_attr,
ctx=ast.Load(),
),
attr=arg,
ctx=ast.Load(),
),
args=[
ast.Name(id=self._domain_var_name, ctx=ast.Load()),
ast.Attribute(
value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
attr=arg,
ctx=ast.Load(),
),
],
keywords=[],
)
)
elif arg in self._value_args:
call.args.append(
ast.Attribute(
value=ast.Name(id=self._values_var_name, ctx=ast.Load()),
attr=arg,
ctx=ast.Load(),
)
)
else:
raise RuntimeError(f"Unhandled argument {arg}")
# print(ast.dump(call, indent=4))
elif callee == _get_test_arg.__name__:
# print(ast.dump(call, indent=4))
call = ast.Attribute(
value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
attr=self._test_name,
ctx=ast.Load(),
)
elif callee == _get_trial_arg.__name__:
# print(ast.dump(call, indent=4))
call = ast.Attribute(
value=ast.Name(id=self._fields_var_name, ctx=ast.Load()),
attr=self._trial_name,
ctx=ast.Load(),
)
return call
def get_integrate_constant_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
accumulate_dtype,
):
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array(dtype=accumulate_dtype),
):
element_index = domain.element_index(domain_index_arg, wp.tid())
elem_sum = accumulate_dtype(0.0)
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
vol = domain.element_measure(domain_arg, sample)
val = integrand_func(sample, fields, values)
elem_sum += accumulate_dtype(qp_weight * vol * val)
wp.atomic_add(result, 0, elem_sum)
return integrate_kernel_fn
def get_integrate_linear_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test: TestField,
output_dtype,
accumulate_dtype,
):
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_arg: test.space_restriction.NodeArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array2d(dtype=output_dtype),
):
local_node_index, test_dof = wp.tid()
node_index = test.space_restriction.node_partition_index(test_arg, local_node_index)
element_count = test.space_restriction.node_element_count(test_arg, local_node_index)
trial_dof_index = NULL_DOF_INDEX
val_sum = accumulate_dtype(0.0)
for n in range(element_count):
node_element_index = test.space_restriction.node_element_index(test_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
qp_coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
vol = domain.element_measure(domain_arg, make_free_sample(element_index, qp_coords))
sample = Sample(element_index, qp_coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
val = integrand_func(sample, fields, values)
val_sum += accumulate_dtype(qp_weight * vol * val)
result[node_index, test_dof] = output_dtype(val_sum)
return integrate_kernel_fn
def get_integrate_linear_nodal_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test: TestField,
output_dtype,
accumulate_dtype,
):
def integrate_kernel_fn(
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_restriction_arg: test.space_restriction.NodeArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array2d(dtype=output_dtype),
):
local_node_index, dof = wp.tid()
node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
trial_dof_index = NULL_DOF_INDEX
val_sum = accumulate_dtype(0.0)
for n in range(element_count):
node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
coords = test.space.node_coords_in_element(
domain_arg,
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
if coords[0] != OUTSIDE:
node_weight = test.space.node_quadrature_weight(
domain_arg,
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
test_dof_index = DofIndex(node_element_index.node_index_in_element, dof)
sample = Sample(
element_index,
coords,
node_index,
node_weight,
test_dof_index,
trial_dof_index,
)
vol = domain.element_measure(domain_arg, sample)
val = integrand_func(sample, fields, values)
val_sum += accumulate_dtype(node_weight * vol * val)
result[node_index, dof] = output_dtype(val_sum)
return integrate_kernel_fn
def get_integrate_bilinear_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test: TestField,
trial: TrialField,
output_dtype,
accumulate_dtype,
):
NODES_PER_ELEMENT = trial.space.topology.NODES_PER_ELEMENT
def integrate_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_arg: test.space_restriction.NodeArg,
trial_partition_arg: trial.space_partition.PartitionArg,
trial_topology_arg: trial.space_partition.space_topology.TopologyArg,
fields: FieldStruct,
values: ValueStruct,
row_offsets: wp.array(dtype=int),
triplet_rows: wp.array(dtype=int),
triplet_cols: wp.array(dtype=int),
triplet_values: wp.array3d(dtype=output_dtype),
):
test_local_node_index, trial_node, test_dof, trial_dof = wp.tid()
element_count = test.space_restriction.node_element_count(test_arg, test_local_node_index)
test_node_index = test.space_restriction.node_partition_index(test_arg, test_local_node_index)
trial_dof_index = DofIndex(trial_node, trial_dof)
for element in range(element_count):
test_element_index = test.space_restriction.node_element_index(test_arg, test_local_node_index, element)
element_index = domain.element_index(domain_index_arg, test_element_index.domain_element_index)
qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
test_dof_index = DofIndex(
test_element_index.node_index_in_element,
test_dof,
)
val_sum = accumulate_dtype(0.0)
for k in range(qp_point_count):
qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
vol = domain.element_measure(domain_arg, make_free_sample(element_index, coords))
sample = Sample(
element_index,
coords,
qp_index,
qp_weight,
test_dof_index,
trial_dof_index,
)
val = integrand_func(sample, fields, values)
val_sum += accumulate_dtype(qp_weight * vol * val)
block_offset = (row_offsets[test_node_index] + element) * NODES_PER_ELEMENT + trial_node
triplet_values[block_offset, test_dof, trial_dof] = output_dtype(val_sum)
# Set row and column indices
if test_dof == 0 and trial_dof == 0:
trial_node_index = trial.space_partition.partition_node_index(
trial_partition_arg,
trial.space.topology.element_node_index(domain_arg, trial_topology_arg, element_index, trial_node),
)
triplet_rows[block_offset] = test_node_index
triplet_cols[block_offset] = trial_node_index
return integrate_kernel_fn
def get_integrate_bilinear_nodal_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
test: TestField,
output_dtype,
accumulate_dtype,
):
def integrate_kernel_fn(
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
test_restriction_arg: test.space_restriction.NodeArg,
fields: FieldStruct,
values: ValueStruct,
triplet_rows: wp.array(dtype=int),
triplet_cols: wp.array(dtype=int),
triplet_values: wp.array3d(dtype=output_dtype),
):
local_node_index, test_dof, trial_dof = wp.tid()
element_count = test.space_restriction.node_element_count(test_restriction_arg, local_node_index)
node_index = test.space_restriction.node_partition_index(test_restriction_arg, local_node_index)
val_sum = accumulate_dtype(0.0)
for n in range(element_count):
node_element_index = test.space_restriction.node_element_index(test_restriction_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
coords = test.space.node_coords_in_element(
domain_arg,
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
if coords[0] != OUTSIDE:
node_weight = test.space.node_quadrature_weight(
domain_arg,
_get_test_arg(),
element_index,
node_element_index.node_index_in_element,
)
test_dof_index = DofIndex(node_element_index.node_index_in_element, test_dof)
trial_dof_index = DofIndex(node_element_index.node_index_in_element, trial_dof)
sample = Sample(
element_index,
coords,
node_index,
node_weight,
test_dof_index,
trial_dof_index,
)
vol = domain.element_measure(domain_arg, sample)
val = integrand_func(sample, fields, values)
val_sum += accumulate_dtype(node_weight * vol * val)
triplet_values[local_node_index, test_dof, trial_dof] = output_dtype(val_sum)
triplet_rows[local_node_index] = node_index
triplet_cols[local_node_index] = node_index
return integrate_kernel_fn
def _generate_integrate_kernel(
integrand: Integrand,
domain: GeometryDomain,
nodal: bool,
quadrature: Quadrature,
test: Optional[TestField],
test_name: str,
trial: Optional[TrialField],
trial_name: str,
fields: Dict[str, FieldLike],
output_dtype: type,
accumulate_dtype: type,
kernel_options: Optional[Dict[str, Any]] = None,
) -> wp.Kernel:
if kernel_options is None:
kernel_options = {}
output_dtype = wp.types.type_scalar_type(output_dtype)
# Extract field arguments from integrand
field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
integrand, fields=fields, domain=domain
)
FieldStruct = _gen_field_struct(field_args)
ValueStruct = _gen_value_struct(value_args)
# Check if kernel exist in cache
kernel_suffix = f"_itg_{wp.types.type_typestr(output_dtype)}{wp.types.type_typestr(accumulate_dtype)}_{domain.name}_{FieldStruct.key}"
if nodal:
kernel_suffix += "_nodal"
else:
kernel_suffix += quadrature.name
if test:
kernel_suffix += f"_test_{test.space_partition.name}_{test.space.name}"
if trial:
kernel_suffix += f"_trial_{trial.space_partition.name}_{trial.space.name}"
kernel = cache.get_integrand_kernel(
integrand=integrand,
suffix=kernel_suffix,
)
if kernel is not None:
return kernel, FieldStruct, ValueStruct
# Not found in cache, transform integrand and generate kernel
_check_field_compat(integrand, fields, field_args, domain)
integrand_func = _translate_integrand(
integrand,
field_args,
)
_register_integrand_field_wrappers(integrand_func, fields)
if test is None and trial is None:
integrate_kernel_fn = get_integrate_constant_kernel(
integrand_func,
domain,
quadrature,
FieldStruct,
ValueStruct,
accumulate_dtype=accumulate_dtype,
)
elif trial is None:
if nodal:
integrate_kernel_fn = get_integrate_linear_nodal_kernel(
integrand_func,
domain,
FieldStruct,
ValueStruct,
test=test,
output_dtype=output_dtype,
accumulate_dtype=accumulate_dtype,
)
else:
integrate_kernel_fn = get_integrate_linear_kernel(
integrand_func,
domain,
quadrature,
FieldStruct,
ValueStruct,
test=test,
output_dtype=output_dtype,
accumulate_dtype=accumulate_dtype,
)
else:
if nodal:
integrate_kernel_fn = get_integrate_bilinear_nodal_kernel(
integrand_func,
domain,
FieldStruct,
ValueStruct,
test=test,
output_dtype=output_dtype,
accumulate_dtype=accumulate_dtype,
)
else:
integrate_kernel_fn = get_integrate_bilinear_kernel(
integrand_func,
domain,
quadrature,
FieldStruct,
ValueStruct,
test=test,
trial=trial,
output_dtype=output_dtype,
accumulate_dtype=accumulate_dtype,
)
kernel = cache.get_integrand_kernel(
integrand=integrand,
kernel_fn=integrate_kernel_fn,
suffix=kernel_suffix,
kernel_options=kernel_options,
code_transformers=[
PassFieldArgsToIntegrand(
arg_names=integrand.argspec.args,
field_args=field_args.keys(),
value_args=value_args.keys(),
sample_name=sample_name,
domain_name=domain_name,
test_name=test_name,
trial_name=trial_name,
)
],
)
return kernel, FieldStruct, ValueStruct
def _launch_integrate_kernel(
integrand: Integrand,
kernel: wp.Kernel,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
domain: GeometryDomain,
nodal: bool,
quadrature: Quadrature,
test: Optional[TestField],
trial: Optional[TrialField],
fields: Dict[str, FieldLike],
values: Dict[str, Any],
accumulate_dtype: type,
temporary_store: Optional[cache.TemporaryStore],
output_dtype: type,
output: Optional[Union[wp.array, BsrMatrix]],
device,
):
# Set-up launch arguments
domain_elt_arg = domain.element_arg_value(device=device)
domain_elt_index_arg = domain.element_index_arg_value(device=device)
if quadrature is not None:
qp_arg = quadrature.arg_value(device=device)
field_arg_values = FieldStruct()
for k, v in fields.items():
setattr(field_arg_values, k, v.eval_arg_value(device=device))
value_struct_values = _populate_value_struct(ValueStruct, values, integrand_name=integrand.name)
# Constant form
if test is None and trial is None:
if output is not None and output.dtype == accumulate_dtype:
if output.size < 1:
raise RuntimeError("Output array must be of size at least 1")
accumulate_array = output
else:
accumulate_temporary = cache.borrow_temporary(
shape=(1),
device=device,
dtype=accumulate_dtype,
temporary_store=temporary_store,
requires_grad=output is not None and output.requires_grad,
)
accumulate_array = accumulate_temporary.array
accumulate_array.zero_()
wp.launch(
kernel=kernel,
dim=domain.element_count(),
inputs=[
qp_arg,
domain_elt_arg,
domain_elt_index_arg,
field_arg_values,
value_struct_values,
accumulate_array,
],
device=device,
)
if output == accumulate_array:
return output
elif output is None:
return accumulate_array.numpy()[0]
else:
array_cast(in_array=accumulate_array, out_array=output)
return output
test_arg = test.space_restriction.node_arg(device=device)
# Linear form
if trial is None:
# If an output array is provided with the correct type, accumulate directly into it
# Otherwise, grab a temporary array
if output is None:
if type_length(output_dtype) == test.space.VALUE_DOF_COUNT:
output_shape = (test.space_partition.node_count(),)
elif type_length(output_dtype) == 1:
output_shape = (test.space_partition.node_count(), test.space.VALUE_DOF_COUNT)
else:
raise RuntimeError(
f"Incompatible output type {wp.types.type_repr(output_dtype)}, must be scalar or vector of length {test.space.VALUE_DOF_COUNT}"
)
output_temporary = cache.borrow_temporary(
temporary_store=temporary_store,
shape=output_shape,
dtype=output_dtype,
device=device,
)
output = output_temporary.array
else:
output_temporary = None
if output.shape[0] < test.space_partition.node_count():
raise RuntimeError(f"Output array must have at least {test.space_partition.node_count()} rows")
output_dtype = output.dtype
if type_length(output_dtype) != test.space.VALUE_DOF_COUNT:
if type_length(output_dtype) != 1:
raise RuntimeError(
f"Incompatible output type {wp.types.type_repr(output_dtype)}, must be scalar or vector of length {test.space.VALUE_DOF_COUNT}"
)
if output.ndim != 2 and output.shape[1] != test.space.VALUE_DOF_COUNT:
raise RuntimeError(
f"Incompatible output array shape, last dimension must be of size {test.space.VALUE_DOF_COUNT}"
)
# Launch the integration on the kernel on a 2d scalar view of the actual array
output.zero_()
def as_2d_array(array):
return wp.array(
data=None,
ptr=array.ptr,
capacity=array.capacity,
device=array.device,
shape=(test.space_partition.node_count(), test.space.VALUE_DOF_COUNT),
dtype=wp.types.type_scalar_type(output_dtype),
grad=None if array.grad is None else as_2d_array(array.grad),
)
output_view = output if output.ndim == 2 else as_2d_array(output)
if nodal:
wp.launch(
kernel=kernel,
dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
inputs=[
domain_elt_arg,
domain_elt_index_arg,
test_arg,
field_arg_values,
value_struct_values,
output_view,
],
device=device,
)
else:
wp.launch(
kernel=kernel,
dim=(test.space_restriction.node_count(), test.space.VALUE_DOF_COUNT),
inputs=[
qp_arg,
domain_elt_arg,
domain_elt_index_arg,
test_arg,
field_arg_values,
value_struct_values,
output_view,
],
device=device,
)
if output_temporary is not None:
return output_temporary.detach()
return output
# Bilinear form
if test.space.VALUE_DOF_COUNT == 1 and trial.space.VALUE_DOF_COUNT == 1:
block_type = output_dtype
else:
block_type = cache.cached_mat_type(
shape=(test.space.VALUE_DOF_COUNT, trial.space.VALUE_DOF_COUNT), dtype=output_dtype
)
if nodal:
nnz = test.space_restriction.node_count()
else:
nnz = test.space_restriction.total_node_element_count() * trial.space.topology.NODES_PER_ELEMENT
triplet_rows_temp = cache.borrow_temporary(temporary_store, shape=(nnz,), dtype=int, device=device)
triplet_cols_temp = cache.borrow_temporary(temporary_store, shape=(nnz,), dtype=int, device=device)
triplet_values_temp = cache.borrow_temporary(
temporary_store,
shape=(
nnz,
test.space.VALUE_DOF_COUNT,
trial.space.VALUE_DOF_COUNT,
),
dtype=output_dtype,
device=device,
)
triplet_cols = triplet_cols_temp.array
triplet_rows = triplet_rows_temp.array
triplet_values = triplet_values_temp.array
triplet_values.zero_()
if nodal:
wp.launch(
kernel=kernel,
dim=triplet_values.shape,
inputs=[
domain_elt_arg,
domain_elt_index_arg,
test_arg,
field_arg_values,
value_struct_values,
triplet_rows,
triplet_cols,
triplet_values,
],
device=device,
)
else:
offsets = test.space_restriction.partition_element_offsets()
trial_partition_arg = trial.space_partition.partition_arg_value(device)
trial_topology_arg = trial.space_partition.space_topology.topo_arg_value(device)
wp.launch(
kernel=kernel,
dim=(
test.space_restriction.node_count(),
trial.space.topology.NODES_PER_ELEMENT,
test.space.VALUE_DOF_COUNT,
trial.space.VALUE_DOF_COUNT,
),
inputs=[
qp_arg,
domain_elt_arg,
domain_elt_index_arg,
test_arg,
trial_partition_arg,
trial_topology_arg,
field_arg_values,
value_struct_values,
offsets,
triplet_rows,
triplet_cols,
triplet_values,
],
device=device,
)
if output is not None:
if output.nrow != test.space_partition.node_count() or output.ncol != trial.space_partition.node_count():
raise RuntimeError(
f"Output matrix must have {test.space_partition.node_count()} rows and {trial.space_partition.node_count()} columns of blocks"
)
else:
output = bsr_zeros(
rows_of_blocks=test.space_partition.node_count(),
cols_of_blocks=trial.space_partition.node_count(),
block_type=block_type,
device=device,
)
bsr_set_from_triplets(output, triplet_rows, triplet_cols, triplet_values)
# Do not wait for garbage collection
triplet_values_temp.release()
triplet_rows_temp.release()
triplet_cols_temp.release()
return output
def integrate(
integrand: Integrand,
domain: Optional[GeometryDomain] = None,
quadrature: Optional[Quadrature] = None,
nodal: bool = False,
fields: Optional[Dict[str, FieldLike]] = None,
values: Optional[Dict[str, Any]] = None,
accumulate_dtype: type = wp.float64,
output_dtype: Optional[type] = None,
output: Optional[Union[BsrMatrix, wp.array]] = None,
device=None,
temporary_store: Optional[cache.TemporaryStore] = None,
kernel_options: Optional[Dict[str, Any]] = None,
):
"""
Integrates a constant, linear or bilinear form, and returns a scalar, array, or sparse matrix, respectively.
Args:
integrand: Form to be integrated, must have :func:`integrand` decorator
domain: Integration domain. If None, deduced from fields
quadrature: Quadrature formula. If None, deduced from domain and fields degree.
nodal: For linear or bilinear form only, use the test function nodes as the quadrature points. Assumes Lagrange interpolation functions are used, and no differential or DG operator is evaluated on the test or trial functions.
fields: Discrete, test, and trial fields to be passed to the integrand. Keys in the dictionary must match integrand parameter names.
values: Additional variable values to be passed to the integrand, can be of any type accepted by warp kernel launches. Keys in the dictionary must match integrand parameter names.
temporary_store: shared pool from which to allocate temporary arrays
accumulate_dtype: Scalar type to be used for accumulating integration samples
output: Sparse matrix or warp array into which to store the result of the integration
output_dtype: Scalar type for returned results in `output` is not provided. If None, defaults to `accumulate_dtype`
device: Device on which to perform the integration
kernel_options: Overloaded options to be passed to the kernel builder (e.g, ``{"enable_backward": True}``)
"""
if fields is None:
fields = {}
if values is None:
values = {}
if kernel_options is None:
kernel_options = {}
if not isinstance(integrand, Integrand):
raise ValueError("integrand must be tagged with @warp.fem.integrand decorator")
test, test_name, trial, trial_name = _get_test_and_trial_fields(fields)
if domain is None:
if quadrature is not None:
domain = quadrature.domain
elif test is not None:
domain = test.domain
if domain is None:
raise ValueError("Must provide at least one of domain, quadrature, or test field")
if test is not None and domain != test.domain:
raise NotImplementedError("Mixing integration and test domain is not supported yet")
if nodal:
if quadrature is not None:
raise ValueError("Cannot specify quadrature for nodal integration")
if test is None:
raise ValueError("Nodal integration requires specifying a test function")
if trial is not None and test.space_partition != trial.space_partition:
raise ValueError(
"Bilinear nodal integration requires test and trial to be defined on the same function space"
)
else:
if quadrature is None:
order = sum(field.degree for field in fields.values())
quadrature = RegularQuadrature(domain=domain, order=order)
elif domain != quadrature.domain:
raise ValueError("Incompatible integration and quadrature domain")
# Canonicalize types
accumulate_dtype = wp.types.type_to_warp(accumulate_dtype)
if output is not None:
if isinstance(output, BsrMatrix):
output_dtype = output.scalar_type
else:
output_dtype = output.dtype
elif output_dtype is None:
output_dtype = accumulate_dtype
else:
output_dtype = wp.types.type_to_warp(output_dtype)
kernel, FieldStruct, ValueStruct = _generate_integrate_kernel(
integrand=integrand,
domain=domain,
nodal=nodal,
quadrature=quadrature,
test=test,
test_name=test_name,
trial=trial,
trial_name=trial_name,
fields=fields,
accumulate_dtype=accumulate_dtype,
output_dtype=output_dtype,
kernel_options=kernel_options,
)
return _launch_integrate_kernel(
integrand=integrand,
kernel=kernel,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
domain=domain,
nodal=nodal,
quadrature=quadrature,
test=test,
trial=trial,
fields=fields,
values=values,
accumulate_dtype=accumulate_dtype,
temporary_store=temporary_store,
output_dtype=output_dtype,
output=output,
device=device,
)
def get_interpolate_to_field_function(
integrand_func: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
dest: FieldRestriction,
):
value_type = dest.space.dtype
def interpolate_to_field_fn(
local_node_index: int,
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
dest_node_arg: dest.space_restriction.NodeArg,
dest_eval_arg: dest.field.EvalArg,
fields: FieldStruct,
values: ValueStruct,
):
node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
element_count = dest.space_restriction.node_element_count(dest_node_arg, local_node_index)
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
node_weight = 1.0
# Volume-weighted average across elements
# Superfluous if the interpolated function is continuous, but helpful for visualizing discontinuous spaces
val_sum = value_type(0.0)
vol_sum = float(0.0)
for n in range(element_count):
node_element_index = dest.space_restriction.node_element_index(dest_node_arg, local_node_index, n)
element_index = domain.element_index(domain_index_arg, node_element_index.domain_element_index)
coords = dest.space.node_coords_in_element(
domain_arg,
dest_eval_arg.space_arg,
element_index,
node_element_index.node_index_in_element,
)
if coords[0] != OUTSIDE:
sample = Sample(
element_index,
coords,
node_index,
node_weight,
test_dof_index,
trial_dof_index,
)
vol = domain.element_measure(domain_arg, sample)
val = integrand_func(sample, fields, values)
vol_sum += vol
val_sum += vol * val
return val_sum, vol_sum
return interpolate_to_field_fn
def get_interpolate_to_field_kernel(
interpolate_to_field_fn: wp.Function,
domain: GeometryDomain,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
dest: FieldRestriction,
):
def interpolate_to_field_kernel_fn(
domain_arg: domain.ElementArg,
domain_index_arg: domain.ElementIndexArg,
dest_node_arg: dest.space_restriction.NodeArg,
dest_eval_arg: dest.field.EvalArg,
fields: FieldStruct,
values: ValueStruct,
):
local_node_index = wp.tid()
val_sum, vol_sum = interpolate_to_field_fn(
local_node_index, domain_arg, domain_index_arg, dest_node_arg, dest_eval_arg, fields, values
)
if vol_sum > 0.0:
node_index = dest.space_restriction.node_partition_index(dest_node_arg, local_node_index)
dest.field.set_node_value(dest_eval_arg, node_index, val_sum / vol_sum)
return interpolate_to_field_kernel_fn
def get_interpolate_to_array_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
value_type: type,
):
def interpolate_to_array_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: quadrature.domain.ElementArg,
domain_index_arg: quadrature.domain.ElementIndexArg,
fields: FieldStruct,
values: ValueStruct,
result: wp.array(dtype=value_type),
):
element_index = domain.element_index(domain_index_arg, wp.tid())
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
result[qp_index] = integrand_func(sample, fields, values)
return interpolate_to_array_kernel_fn
def get_interpolate_nonvalued_kernel(
integrand_func: wp.Function,
domain: GeometryDomain,
quadrature: Quadrature,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
):
def interpolate_nonvalued_kernel_fn(
qp_arg: quadrature.Arg,
domain_arg: quadrature.domain.ElementArg,
domain_index_arg: quadrature.domain.ElementIndexArg,
fields: FieldStruct,
values: ValueStruct,
):
element_index = domain.element_index(domain_index_arg, wp.tid())
test_dof_index = NULL_DOF_INDEX
trial_dof_index = NULL_DOF_INDEX
qp_point_count = quadrature.point_count(domain_arg, qp_arg, element_index)
for k in range(qp_point_count):
qp_index = quadrature.point_index(domain_arg, qp_arg, element_index, k)
coords = quadrature.point_coords(domain_arg, qp_arg, element_index, k)
qp_weight = quadrature.point_weight(domain_arg, qp_arg, element_index, k)
sample = Sample(element_index, coords, qp_index, qp_weight, test_dof_index, trial_dof_index)
integrand_func(sample, fields, values)
return interpolate_nonvalued_kernel_fn
def _generate_interpolate_kernel(
integrand: Integrand,
domain: GeometryDomain,
dest: Optional[Union[FieldLike, wp.array]],
quadrature: Optional[Quadrature],
fields: Dict[str, FieldLike],
kernel_options: Optional[Dict[str, Any]] = None,
) -> wp.Kernel:
if kernel_options is None:
kernel_options = {}
# Extract field arguments from integrand
field_args, value_args, domain_name, sample_name = _get_integrand_field_arguments(
integrand, fields=fields, domain=domain
)
# Generate field struct
integrand_func = _translate_integrand(
integrand,
field_args,
)
_register_integrand_field_wrappers(integrand_func, fields)
FieldStruct = _gen_field_struct(field_args)
ValueStruct = _gen_value_struct(value_args)
# Check if kernel exist in cache
if isinstance(dest, FieldRestriction):
kernel_suffix = (
f"_itp_{FieldStruct.key}_{dest.domain.name}_{dest.space_restriction.space_partition.name}_{dest.space.name}"
)
elif wp.types.is_array(dest):
kernel_suffix = f"_itp_{FieldStruct.key}_{quadrature.name}_{wp.types.type_repr(dest.dtype)}"
else:
kernel_suffix = f"_itp_{FieldStruct.key}_{quadrature.name}"
kernel = cache.get_integrand_kernel(
integrand=integrand,
suffix=kernel_suffix,
)
if kernel is not None:
return kernel, FieldStruct, ValueStruct
_check_field_compat(integrand, fields, field_args, domain)
# Generate interpolation kernel
if isinstance(dest, FieldRestriction):
# need to split into kernel + function for diffferentiability
interpolate_fn = get_interpolate_to_field_function(
integrand_func,
domain,
dest=dest,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
)
interpolate_fn = cache.get_integrand_function(
integrand=integrand,
func=interpolate_fn,
suffix=kernel_suffix,
code_transformers=[
PassFieldArgsToIntegrand(
arg_names=integrand.argspec.args,
field_args=field_args.keys(),
value_args=value_args.keys(),
sample_name=sample_name,
domain_name=domain_name,
)
],
)
interpolate_kernel_fn = get_interpolate_to_field_kernel(
interpolate_fn,
domain,
dest=dest,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
)
elif wp.types.is_array(dest):
interpolate_kernel_fn = get_interpolate_to_array_kernel(
integrand_func,
domain=domain,
quadrature=quadrature,
value_type=dest.dtype,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
)
else:
interpolate_kernel_fn = get_interpolate_nonvalued_kernel(
integrand_func,
domain=domain,
quadrature=quadrature,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
)
kernel = cache.get_integrand_kernel(
integrand=integrand,
kernel_fn=interpolate_kernel_fn,
suffix=kernel_suffix,
kernel_options=kernel_options,
code_transformers=[
PassFieldArgsToIntegrand(
arg_names=integrand.argspec.args,
field_args=field_args.keys(),
value_args=value_args.keys(),
sample_name=sample_name,
domain_name=domain_name,
)
],
)
return kernel, FieldStruct, ValueStruct
def _launch_interpolate_kernel(
integrand: Integrand,
kernel: wp.kernel,
FieldStruct: wp.codegen.Struct,
ValueStruct: wp.codegen.Struct,
domain: GeometryDomain,
dest: Optional[Union[FieldRestriction, wp.array]],
quadrature: Optional[Quadrature],
fields: Dict[str, FieldLike],
values: Dict[str, Any],
device,
) -> wp.Kernel:
# Set-up launch arguments
elt_arg = domain.element_arg_value(device=device)
elt_index_arg = domain.element_index_arg_value(device=device)
field_arg_values = FieldStruct()
for k, v in fields.items():
setattr(field_arg_values, k, v.eval_arg_value(device=device))
value_struct_values = _populate_value_struct(ValueStruct, values, integrand_name=integrand.name)
if isinstance(dest, FieldRestriction):
dest_node_arg = dest.space_restriction.node_arg(device=device)
dest_eval_arg = dest.field.eval_arg_value(device=device)
wp.launch(
kernel=kernel,
dim=dest.space_restriction.node_count(),
inputs=[
elt_arg,
elt_index_arg,
dest_node_arg,
dest_eval_arg,
field_arg_values,
value_struct_values,
],
device=device,
)
elif wp.types.is_array(dest):
qp_arg = quadrature.arg_value(device)
wp.launch(
kernel=kernel,
dim=domain.element_count(),
inputs=[qp_arg, elt_arg, elt_index_arg, field_arg_values, value_struct_values, dest],
device=device,
)
else:
qp_arg = quadrature.arg_value(device)
wp.launch(
kernel=kernel,
dim=domain.element_count(),
inputs=[qp_arg, elt_arg, elt_index_arg, field_arg_values, value_struct_values],
device=device,
)
def interpolate(
integrand: Integrand,
dest: Optional[Union[DiscreteField, FieldRestriction, wp.array]] = None,
quadrature: Optional[Quadrature] = None,
fields: Optional[Dict[str, FieldLike]] = None,
values: Optional[Dict[str, Any]] = None,
device=None,
kernel_options: Optional[Dict[str, Any]] = None,
):
"""
Interpolates a function at a finite set of sample points and optionally assigns the result to a discrete field or a raw warp array.
Args:
integrand: Function to be interpolated, must have :func:`integrand` decorator
dest: Where to store the interpolation result. Can be either
- a :class:`DiscreteField`, or restriction of a discrete field to a domain (from :func:`make_restriction`). In this case, interpolation will be performed at each node.
- a normal warp array. In this case, the `quadrature` argument defining the interpolation locations must be provided and the result of the `integrand` at each quadrature point will be assigned to the array.
- ``None``. In this case, the `quadrature` argument must also be provided and the `integrand` function is responsible for dealing with the interpolation result.
quadrature: Quadrature formula defining the interpolation samples if `dest` is not a discrete field or field restriction.
fields: Discrete fields to be passed to the integrand. Keys in the dictionary must match integrand parameters names.
values: Additional variable values to be passed to the integrand, can be of any type accepted by warp kernel launches. Keys in the dictionary must match integrand parameter names.
device: Device on which to perform the interpolation
kernel_options: Overloaded options to be passed to the kernel builder (e.g, ``{"enable_backward": True}``)
"""
if fields is None:
fields = {}
if values is None:
values = {}
if kernel_options is None:
kernel_options = {}
if not isinstance(integrand, Integrand):
raise ValueError("integrand must be tagged with @integrand decorator")
test, _, trial, __ = _get_test_and_trial_fields(fields)
if test is not None or trial is not None:
raise ValueError("Test or Trial fields should not be used for interpolation")
if isinstance(dest, DiscreteField):
dest = make_restriction(dest)
if isinstance(dest, FieldRestriction):
domain = dest.domain
else:
if quadrature is None:
raise ValueError("When not interpolating to a field, a quadrature formula must be provided")
domain = quadrature.domain
kernel, FieldStruct, ValueStruct = _generate_interpolate_kernel(
integrand=integrand,
domain=domain,
dest=dest,
quadrature=quadrature,
fields=fields,
kernel_options=kernel_options,
)
return _launch_interpolate_kernel(
integrand=integrand,
kernel=kernel,
FieldStruct=FieldStruct,
ValueStruct=ValueStruct,
domain=domain,
dest=dest,
quadrature=quadrature,
fields=fields,
values=values,
device=device,
)
| 59,748 | Python | 34.459347 | 233 | 0.593158 |
NVIDIA/warp/warp/fem/field/trial.py | import warp as wp
from warp.fem import cache, utils
from warp.fem.domain import GeometryDomain
from warp.fem.space import FunctionSpace, SpacePartition
from warp.fem.types import Sample, get_node_index_in_element
from .field import SpaceField
class TrialField(SpaceField):
"""Field defined over a domain that can be used as a trial function"""
def __init__(
self,
space: FunctionSpace,
space_partition: SpacePartition,
domain: GeometryDomain,
):
if domain.dimension == space.dimension - 1:
space = space.trace()
if domain.dimension != space.dimension:
raise ValueError("Incompatible space and domain dimensions")
if not space.topology.is_derived_from(space_partition.space_topology):
raise ValueError("Incompatible space and space partition topologies")
super().__init__(space, space_partition)
self.domain = domain
self.EvalArg = self.space.SpaceArg
self.ElementEvalArg = self._make_element_eval_arg()
self.eval_degree = self._make_eval_degree()
self.eval_inner = self._make_eval_inner()
self.eval_grad_inner = self._make_eval_grad_inner()
self.eval_div_inner = self._make_eval_div_inner()
self.eval_outer = self._make_eval_outer()
self.eval_grad_outer = self._make_eval_grad_outer()
self.eval_div_outer = self._make_eval_div_outer()
self.at_node = self._make_at_node()
def partition_node_count(self) -> int:
"""Returns the number of nodes in the associated space topology partition"""
return self.space_partition.node_count()
@property
def name(self) -> str:
return self.space.name + "Trial"
def eval_arg_value(self, device) -> wp.codegen.StructInstance:
return self.space.space_arg_value(device)
def _make_element_eval_arg(self):
@cache.dynamic_struct(suffix=self.name)
class ElementEvalArg:
elt_arg: self.domain.ElementArg
eval_arg: self.EvalArg
return ElementEvalArg
def _make_eval_inner(self):
@cache.dynamic_func(suffix=self.name)
def eval_trial_inner(args: self.ElementEvalArg, s: Sample):
weight = self.space.element_inner_weight(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
return weight * self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.trial_dof)
return eval_trial_inner
def _make_eval_grad_inner(self):
if not self.gradient_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_nabla_trial_inner(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_inner_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
grad_transform = self.space.element_inner_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_outer(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.trial_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_nabla_trial_inner
def _make_eval_div_inner(self):
if not self.divergence_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_div_trial_inner(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_inner_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
grad_transform = self.space.element_inner_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_inner(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.trial_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_div_trial_inner
def _make_eval_outer(self):
@cache.dynamic_func(suffix=self.name)
def eval_trial_outer(args: self.ElementEvalArg, s: Sample):
weight = self.space.element_outer_weight(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
return weight * self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.trial_dof)
return eval_trial_outer
def _make_eval_grad_outer(self):
if not self.gradient_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_nabla_trial_outer(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_outer_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
grad_transform = self.space.element_outer_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_outer(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.trial_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_nabla_trial_outer
def _make_eval_div_outer(self):
if not self.divergence_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_div_trial_outer(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_outer_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.trial_dof),
)
grad_transform = self.space.element_outer_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_inner(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.trial_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_div_trial_outer
def _make_at_node(self):
@cache.dynamic_func(suffix=self.name)
def at_node(args: self.ElementEvalArg, s: Sample):
node_coords = self.space.node_coords_in_element(
args.elt_arg, args.eval_arg, s.element_index, get_node_index_in_element(s.trial_dof)
)
return Sample(s.element_index, node_coords, s.qp_index, s.qp_weight, s.test_dof, s.trial_dof)
return at_node
| 6,918 | Python | 36.603261 | 105 | 0.593235 |
NVIDIA/warp/warp/fem/field/restriction.py | from warp.fem.space import SpaceRestriction
from .field import DiscreteField
class FieldRestriction:
"""Restriction of a discrete field to a given GeometryDomain"""
def __init__(self, space_restriction: SpaceRestriction, field: DiscreteField):
if field.space.dimension - 1 == space_restriction.space_topology.dimension:
field = field.trace()
if field.space.dimension != space_restriction.space_topology.dimension:
raise ValueError("Incompatible space and field dimensions")
if field.space.topology != space_restriction.space_topology:
raise ValueError("Incompatible field and space restriction topologies")
self.space_restriction = space_restriction
self.domain = self.space_restriction.domain
self.field = field
self.space = self.field.space
| 850 | Python | 35.999998 | 83 | 0.705882 |
NVIDIA/warp/warp/fem/field/field.py | from typing import Any
import warp as wp
from warp.fem.geometry import DeformedGeometry, Geometry
from warp.fem.space import FunctionSpace, SpacePartition
from warp.fem.types import Sample
class FieldLike:
"""Base class for integrable fields"""
EvalArg: wp.codegen.Struct
"""Structure containing field-level arguments passed to device functions for field evaluation"""
ElementEvalArg: wp.codegen.Struct
"""Structure combining geometry-level and field-level arguments passed to device functions for field evaluation"""
def eval_arg_value(self, device) -> "EvalArg": # noqa: F821
"""Value of the field-level arguments to be passed to device functions"""
raise NotImplementedError
@property
def degree(self) -> int:
"""Polynomial degree of the field, used to estimate necessary quadrature order"""
raise NotImplementedError
@property
def name(self) -> str:
raise NotImplementedError
@property
def __str__(self) -> str:
return self.name
def eval_arg_value(self, device):
"""Value of arguments to be passed to device functions"""
raise NotImplementedError
@staticmethod
def eval_inner(args: "ElementEvalArg", s: "Sample"): # noqa: F821
"""Device function evaluating the inner field value at a sample point"""
raise NotImplementedError
@staticmethod
def eval_grad_inner(args: "ElementEvalArg", s: "Sample"): # noqa: F821
"""Device function evaluating the inner field gradient at a sample point"""
raise NotImplementedError
@staticmethod
def eval_div_inner(args: "ElementEvalArg", s: "Sample"): # noqa: F821
"""Device function evaluating the inner field divergence at a sample point"""
raise NotImplementedError
@staticmethod
def eval_outer(args: "ElementEvalArg", s: "Sample"): # noqa: F821
"""Device function evaluating the outer field value at a sample point"""
raise NotImplementedError
@staticmethod
def eval_grad_outer(args: "ElementEvalArg", s: "Sample"): # noqa: F821
"""Device function evaluating the outer field gradient at a sample point"""
raise NotImplementedError
@staticmethod
def eval_div_outer(args: "ElementEvalArg", s: "Sample"): # noqa: F821
"""Device function evaluating the outer field divergence at a sample point"""
raise NotImplementedError
class SpaceField(FieldLike):
"""Base class for fields defined over a function space"""
def __init__(self, space: FunctionSpace, space_partition: SpacePartition):
self._space = space
self._space_partition = space_partition
@property
def space(self) -> FunctionSpace:
return self._space
@property
def space_partition(self) -> SpacePartition:
return self._space_partition
@property
def degree(self) -> int:
return self.space.degree
@property
def dtype(self) -> type:
return self.space.dtype
@property
def dof_dtype(self) -> type:
return self.space.dof_dtype
def gradient_valid(self) -> bool:
"""Whether gradient operator can be computed. Only for scalar and vector fields as higher-order tensors are not support yet"""
return not wp.types.type_is_matrix(self.dtype)
def divergence_valid(self) -> bool:
"""Whether divergence of this field can be computed. Only for vector and tensor fields with same dimension as embedding geometry"""
if wp.types.type_is_vector(self.dtype):
return wp.types.type_length(self.dtype) == self.space.geometry.dimension
if wp.types.type_is_matrix(self.dtype):
return self.dtype._shape_[0] == self.space.geometry.dimension
return False
def _make_eval_degree(self):
ORDER = self.space.ORDER
from warp.fem import cache
@cache.dynamic_func(suffix=self.name)
def degree(args: self.ElementEvalArg):
return ORDER
return degree
class DiscreteField(SpaceField):
"""Explicitly-valued field defined over a partition of a discrete function space"""
@property
def dof_values(self) -> wp.array:
"""Array of degrees of freedom values"""
raise NotImplementedError
@dof_values.setter
def dof_values(self, values: wp.array):
"""Sets degrees of freedom values from an array"""
raise NotImplementedError
def trace(self) -> "DiscreteField":
"""Trace of this field over a lower-dimensional function space"""
raise NotImplementedError
@staticmethod
def set_node_value(args: "FieldLike.EvalArg", node_index: int, value: Any):
"""Device function setting the value at given node"""
raise NotImplementedError
@property
def name(self) -> str:
return f"{self.__class__.__qualname__}_{self.space.name}_{self.space_partition.name}"
def make_deformed_geometry(self) -> Geometry:
"""Returns a deformed version of the underlying geometry using this field's values as displacement"""
return DeformedGeometry(self)
| 5,138 | Python | 33.489933 | 139 | 0.672635 |
NVIDIA/warp/warp/fem/field/__init__.py | from typing import Optional, Union
from warp.fem.domain import Cells, GeometryDomain
from warp.fem.space import FunctionSpace, SpacePartition, SpaceRestriction, make_space_partition, make_space_restriction
from .field import DiscreteField, FieldLike, SpaceField
from .nodal_field import NodalField
from .restriction import FieldRestriction
from .test import TestField
from .trial import TrialField
def make_restriction(
field: DiscreteField,
space_restriction: Optional[SpaceRestriction] = None,
domain: Optional[GeometryDomain] = None,
device=None,
) -> FieldRestriction:
"""
Restricts a discrete field to a subset of elements.
Args:
field: the discrete field to restrict
space_restriction: the function space restriction defining the subset of elements to consider
domain: if ``space_restriction`` is not provided, the :py:class:`Domain` defining the subset of elements to consider
device: Warp device on which to perform and store computations
Returns:
the field restriction
"""
if space_restriction is None:
space_restriction = make_space_restriction(space_partition=field.space_partition, domain=domain, device=device)
return FieldRestriction(field=field, space_restriction=space_restriction)
def make_test(
space: FunctionSpace,
space_restriction: Optional[SpaceRestriction] = None,
space_partition: Optional[SpacePartition] = None,
domain: Optional[GeometryDomain] = None,
device=None,
) -> TestField:
"""
Constructs a test field over a function space or its restriction
Args:
space: the function space
space_restriction: restriction of the space topology to a domain
space_partition: if `space_restriction` is ``None``, the optional subset of node indices to consider
domain: if `space_restriction` is ``None``, optional subset of elements to consider
device: Warp device on which to perform and store computations
Returns:
the test field
"""
if space_restriction is None:
space_restriction = make_space_restriction(
space_topology=space.topology, space_partition=space_partition, domain=domain, device=device
)
return TestField(space_restriction=space_restriction, space=space)
def make_trial(
space: FunctionSpace,
space_restriction: Optional[SpaceRestriction] = None,
space_partition: Optional[SpacePartition] = None,
domain: Optional[GeometryDomain] = None,
) -> TrialField:
"""
Constructs a trial field over a function space or partition
Args:
space: the function space or function space restriction
space_restriction: restriction of the space topology to a domain
space_partition: if `space_restriction` is ``None``, the optional subset of node indices to consider
domain: if `space_restriction` is ``None``, optional subset of elements to consider
device: Warp device on which to perform and store computations
Returns:
the trial field
"""
if space_restriction is not None:
domain = space.domain
space_partition = space.space_partition
if space_partition is None:
if domain is None:
domain = Cells(geometry=space.geometry)
space_partition = make_space_partition(
space_topology=space.topology, geometry_partition=domain.geometry_partition
)
elif domain is None:
domain = Cells(geometry=space_partition.geo_partition)
return TrialField(space, space_partition, domain)
| 3,591 | Python | 34.564356 | 124 | 0.711501 |
NVIDIA/warp/warp/fem/field/test.py | import warp as wp
from warp.fem import cache, utils
from warp.fem.space import FunctionSpace, SpaceRestriction
from warp.fem.types import Sample, get_node_index_in_element
from .field import SpaceField
class TestField(SpaceField):
"""Field defined over a space restriction that can be used as a test function.
In order to reuse computations, it is possible to define the test field using a SpaceRestriction
defined for a different value type than the test function value type, as long as the node topology is similar.
"""
def __init__(self, space_restriction: SpaceRestriction, space: FunctionSpace):
if space_restriction.domain.dimension == space.dimension - 1:
space = space.trace()
if space_restriction.domain.dimension != space.dimension:
raise ValueError("Incompatible space and domain dimensions")
if space.topology != space_restriction.space_topology:
raise ValueError("Incompatible space and space partition topologies")
super().__init__(space, space_restriction.space_partition)
self.space_restriction = space_restriction
self.domain = self.space_restriction.domain
self.EvalArg = self.space.SpaceArg
self.ElementEvalArg = self._make_element_eval_arg()
self.eval_degree = self._make_eval_degree()
self.eval_inner = self._make_eval_inner()
self.eval_grad_inner = self._make_eval_grad_inner()
self.eval_div_inner = self._make_eval_div_inner()
self.eval_outer = self._make_eval_outer()
self.eval_grad_outer = self._make_eval_grad_outer()
self.eval_div_outer = self._make_eval_div_outer()
self.at_node = self._make_at_node()
@property
def name(self) -> str:
return self.space.name + "Test"
def eval_arg_value(self, device) -> wp.codegen.StructInstance:
return self.space.space_arg_value(device)
def _make_element_eval_arg(self):
from warp.fem import cache
@cache.dynamic_struct(suffix=self.name)
class ElementEvalArg:
elt_arg: self.domain.ElementArg
eval_arg: self.EvalArg
return ElementEvalArg
def _make_eval_inner(self):
@cache.dynamic_func(suffix=self.name)
def eval_test_inner(args: self.ElementEvalArg, s: Sample):
weight = self.space.element_inner_weight(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
return weight * self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.test_dof)
return eval_test_inner
def _make_eval_grad_inner(self):
if not self.gradient_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_nabla_test_inner(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_inner_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
grad_transform = self.space.element_inner_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_outer(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.test_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_nabla_test_inner
def _make_eval_div_inner(self):
if not self.divergence_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_div_test_inner(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_inner_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
grad_transform = self.space.element_inner_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_inner(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.test_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_div_test_inner
def _make_eval_outer(self):
@cache.dynamic_func(suffix=self.name)
def eval_test_outer(args: self.ElementEvalArg, s: Sample):
weight = self.space.element_outer_weight(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
return weight * self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.test_dof)
return eval_test_outer
def _make_eval_grad_outer(self):
if not self.gradient_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_nabla_test_outer(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_outer_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
grad_transform = self.space.element_outer_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_outer(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.test_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_nabla_test_outer
def _make_eval_div_outer(self):
if not self.divergence_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_div_test_outer(args: self.ElementEvalArg, s: Sample):
nabla_weight = self.space.element_outer_weight_gradient(
args.elt_arg,
args.eval_arg,
s.element_index,
s.element_coords,
get_node_index_in_element(s.test_dof),
)
grad_transform = self.space.element_outer_reference_gradient_transform(args.elt_arg, s)
return utils.generalized_inner(
self.space.unit_dof_value(args.elt_arg, args.eval_arg, s.test_dof),
utils.apply_right(nabla_weight, grad_transform),
)
return eval_div_test_outer
def _make_at_node(self):
@cache.dynamic_func(suffix=self.name)
def at_node(args: self.ElementEvalArg, s: Sample):
node_coords = self.space.node_coords_in_element(
args.elt_arg, args.eval_arg, s.element_index, get_node_index_in_element(s.test_dof)
)
return Sample(s.element_index, node_coords, s.qp_index, s.qp_weight, s.test_dof, s.trial_dof)
return at_node
| 6,994 | Python | 37.646409 | 114 | 0.5998 |
NVIDIA/warp/warp/fem/field/nodal_field.py | import warp as wp
from warp.fem import cache, utils
from warp.fem.space import CollocatedFunctionSpace, SpacePartition
from warp.fem.types import NULL_NODE_INDEX, ElementIndex, Sample
from .field import DiscreteField
class NodalFieldBase(DiscreteField):
"""Base class for nodal field and nodal field traces. Does not hold values"""
def __init__(self, space: CollocatedFunctionSpace, space_partition: SpacePartition):
super().__init__(space, space_partition)
self.EvalArg = self._make_eval_arg()
self.ElementEvalArg = self._make_element_eval_arg()
self.eval_degree = DiscreteField._make_eval_degree(self)
self._read_node_value = self._make_read_node_value()
self.eval_inner = self._make_eval_inner()
self.eval_outer = self._make_eval_outer()
self.eval_grad_inner = self._make_eval_grad_inner(world_space=True)
self.eval_grad_outer = self._make_eval_grad_outer(world_space=True)
self.eval_reference_grad_inner = self._make_eval_grad_inner(world_space=False)
self.eval_reference_grad_outer = self._make_eval_grad_outer(world_space=False)
self.eval_div_inner = self._make_eval_div_inner()
self.eval_div_outer = self._make_eval_div_outer()
self.set_node_value = self._make_set_node_value()
def _make_eval_arg(self):
@cache.dynamic_struct(suffix=self.name)
class EvalArg:
dof_values: wp.array(dtype=self.space.dof_dtype)
space_arg: self.space.SpaceArg
topology_arg: self.space.topology.TopologyArg
partition_arg: self.space_partition.PartitionArg
return EvalArg
def _make_element_eval_arg(self):
@cache.dynamic_struct(suffix=self.name)
class ElementEvalArg:
elt_arg: self.space.topology.ElementArg
eval_arg: self.EvalArg
return ElementEvalArg
def _make_read_node_value(self):
@cache.dynamic_func(suffix=self.name)
def read_node_value(args: self.ElementEvalArg, geo_element_index: ElementIndex, node_index_in_elt: int):
nidx = self.space.topology.element_node_index(
args.elt_arg, args.eval_arg.topology_arg, geo_element_index, node_index_in_elt
)
pidx = self.space_partition.partition_node_index(args.eval_arg.partition_arg, nidx)
if pidx == NULL_NODE_INDEX:
return self.space.dtype(0.0)
return self.space.dof_mapper.dof_to_value(args.eval_arg.dof_values[pidx])
return read_node_value
def _make_eval_inner(self):
NODES_PER_ELEMENT = self.space.topology.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def eval_inner(args: self.ElementEvalArg, s: Sample):
res = self.space.element_inner_weight(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, 0
) * self._read_node_value(args, s.element_index, 0)
for k in range(1, NODES_PER_ELEMENT):
res += self.space.element_inner_weight(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, k
) * self._read_node_value(args, s.element_index, k)
return res
return eval_inner
def _make_eval_grad_inner(self, world_space: bool):
NODES_PER_ELEMENT = self.space.topology.NODES_PER_ELEMENT
if not self.gradient_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_grad_inner_ref_space(args: self.ElementEvalArg, s: Sample):
res = utils.generalized_outer(
self._read_node_value(args, s.element_index, 0),
self.space.element_inner_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, 0
),
)
for k in range(1, NODES_PER_ELEMENT):
res += utils.generalized_outer(
self._read_node_value(args, s.element_index, k),
self.space.element_inner_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, k
),
)
return res
@cache.dynamic_func(suffix=self.name)
def eval_grad_inner_world_space(args: self.ElementEvalArg, s: Sample):
grad_transform = self.space.element_inner_reference_gradient_transform(args.elt_arg, s)
res = eval_grad_inner_ref_space(args, s)
return utils.apply_right(res, grad_transform)
return eval_grad_inner_world_space if world_space else eval_grad_inner_ref_space
def _make_eval_div_inner(self):
NODES_PER_ELEMENT = self.space.topology.NODES_PER_ELEMENT
if not self.divergence_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_div_inner(args: self.ElementEvalArg, s: Sample):
grad_transform = self.space.element_inner_reference_gradient_transform(args.elt_arg, s)
res = utils.generalized_inner(
self._read_node_value(args, s.element_index, 0),
utils.apply_right(
self.space.element_inner_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, 0
),
grad_transform,
),
)
for k in range(1, NODES_PER_ELEMENT):
res += utils.generalized_inner(
self._read_node_value(args, s.element_index, k),
utils.apply_right(
self.space.element_inner_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, k
),
grad_transform,
),
)
return res
return eval_div_inner
def _make_eval_outer(self):
NODES_PER_ELEMENT = self.space.topology.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def eval_outer(args: self.ElementEvalArg, s: Sample):
res = self.space.element_outer_weight(
args.elt_arg,
args.eval_arg.space_arg,
s.element_index,
s.element_coords,
0,
) * self._read_node_value(args, s.element_index, 0)
for k in range(1, NODES_PER_ELEMENT):
res += self.space.element_outer_weight(
args.elt_arg,
args.eval_arg.space_arg,
s.element_index,
s.element_coords,
k,
) * self._read_node_value(args, s.element_index, k)
return res
return eval_outer
def _make_eval_grad_outer(self, world_space: bool):
NODES_PER_ELEMENT = self.space.topology.NODES_PER_ELEMENT
if not self.gradient_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_grad_outer_ref_space(args: self.ElementEvalArg, s: Sample):
res = utils.generalized_outer(
self._read_node_value(args, s.element_index, 0),
self.space.element_outer_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, 0
),
)
for k in range(1, NODES_PER_ELEMENT):
res += utils.generalized_outer(
self._read_node_value(args, s.element_index, k),
self.space.element_outer_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, k
),
)
return res
@cache.dynamic_func(suffix=self.name)
def eval_grad_outer_world_space(args: self.ElementEvalArg, s: Sample):
grad_transform = self.space.element_outer_reference_gradient_transform(args.elt_arg, s)
res = eval_grad_outer_ref_space(args, s)
return utils.apply_right(res, grad_transform)
return eval_grad_outer_world_space if world_space else eval_grad_outer_ref_space
def _make_eval_div_outer(self):
NODES_PER_ELEMENT = self.space.topology.NODES_PER_ELEMENT
if not self.divergence_valid():
return None
@cache.dynamic_func(suffix=self.name)
def eval_div_outer(args: self.ElementEvalArg, s: Sample):
grad_transform = self.space.element_outer_reference_gradient_transform(args.elt_arg, s)
res = utils.generalized_inner(
self._read_node_value(args, s.element_index, 0),
utils.apply_right(
self.space.element_outer_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, 0
),
grad_transform,
),
)
for k in range(1, NODES_PER_ELEMENT):
res += utils.generalized_inner(
self._read_node_value(args, s.element_index, k),
utils.apply_right(
self.space.element_outer_weight_gradient(
args.elt_arg, args.eval_arg.space_arg, s.element_index, s.element_coords, k
),
grad_transform,
),
)
return res
return eval_div_outer
def _make_set_node_value(self):
@cache.dynamic_func(suffix=self.name)
def set_node_value(args: self.EvalArg, partition_node_index: int, value: self.space.dtype):
args.dof_values[partition_node_index] = self.space.dof_mapper.value_to_dof(value)
return set_node_value
class NodalField(NodalFieldBase):
"""A field holding values for all degrees of freedom at each node of the underlying function space partition
See also: warp.fem.space.CollocatedFunctionSpace.make_field
"""
def __init__(self, space: CollocatedFunctionSpace, space_partition: SpacePartition):
if space.topology != space_partition.space_topology:
raise ValueError("Incompatible space and space partition topologies")
super().__init__(space, space_partition)
self._dof_values = wp.zeros(n=self.space_partition.node_count(), dtype=self.dof_dtype)
def eval_arg_value(self, device):
arg = self.EvalArg()
arg.dof_values = self._dof_values.to(device)
arg.space_arg = self.space.space_arg_value(device)
arg.partition_arg = self.space_partition.partition_arg_value(device)
arg.topology_arg = self.space.topology.topo_arg_value(device)
return arg
@property
def dof_values(self) -> wp.array:
"""Returns a warp array containing the values at all degrees of freedom of the underlying space partition"""
return self._dof_values
@dof_values.setter
def dof_values(self, values):
"""Sets the degrees-of-freedom values
Args:
values: Array that is convertible to a warp array of length ``self.space_partition.node_count()`` and data type ``self.space.dof_dtype``
"""
if isinstance(values, wp.array):
self._dof_values = values
else:
self._dof_values = wp.array(values, dtype=self.dof_dtype)
class Trace(NodalFieldBase):
def __init__(self, field):
self._field = field
super().__init__(field.space.trace(), field.space_partition)
def eval_arg_value(self, device):
arg = self.EvalArg()
arg.dof_values = self._field.dof_values.to(device)
arg.space_arg = self.space.space_arg_value(device)
arg.partition_arg = self.space_partition.partition_arg_value(device)
arg.topology_arg = self.space.topology.topo_arg_value(device)
return arg
def trace(self) -> Trace:
trace_field = NodalField.Trace(self)
return trace_field
| 12,223 | Python | 39.882943 | 148 | 0.587744 |
NVIDIA/warp/warp/fem/space/grid_3d_function_space.py | import numpy as np
import warp as wp
from warp.fem import cache
from warp.fem.geometry import Grid3D
from warp.fem.polynomial import is_closed
from warp.fem.types import ElementIndex
from .shape import (
CubeSerendipityShapeFunctions,
CubeTripolynomialShapeFunctions,
ShapeFunction,
)
from .topology import SpaceTopology, forward_base_topology
class Grid3DSpaceTopology(SpaceTopology):
def __init__(self, grid: Grid3D, shape: ShapeFunction):
if not is_closed(shape.family):
raise ValueError("A closed polynomial family is required to define a continuous function space")
super().__init__(grid, shape.NODES_PER_ELEMENT)
self._shape = shape
self._grid = grid
@wp.func
def _vertex_coords(vidx_in_cell: int):
x = vidx_in_cell // 4
y = (vidx_in_cell - 4 * x) // 2
z = vidx_in_cell - 4 * x - 2 * y
return wp.vec3i(x, y, z)
@wp.func
def _vertex_index(cell_arg: Grid3D.CellArg, cell_index: ElementIndex, vidx_in_cell: int):
res = cell_arg.res
strides = wp.vec2i((res[1] + 1) * (res[2] + 1), res[2] + 1)
corner = Grid3D.get_cell(res, cell_index) + Grid3DSpaceTopology._vertex_coords(vidx_in_cell)
return Grid3D._from_3d_index(strides, corner)
class GridTripolynomialSpaceTopology(Grid3DSpaceTopology):
def __init__(self, grid: Grid3D, shape: CubeTripolynomialShapeFunctions):
super().__init__(grid, shape)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return (
(self.geometry.res[0] * self._shape.ORDER + 1)
* (self.geometry.res[1] * self._shape.ORDER + 1)
* (self.geometry.res[2] * self._shape.ORDER + 1)
)
def _make_element_node_index(self):
ORDER = self._shape.ORDER
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Grid3D.CellArg,
topo_arg: Grid3DSpaceTopology.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
res = cell_arg.res
cell = Grid3D.get_cell(res, element_index)
node_i, node_j, node_k = self._shape._node_ijk(node_index_in_elt)
node_x = ORDER * cell[0] + node_i
node_y = ORDER * cell[1] + node_j
node_z = ORDER * cell[2] + node_k
node_pitch_y = (res[2] * ORDER) + 1
node_pitch_x = node_pitch_y * ((res[1] * ORDER) + 1)
node_index = node_pitch_x * node_x + node_pitch_y * node_y + node_z
return node_index
return element_node_index
def _node_grid(self):
res = self.geometry.res
cell_coords = np.array(self._shape.LOBATTO_COORDS)[:-1]
grid_coords_x = np.repeat(np.arange(0, res[0], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[0]
)
grid_coords_x = np.append(grid_coords_x, res[0])
X = grid_coords_x * self._grid.cell_size[0] + self._grid.origin[0]
grid_coords_y = np.repeat(np.arange(0, res[1], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[1]
)
grid_coords_y = np.append(grid_coords_y, res[1])
Y = grid_coords_y * self._grid.cell_size[1] + self._grid.origin[1]
grid_coords_z = np.repeat(np.arange(0, res[2], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[2]
)
grid_coords_z = np.append(grid_coords_z, res[2])
Z = grid_coords_z * self._grid.cell_size[2] + self._grid.origin[2]
return np.meshgrid(X, Y, Z, indexing="ij")
class Grid3DSerendipitySpaceTopology(Grid3DSpaceTopology):
def __init__(self, grid: Grid3D, shape: CubeSerendipityShapeFunctions):
super().__init__(grid, shape)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return self.geometry.vertex_count() + (self._shape.ORDER - 1) * self.geometry.edge_count()
def _make_element_node_index(self):
ORDER = self._shape.ORDER
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Grid3D.CellArg,
topo_arg: Grid3DSpaceTopology.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
res = cell_arg.res
cell = Grid3D.get_cell(res, element_index)
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == CubeSerendipityShapeFunctions.VERTEX:
return Grid3DSpaceTopology._vertex_index(cell_arg, element_index, type_index)
axis = CubeSerendipityShapeFunctions._edge_axis(node_type)
node_all = CubeSerendipityShapeFunctions._edge_coords(type_index)
res = cell_arg.res
edge_index = 0
if axis > 0:
edge_index += (res[1] + 1) * (res[2] + 1) * res[0]
if axis > 1:
edge_index += (res[0] + 1) * (res[2] + 1) * res[1]
res_loc = Grid3D._world_to_local(axis, res)
cell_loc = Grid3D._world_to_local(axis, cell)
edge_index += (res_loc[1] + 1) * (res_loc[2] + 1) * cell_loc[0]
edge_index += (res_loc[2] + 1) * (cell_loc[1] + node_all[1])
edge_index += cell_loc[2] + node_all[2]
vertex_count = (res[0] + 1) * (res[1] + 1) * (res[2] + 1)
return vertex_count + (ORDER - 1) * edge_index + (node_all[0] - 1)
return element_node_index
def make_grid_3d_space_topology(grid: Grid3D, shape: ShapeFunction):
if isinstance(shape, CubeSerendipityShapeFunctions):
return forward_base_topology(Grid3DSerendipitySpaceTopology, grid, shape)
if isinstance(shape, CubeTripolynomialShapeFunctions):
return forward_base_topology(GridTripolynomialSpaceTopology, grid, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 6,042 | Python | 34.970238 | 108 | 0.595664 |
NVIDIA/warp/warp/fem/space/nanogrid_function_space.py | import warp as wp
from warp.fem import cache
from warp.fem.geometry import Nanogrid
from warp.fem.geometry.nanogrid import _add_axis_flag
from warp.fem.polynomial import is_closed
from warp.fem.types import ElementIndex
from .shape import (
CubeSerendipityShapeFunctions,
CubeTripolynomialShapeFunctions,
ShapeFunction,
)
from .topology import SpaceTopology, forward_base_topology
@wp.struct
class NanogridTopologyArg:
vertex_grid: wp.uint64
face_grid: wp.uint64
edge_grid: wp.uint64
vertex_count: int
edge_count: int
face_count: int
class NanogridSpaceTopology(SpaceTopology):
TopologyArg = NanogridTopologyArg
def __init__(
self,
grid: Nanogrid,
shape: ShapeFunction,
need_edge_indices: bool = True,
need_face_indices: bool = True,
):
if not is_closed(shape.family):
raise ValueError("A closed polynomial family is required to define a continuous function space")
super().__init__(grid, shape.NODES_PER_ELEMENT)
self._grid = grid
self._shape = shape
if need_edge_indices:
self._edge_count = self._grid.edge_count()
else:
self._edge_count = 0
self._vertex_grid = grid._node_grid
self._face_grid = grid._face_grid
self._edge_grid = grid._edge_grid
@cache.cached_arg_value
def topo_arg_value(self, device):
arg = NanogridTopologyArg()
arg.vertex_grid = self._vertex_grid.id
arg.face_grid = self._face_grid.id
arg.edge_grid = -1 if self._edge_grid is None else self._edge_grid.id
arg.vertex_count = self._grid.vertex_count()
arg.face_count = self._grid.side_count()
arg.edge_count = self._edge_count
return arg
@wp.func
def _cell_vertex_coord(cell_ijk: wp.vec3i, n: int):
return cell_ijk + wp.vec3i((n & 4) >> 2, (n & 2) >> 1, n & 1)
@wp.func
def _cell_edge_coord(cell_ijk: wp.vec3i, axis: int, offset: int):
e_ijk = cell_ijk
e_ijk[(axis + 1) % 3] += offset >> 1
e_ijk[(axis + 2) % 3] += offset & 1
return _add_axis_flag(e_ijk, axis)
@wp.func
def _cell_face_coord(cell_ijk: wp.vec3i, axis: int, offset: int):
f_ijk = cell_ijk
f_ijk[axis] += offset
return _add_axis_flag(f_ijk, axis)
class NanogridTripolynomialSpaceTopology(NanogridSpaceTopology):
def __init__(self, grid: Nanogrid, shape: CubeTripolynomialShapeFunctions):
super().__init__(grid, shape, need_edge_indices=shape.ORDER >= 2, need_face_indices=shape.ORDER >= 2)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
ORDER = self._shape.ORDER
INTERIOR_NODES_PER_EDGE = max(0, ORDER - 1)
INTERIOR_NODES_PER_FACE = INTERIOR_NODES_PER_EDGE**2
INTERIOR_NODES_PER_CELL = INTERIOR_NODES_PER_EDGE**3
return (
self._grid.vertex_count()
+ self._grid.edge_count() * INTERIOR_NODES_PER_EDGE
+ self._grid.side_count() * INTERIOR_NODES_PER_FACE
+ self._grid.cell_count() * INTERIOR_NODES_PER_CELL
)
def _make_element_node_index(self):
ORDER = self._shape.ORDER
INTERIOR_NODES_PER_EDGE = wp.constant(max(0, ORDER - 1))
INTERIOR_NODES_PER_FACE = wp.constant(INTERIOR_NODES_PER_EDGE**2)
INTERIOR_NODES_PER_CELL = wp.constant(INTERIOR_NODES_PER_EDGE**3)
@cache.dynamic_func(suffix=self.name)
def element_node_index(
geo_arg: Nanogrid.CellArg,
topo_arg: NanogridTopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_instance, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
ijk = geo_arg.cell_ijk[element_index]
if node_type == CubeTripolynomialShapeFunctions.VERTEX:
n_ijk = _cell_vertex_coord(ijk, type_instance)
return wp.volume_lookup_index(topo_arg.vertex_grid, n_ijk[0], n_ijk[1], n_ijk[2])
offset = topo_arg.vertex_count
if node_type == CubeTripolynomialShapeFunctions.EDGE:
axis = type_instance >> 2
node_offset = type_instance & 3
n_ijk = _cell_edge_coord(ijk, axis, node_offset)
edge_index = wp.volume_lookup_index(topo_arg.edge_grid, n_ijk[0], n_ijk[1], n_ijk[2])
return offset + INTERIOR_NODES_PER_EDGE * edge_index + type_index
offset += INTERIOR_NODES_PER_EDGE * topo_arg.edge_count
if node_type == CubeTripolynomialShapeFunctions.FACE:
axis = type_instance >> 1
node_offset = type_instance & 1
n_ijk = _cell_face_coord(ijk, axis, node_offset)
face_index = wp.volume_lookup_index(topo_arg.face_grid, n_ijk[0], n_ijk[1], n_ijk[2])
return offset + INTERIOR_NODES_PER_FACE * face_index + type_index
offset += INTERIOR_NODES_PER_FACE * topo_arg.face_count
return offset + INTERIOR_NODES_PER_CELL * element_index + type_index
return element_node_index
class NanogridSerendipitySpaceTopology(NanogridSpaceTopology):
def __init__(self, grid: Nanogrid, shape: CubeSerendipityShapeFunctions):
super().__init__(grid, shape, need_edge_indices=True, need_face_indices=False)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return self.geometry.vertex_count() + (self._shape.ORDER - 1) * self.geometry.edge_count()
def _make_element_node_index(self):
ORDER = self._shape.ORDER
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Nanogrid.CellArg,
topo_arg: NanogridSpaceTopology.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
ijk = cell_arg.cell_ijk[element_index]
if node_type == CubeSerendipityShapeFunctions.VERTEX:
n_ijk = _cell_vertex_coord(ijk, type_index)
return wp.volume_lookup_index(topo_arg.vertex_grid, n_ijk[0], n_ijk[1], n_ijk[2])
type_instance, index_in_edge = CubeSerendipityShapeFunctions._cube_edge_index(node_type, type_index)
axis = type_instance >> 2
node_offset = type_instance & 3
n_ijk = _cell_edge_coord(ijk, axis, node_offset)
edge_index = wp.volume_lookup_index(topo_arg.edge_grid, n_ijk[0], n_ijk[1], n_ijk[2])
return topo_arg.vertex_count + (ORDER - 1) * edge_index + index_in_edge
return element_node_index
def make_nanogrid_space_topology(grid: Nanogrid, shape: ShapeFunction):
if isinstance(shape, CubeSerendipityShapeFunctions):
return forward_base_topology(NanogridSerendipitySpaceTopology, grid, shape)
if isinstance(shape, CubeTripolynomialShapeFunctions):
return forward_base_topology(NanogridTripolynomialSpaceTopology, grid, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 7,205 | Python | 34.497537 | 112 | 0.626926 |
NVIDIA/warp/warp/fem/space/quadmesh_2d_function_space.py | import warp as wp
from warp.fem import cache
from warp.fem.geometry import Quadmesh2D
from warp.fem.polynomial import is_closed
from warp.fem.types import ElementIndex
from .shape import (
ShapeFunction,
SquareBipolynomialShapeFunctions,
SquareSerendipityShapeFunctions,
)
from .topology import SpaceTopology, forward_base_topology
@wp.struct
class Quadmesh2DTopologyArg:
edge_vertex_indices: wp.array(dtype=wp.vec2i)
quad_edge_indices: wp.array2d(dtype=int)
vertex_count: int
edge_count: int
class Quadmesh2DSpaceTopology(SpaceTopology):
TopologyArg = Quadmesh2DTopologyArg
def __init__(self, mesh: Quadmesh2D, shape: ShapeFunction):
if not is_closed(shape.family):
raise ValueError("A closed polynomial family is required to define a continuous function space")
super().__init__(mesh, shape.NODES_PER_ELEMENT)
self._mesh = mesh
self._shape = shape
self._compute_quad_edge_indices()
@cache.cached_arg_value
def topo_arg_value(self, device):
arg = Quadmesh2DTopologyArg()
arg.quad_edge_indices = self._quad_edge_indices.to(device)
arg.edge_vertex_indices = self._mesh.edge_vertex_indices.to(device)
arg.vertex_count = self._mesh.vertex_count()
arg.edge_count = self._mesh.side_count()
return arg
def _compute_quad_edge_indices(self):
self._quad_edge_indices = wp.empty(
dtype=int, device=self._mesh.quad_vertex_indices.device, shape=(self._mesh.cell_count(), 4)
)
wp.launch(
kernel=Quadmesh2DSpaceTopology._compute_quad_edge_indices_kernel,
dim=self._mesh.edge_quad_indices.shape,
device=self._mesh.quad_vertex_indices.device,
inputs=[
self._mesh.edge_quad_indices,
self._mesh.edge_vertex_indices,
self._mesh.quad_vertex_indices,
self._quad_edge_indices,
],
)
@wp.func
def _find_edge_index_in_quad(
edge_vtx: wp.vec2i,
quad_vtx: wp.vec4i,
):
for k in range(3):
if (edge_vtx[0] == quad_vtx[k] and edge_vtx[1] == quad_vtx[k + 1]) or (
edge_vtx[1] == quad_vtx[k] and edge_vtx[0] == quad_vtx[k + 1]
):
return k
return 3
@wp.kernel
def _compute_quad_edge_indices_kernel(
edge_quad_indices: wp.array(dtype=wp.vec2i),
edge_vertex_indices: wp.array(dtype=wp.vec2i),
quad_vertex_indices: wp.array2d(dtype=int),
quad_edge_indices: wp.array2d(dtype=int),
):
e = wp.tid()
edge_vtx = edge_vertex_indices[e]
edge_quads = edge_quad_indices[e]
q0 = edge_quads[0]
q0_vtx = wp.vec4i(
quad_vertex_indices[q0, 0],
quad_vertex_indices[q0, 1],
quad_vertex_indices[q0, 2],
quad_vertex_indices[q0, 3],
)
q0_edge = Quadmesh2DSpaceTopology._find_edge_index_in_quad(edge_vtx, q0_vtx)
quad_edge_indices[q0, q0_edge] = e
q1 = edge_quads[1]
if q1 != q0:
t1_vtx = wp.vec4i(
quad_vertex_indices[q1, 0],
quad_vertex_indices[q1, 1],
quad_vertex_indices[q1, 2],
quad_vertex_indices[q1, 3],
)
t1_edge = Quadmesh2DSpaceTopology._find_edge_index_in_quad(edge_vtx, t1_vtx)
quad_edge_indices[q1, t1_edge] = e
class Quadmesh2DBipolynomialSpaceTopology(Quadmesh2DSpaceTopology):
def __init__(self, mesh: Quadmesh2D, shape: SquareBipolynomialShapeFunctions):
super().__init__(mesh, shape)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
ORDER = self._shape.ORDER
INTERIOR_NODES_PER_SIDE = max(0, ORDER - 1)
INTERIOR_NODES_PER_CELL = INTERIOR_NODES_PER_SIDE**2
return (
self._mesh.vertex_count()
+ self._mesh.side_count() * INTERIOR_NODES_PER_SIDE
+ self._mesh.cell_count() * INTERIOR_NODES_PER_CELL
)
def _make_element_node_index(self):
ORDER = self._shape.ORDER
INTERIOR_NODES_PER_SIDE = wp.constant(max(0, ORDER - 1))
INTERIOR_NODES_PER_CELL = wp.constant(INTERIOR_NODES_PER_SIDE**2)
@cache.dynamic_func(suffix=self.name)
def element_node_index(
geo_arg: Quadmesh2D.CellArg,
topo_arg: Quadmesh2DTopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
# Vertices
if node_i == 0:
if node_j == 0:
return geo_arg.quad_vertex_indices[element_index, 0]
elif node_j == ORDER:
return geo_arg.quad_vertex_indices[element_index, 3]
# 3-0 edge
side_index = topo_arg.quad_edge_indices[element_index, 3]
local_vs = geo_arg.quad_vertex_indices[element_index, 3]
global_vs = topo_arg.edge_vertex_indices[side_index][0]
index_in_side = wp.select(local_vs == global_vs, ORDER - node_j, node_j) - 1
return topo_arg.vertex_count + (ORDER - 1) * side_index + index_in_side
elif node_i == ORDER:
if node_j == 0:
return geo_arg.quad_vertex_indices[element_index, 1]
elif node_j == ORDER:
return geo_arg.quad_vertex_indices[element_index, 2]
# 1-2 edge
side_index = topo_arg.quad_edge_indices[element_index, 1]
local_vs = geo_arg.quad_vertex_indices[element_index, 1]
global_vs = topo_arg.edge_vertex_indices[side_index][0]
index_in_side = wp.select(local_vs == global_vs, ORDER - node_j, node_j) - 1
return topo_arg.vertex_count + (ORDER - 1) * side_index + index_in_side
if node_j == 0:
# 0-1 edge
side_index = topo_arg.quad_edge_indices[element_index, 0]
local_vs = geo_arg.quad_vertex_indices[element_index, 0]
global_vs = topo_arg.edge_vertex_indices[side_index][0]
index_in_side = wp.select(local_vs == global_vs, node_i, ORDER - node_i) - 1
return topo_arg.vertex_count + (ORDER - 1) * side_index + index_in_side
elif node_j == ORDER:
# 2-3 edge
side_index = topo_arg.quad_edge_indices[element_index, 2]
local_vs = geo_arg.quad_vertex_indices[element_index, 2]
global_vs = topo_arg.edge_vertex_indices[side_index][0]
index_in_side = wp.select(local_vs == global_vs, node_i, ORDER - node_i) - 1
return topo_arg.vertex_count + (ORDER - 1) * side_index + index_in_side
return (
topo_arg.vertex_count
+ topo_arg.edge_count * INTERIOR_NODES_PER_SIDE
+ element_index * INTERIOR_NODES_PER_CELL
+ (node_i - 1) * INTERIOR_NODES_PER_SIDE
+ node_j
- 1
)
return element_node_index
class Quadmesh2DSerendipitySpaceTopology(Quadmesh2DSpaceTopology):
def __init__(self, grid: Quadmesh2D, shape: SquareSerendipityShapeFunctions):
super().__init__(grid, shape)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return self.geometry.vertex_count() + (self._shape.ORDER - 1) * self.geometry.side_count()
def _make_element_node_index(self):
ORDER = self._shape.ORDER
SHAPE_TO_QUAD_IDX = wp.constant(wp.vec4i([0, 3, 1, 2]))
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Quadmesh2D.CellArg,
topo_arg: Quadmesh2DSpaceTopology.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == SquareSerendipityShapeFunctions.VERTEX:
return cell_arg.quad_vertex_indices[element_index, SHAPE_TO_QUAD_IDX[type_index]]
side_offset, index_in_side = SquareSerendipityShapeFunctions.side_offset_and_index(type_index)
if node_type == SquareSerendipityShapeFunctions.EDGE_X:
if side_offset == 0:
side_start = 0
else:
side_start = 2
index_in_side = ORDER - 2 - index_in_side
else:
if side_offset == 0:
side_start = 3
index_in_side = ORDER - 2 - index_in_side
else:
side_start = 1
side_index = topo_arg.quad_edge_indices[element_index, side_start]
local_vs = cell_arg.quad_vertex_indices[element_index, side_start]
global_vs = topo_arg.edge_vertex_indices[side_index][0]
if local_vs != global_vs:
# Flip indexing direction
index_in_side = ORDER - 2 - index_in_side
return topo_arg.vertex_count + (ORDER - 1) * side_index + index_in_side
return element_node_index
def make_quadmesh_2d_space_topology(mesh: Quadmesh2D, shape: ShapeFunction):
if isinstance(shape, SquareSerendipityShapeFunctions):
return forward_base_topology(Quadmesh2DSerendipitySpaceTopology, mesh, shape)
if isinstance(shape, SquareBipolynomialShapeFunctions):
return forward_base_topology(Quadmesh2DBipolynomialSpaceTopology, mesh, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 9,889 | Python | 36.748091 | 108 | 0.578319 |
NVIDIA/warp/warp/fem/space/restriction.py | import warp as wp
from warp.fem.cache import TemporaryStore, borrow_temporary, borrow_temporary_like, cached_arg_value
from warp.fem.domain import GeometryDomain
from warp.fem.types import NodeElementIndex
from warp.fem.utils import compress_node_indices
from .partition import SpacePartition
wp.set_module_options({"enable_backward": False})
class SpaceRestriction:
"""Restriction of a space partition to a given GeometryDomain"""
def __init__(
self,
space_partition: SpacePartition,
domain: GeometryDomain,
device=None,
temporary_store: TemporaryStore = None,
):
space_topology = space_partition.space_topology
if domain.dimension == space_topology.dimension - 1:
space_topology = space_topology.trace()
if domain.dimension != space_topology.dimension:
raise ValueError("Incompatible space and domain dimensions")
self.space_partition = space_partition
self.space_topology = space_topology
self.domain = domain
self._compute_node_element_indices(device=device, temporary_store=temporary_store)
def _compute_node_element_indices(self, device, temporary_store: TemporaryStore):
from warp.fem import cache
NODES_PER_ELEMENT = self.space_topology.NODES_PER_ELEMENT
@cache.dynamic_kernel(
suffix=f"{self.domain.name}_{self.space_topology.name}_{self.space_partition.name}",
kernel_options={"max_unroll": 8},
)
def fill_element_node_indices(
element_arg: self.domain.ElementArg,
domain_index_arg: self.domain.ElementIndexArg,
topo_arg: self.space_topology.TopologyArg,
partition_arg: self.space_partition.PartitionArg,
element_node_indices: wp.array2d(dtype=int),
):
domain_element_index = wp.tid()
element_index = self.domain.element_index(domain_index_arg, domain_element_index)
for n in range(NODES_PER_ELEMENT):
space_nidx = self.space_topology.element_node_index(element_arg, topo_arg, element_index, n)
partition_nidx = self.space_partition.partition_node_index(partition_arg, space_nidx)
element_node_indices[domain_element_index, n] = partition_nidx
element_node_indices = borrow_temporary(
temporary_store,
shape=(self.domain.element_count(), NODES_PER_ELEMENT),
dtype=int,
device=device,
)
wp.launch(
dim=element_node_indices.array.shape[0],
kernel=fill_element_node_indices,
inputs=[
self.domain.element_arg_value(device),
self.domain.element_index_arg_value(device),
self.space_topology.topo_arg_value(device),
self.space_partition.partition_arg_value(device),
element_node_indices.array,
],
device=device,
)
# Build compressed map from node to element indices
flattened_node_indices = element_node_indices.array.flatten()
(
self._dof_partition_element_offsets,
node_array_indices,
self._node_count,
self._dof_partition_indices,
) = compress_node_indices(
self.space_partition.node_count(), flattened_node_indices, temporary_store=temporary_store
)
# Extract element index and index in element
self._dof_element_indices = borrow_temporary_like(flattened_node_indices, temporary_store)
self._dof_indices_in_element = borrow_temporary_like(flattened_node_indices, temporary_store)
wp.launch(
kernel=SpaceRestriction._split_vertex_element_index,
dim=flattened_node_indices.shape,
inputs=[
NODES_PER_ELEMENT,
node_array_indices.array,
self._dof_element_indices.array,
self._dof_indices_in_element.array,
],
device=flattened_node_indices.device,
)
node_array_indices.release()
def node_count(self):
return self._node_count
def partition_element_offsets(self):
return self._dof_partition_element_offsets.array
def node_partition_indices(self):
return self._dof_partition_indices.array
def total_node_element_count(self):
return self._dof_element_indices.array.size
@wp.struct
class NodeArg:
dof_element_offsets: wp.array(dtype=int)
dof_element_indices: wp.array(dtype=int)
dof_partition_indices: wp.array(dtype=int)
dof_indices_in_element: wp.array(dtype=int)
@cached_arg_value
def node_arg(self, device):
arg = SpaceRestriction.NodeArg()
arg.dof_element_offsets = self._dof_partition_element_offsets.array.to(device)
arg.dof_element_indices = self._dof_element_indices.array.to(device)
arg.dof_partition_indices = self._dof_partition_indices.array.to(device)
arg.dof_indices_in_element = self._dof_indices_in_element.array.to(device)
return arg
@wp.func
def node_partition_index(args: NodeArg, node_index: int):
return args.dof_partition_indices[node_index]
@wp.func
def node_element_count(args: NodeArg, node_index: int):
partition_node_index = SpaceRestriction.node_partition_index(args, node_index)
return args.dof_element_offsets[partition_node_index + 1] - args.dof_element_offsets[partition_node_index]
@wp.func
def node_element_index(args: NodeArg, node_index: int, element_index: int):
partition_node_index = SpaceRestriction.node_partition_index(args, node_index)
offset = args.dof_element_offsets[partition_node_index] + element_index
domain_element_index = args.dof_element_indices[offset]
index_in_element = args.dof_indices_in_element[offset]
return NodeElementIndex(domain_element_index, index_in_element)
@wp.kernel
def _split_vertex_element_index(
vertex_per_element: int,
sorted_indices: wp.array(dtype=int),
vertex_element_index: wp.array(dtype=int),
vertex_index_in_element: wp.array(dtype=int),
):
idx = sorted_indices[wp.tid()]
element_index = idx // vertex_per_element
vertex_element_index[wp.tid()] = element_index
vertex_index_in_element[wp.tid()] = idx - vertex_per_element * element_index
| 6,496 | Python | 39.104938 | 114 | 0.645628 |
NVIDIA/warp/warp/fem/space/partition.py | from typing import Any, Optional
import warp as wp
from warp.fem.cache import (
TemporaryStore,
borrow_temporary,
borrow_temporary_like,
cached_arg_value,
)
from warp.fem.geometry import GeometryPartition, WholeGeometryPartition
from warp.fem.types import NULL_NODE_INDEX
from warp.fem.utils import _iota_kernel, compress_node_indices
from .function_space import FunctionSpace
from .topology import SpaceTopology
wp.set_module_options({"enable_backward": False})
class SpacePartition:
class PartitionArg:
pass
def __init__(self, space_topology: SpaceTopology, geo_partition: GeometryPartition):
self.space_topology = space_topology
self.geo_partition = geo_partition
def node_count(self):
"""Returns number of nodes in this partition"""
def owned_node_count(self) -> int:
"""Returns number of nodes in this partition, excluding exterior halo"""
def interior_node_count(self) -> int:
"""Returns number of interior nodes in this partition"""
def space_node_indices(self) -> wp.array:
"""Return the global function space indices for nodes in this partition"""
def partition_arg_value(self, device):
pass
@staticmethod
def partition_node_index(args: "PartitionArg", space_node_index: int):
"""Returns the index in the partition of a function space node, or -1 if it does not exist"""
def __str__(self) -> str:
return self.name
@property
def name(self) -> str:
return f"{self.__class__.__name__}"
class WholeSpacePartition(SpacePartition):
@wp.struct
class PartitionArg:
pass
def __init__(self, space_topology: SpaceTopology):
super().__init__(space_topology, WholeGeometryPartition(space_topology.geometry))
self._node_indices = None
def node_count(self):
"""Returns number of nodes in this partition"""
return self.space_topology.node_count()
def owned_node_count(self) -> int:
"""Returns number of nodes in this partition, excluding exterior halo"""
return self.space_topology.node_count()
def interior_node_count(self) -> int:
"""Returns number of interior nodes in this partition"""
return self.space_topology.node_count()
def space_node_indices(self):
"""Return the global function space indices for nodes in this partition"""
if self._node_indices is None:
self._node_indices = borrow_temporary(temporary_store=None, shape=(self.node_count(),), dtype=int)
wp.launch(kernel=_iota_kernel, dim=self.node_count(), inputs=[self._node_indices.array, 1])
return self._node_indices.array
def partition_arg_value(self, device):
return WholeSpacePartition.PartitionArg()
@wp.func
def partition_node_index(args: Any, space_node_index: int):
return space_node_index
def __eq__(self, other: SpacePartition) -> bool:
return isinstance(other, SpacePartition) and self.space_topology == other.space_topology
@property
def name(self) -> str:
return "Whole"
class NodeCategory:
OWNED_INTERIOR = wp.constant(0)
"""Node is touched exclusively by this partition, not touched by frontier side"""
OWNED_FRONTIER = wp.constant(1)
"""Node is touched by a frontier side, but belongs to an element of this partition"""
HALO_LOCAL_SIDE = wp.constant(2)
"""Node belongs to an element of another partition, but is touched by one of our frontier side"""
HALO_OTHER_SIDE = wp.constant(3)
"""Node belongs to an element of another partition, and is not touched by one of our frontier side"""
EXTERIOR = wp.constant(4)
"""Node is never referenced by this partition"""
COUNT = 5
class NodePartition(SpacePartition):
@wp.struct
class PartitionArg:
space_to_partition: wp.array(dtype=int)
def __init__(
self,
space_topology: SpaceTopology,
geo_partition: GeometryPartition,
with_halo: bool = True,
device=None,
temporary_store: TemporaryStore = None,
):
super().__init__(space_topology=space_topology, geo_partition=geo_partition)
self._compute_node_indices_from_sides(device, with_halo, temporary_store)
def node_count(self) -> int:
"""Returns number of nodes referenced by this partition, including exterior halo"""
return int(self._category_offsets.array.numpy()[NodeCategory.HALO_OTHER_SIDE + 1])
def owned_node_count(self) -> int:
"""Returns number of nodes in this partition, excluding exterior halo"""
return int(self._category_offsets.array.numpy()[NodeCategory.OWNED_FRONTIER + 1])
def interior_node_count(self) -> int:
"""Returns number of interior nodes in this partition"""
return int(self._category_offsets.array.numpy()[NodeCategory.OWNED_INTERIOR + 1])
def space_node_indices(self):
"""Return the global function space indices for nodes in this partition"""
return self._node_indices.array
@cached_arg_value
def partition_arg_value(self, device):
arg = NodePartition.PartitionArg()
arg.space_to_partition = self._space_to_partition.array.to(device)
return arg
@wp.func
def partition_node_index(args: PartitionArg, space_node_index: int):
return args.space_to_partition[space_node_index]
def _compute_node_indices_from_sides(self, device, with_halo: bool, temporary_store: TemporaryStore):
from warp.fem import cache
trace_topology = self.space_topology.trace()
NODES_PER_CELL = self.space_topology.NODES_PER_ELEMENT
NODES_PER_SIDE = trace_topology.NODES_PER_ELEMENT
@cache.dynamic_kernel(suffix=f"{self.geo_partition.name}_{self.space_topology.name}")
def node_category_from_cells_kernel(
geo_arg: self.geo_partition.geometry.CellArg,
geo_partition_arg: self.geo_partition.CellArg,
space_arg: self.space_topology.TopologyArg,
node_mask: wp.array(dtype=int),
):
partition_cell_index = wp.tid()
cell_index = self.geo_partition.cell_index(geo_partition_arg, partition_cell_index)
for n in range(NODES_PER_CELL):
space_nidx = self.space_topology.element_node_index(geo_arg, space_arg, cell_index, n)
node_mask[space_nidx] = NodeCategory.OWNED_INTERIOR
@cache.dynamic_kernel(suffix=f"{self.geo_partition.name}_{self.space_topology.name}")
def node_category_from_owned_sides_kernel(
geo_arg: self.geo_partition.geometry.SideArg,
geo_partition_arg: self.geo_partition.SideArg,
space_arg: trace_topology.TopologyArg,
node_mask: wp.array(dtype=int),
):
partition_side_index = wp.tid()
side_index = self.geo_partition.side_index(geo_partition_arg, partition_side_index)
for n in range(NODES_PER_SIDE):
space_nidx = trace_topology.element_node_index(geo_arg, space_arg, side_index, n)
if node_mask[space_nidx] == NodeCategory.EXTERIOR:
node_mask[space_nidx] = NodeCategory.HALO_LOCAL_SIDE
@cache.dynamic_kernel(suffix=f"{self.geo_partition.name}_{self.space_topology.name}")
def node_category_from_frontier_sides_kernel(
geo_arg: self.geo_partition.geometry.SideArg,
geo_partition_arg: self.geo_partition.SideArg,
space_arg: trace_topology.TopologyArg,
node_mask: wp.array(dtype=int),
):
frontier_side_index = wp.tid()
side_index = self.geo_partition.frontier_side_index(geo_partition_arg, frontier_side_index)
for n in range(NODES_PER_SIDE):
space_nidx = trace_topology.element_node_index(geo_arg, space_arg, side_index, n)
if node_mask[space_nidx] == NodeCategory.EXTERIOR:
node_mask[space_nidx] = NodeCategory.HALO_OTHER_SIDE
elif node_mask[space_nidx] == NodeCategory.OWNED_INTERIOR:
node_mask[space_nidx] = NodeCategory.OWNED_FRONTIER
node_category = borrow_temporary(
temporary_store,
shape=(self.space_topology.node_count(),),
dtype=int,
device=device,
)
node_category.array.fill_(value=NodeCategory.EXTERIOR)
wp.launch(
dim=self.geo_partition.cell_count(),
kernel=node_category_from_cells_kernel,
inputs=[
self.geo_partition.geometry.cell_arg_value(device),
self.geo_partition.cell_arg_value(device),
self.space_topology.topo_arg_value(device),
node_category.array,
],
device=device,
)
if with_halo:
wp.launch(
dim=self.geo_partition.side_count(),
kernel=node_category_from_owned_sides_kernel,
inputs=[
self.geo_partition.geometry.side_arg_value(device),
self.geo_partition.side_arg_value(device),
self.space_topology.topo_arg_value(device),
node_category.array,
],
device=device,
)
wp.launch(
dim=self.geo_partition.frontier_side_count(),
kernel=node_category_from_frontier_sides_kernel,
inputs=[
self.geo_partition.geometry.side_arg_value(device),
self.geo_partition.side_arg_value(device),
self.space_topology.topo_arg_value(device),
node_category.array,
],
device=device,
)
self._finalize_node_indices(node_category.array, temporary_store)
node_category.release()
def _finalize_node_indices(self, node_category: wp.array(dtype=int), temporary_store: TemporaryStore):
category_offsets, node_indices, _, __ = compress_node_indices(NodeCategory.COUNT, node_category)
# Copy offsets to cpu
device = node_category.device
self._category_offsets = borrow_temporary(
temporary_store,
shape=category_offsets.array.shape,
dtype=category_offsets.array.dtype,
pinned=device.is_cuda,
device="cpu",
)
wp.copy(src=category_offsets.array, dest=self._category_offsets.array)
if device.is_cuda:
# TODO switch to synchronize_event once available
wp.synchronize_stream(wp.get_stream(device))
category_offsets.release()
# Compute global to local indices
self._space_to_partition = borrow_temporary_like(node_indices, temporary_store)
wp.launch(
kernel=NodePartition._scatter_partition_indices,
dim=self.space_topology.node_count(),
device=device,
inputs=[self.node_count(), node_indices.array, self._space_to_partition.array],
)
# Copy to shrinked-to-fit array
self._node_indices = borrow_temporary(temporary_store, shape=(self.node_count()), dtype=int, device=device)
wp.copy(dest=self._node_indices.array, src=node_indices.array, count=self.node_count())
node_indices.release()
@wp.kernel
def _scatter_partition_indices(
local_node_count: int,
node_indices: wp.array(dtype=int),
space_to_partition_indices: wp.array(dtype=int),
):
local_idx = wp.tid()
space_idx = node_indices[local_idx]
if local_idx < local_node_count:
space_to_partition_indices[space_idx] = local_idx
else:
space_to_partition_indices[space_idx] = NULL_NODE_INDEX
def make_space_partition(
space: Optional[FunctionSpace] = None,
geometry_partition: Optional[GeometryPartition] = None,
space_topology: Optional[SpaceTopology] = None,
with_halo: bool = True,
device=None,
temporary_store: TemporaryStore = None,
) -> SpacePartition:
"""Computes the subset of nodes from a function space topology that touch a geometry partition
Either `space_topology` or `space` must be provided (and will be considered in that order).
Args:
space: (deprecated) the function space defining the topology if `space_topology` is ``None``.
geometry_partition: The subset of the space geometry. If not provided, use the whole geometry.
space_topology: the topology of the function space to consider. If ``None``, deduced from `space`.
with_halo: if True, include the halo nodes (nodes from exterior frontier cells to the partition)
device: Warp device on which to perform and store computations
Returns:
the resulting space partition
"""
if space_topology is None:
space_topology = space.topology
space_topology = space_topology.full_space_topology()
if geometry_partition is not None:
if geometry_partition.cell_count() < geometry_partition.geometry.cell_count():
return NodePartition(
space_topology=space_topology,
geo_partition=geometry_partition,
with_halo=with_halo,
device=device,
temporary_store=temporary_store,
)
return WholeSpacePartition(space_topology)
| 13,484 | Python | 37.418803 | 115 | 0.63542 |
NVIDIA/warp/warp/fem/space/function_space.py | import warp as wp
from warp.fem.geometry import Geometry
from warp.fem.types import Coords, DofIndex, ElementIndex
from .topology import SpaceTopology
class FunctionSpace:
"""
Interface class for function spaces, i.e. geometry + interpolation basis
"""
dtype: type
"""Value type of the interpolation functions"""
SpaceArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device function"""
VALUE_DOF_COUNT: int
"""Number of degrees of freedom per node, as a Warp constant"""
def __init__(self, topology: SpaceTopology):
self._topology = topology
if self._topology.is_trace:
self.element_inner_reference_gradient_transform = self.geometry.side_inner_inverse_deformation_gradient
self.element_outer_reference_gradient_transform = self.geometry.side_outer_inverse_deformation_gradient
else:
self.element_inner_reference_gradient_transform = self.geometry.cell_inverse_deformation_gradient
self.element_outer_reference_gradient_transform = self.geometry.cell_inverse_deformation_gradient
def node_count(self) -> int:
"""Number of nodes in the interpolation basis"""
raise NotImplementedError
def space_arg_value(self, device) -> wp.codegen.StructInstance:
"""Value of the arguments to be passed to device functions"""
raise NotImplementedError
@property
def topology(self) -> SpaceTopology:
"""Underlying geometry"""
return self._topology
@property
def geometry(self) -> Geometry:
"""Underlying geometry"""
return self.topology.geometry
@property
def dimension(self) -> int:
"""Function space embedding dimension"""
return self.topology.dimension
@property
def degree(self) -> int:
"""Maximum polynomial degree of the underlying basis"""
raise NotImplementedError
@property
def name(self):
raise NotImplementedError
def __str__(self):
return self.name
def trace(self) -> "FunctionSpace":
"""Trace of the function space over lower-dimensional elements of the geometry"""
raise NotImplementedError
def make_field(self, space_partition=None):
"""Creates a zero-initialized discrete field over the function space holding values for all degrees of freedom of nodes in a space partition
space_arg:
space_partition: If provided, the subset of nodes to consider
See also: :func:`make_space_partition`
"""
raise NotImplementedError
@staticmethod
def unit_dof_value(elt_arg: "SpaceTopology.ElementArg", space_arg: "SpaceArg", dof: DofIndex): # noqa: F821
"""Unit value for a given degree of freedom. Typically a rank-1 tensor"""
raise NotImplementedError
@staticmethod
def node_coords_in_element(
elt_arg: "SpaceTopology.ElementArg",
space_arg: "SpaceArg", # noqa: F821
element_index: ElementIndex,
node_index_in_elt: int,
):
"""Coordinates inside element of a given node"""
raise NotImplementedError
@staticmethod
def node_quadrature_weight(
elt_arg: "SpaceTopology.ElementArg",
space_arg: "SpaceArg", # noqa: F821
element_index: ElementIndex,
node_index_in_elt: int,
):
"""Weight of a given node when used as a quadrature point"""
raise NotImplementedError
@staticmethod
def element_inner_weight(
elt_arg: "SpaceTopology.ElementArg",
space_arg: "SpaceArg", # noqa: F821
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
"""Inner weight for a node at given coordinates"""
raise NotImplementedError
@staticmethod
def element_inner_weight_gradient(
elt_arg: "SpaceTopology.ElementArg",
space_arg: "SpaceArg", # noqa: F821
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
"""Inner weight gradient w.r.t. reference space for a node at given coordinates"""
raise NotImplementedError
@staticmethod
def element_outer_weight(
elt_arg: "SpaceTopology.ElementArg",
space_arg: "SpaceArg", # noqa: F821
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
"""Outer weight for a node at given coordinates"""
raise NotImplementedError
@staticmethod
def element_outer_weight_gradient(
elt_arg: "SpaceTopology.ElementArg",
space_arg: "SpaceArg", # noqa: F821
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
"""Outer weight gradient w.r.t reference space for a node at given coordinates"""
raise NotImplementedError
| 4,896 | Python | 31.865772 | 148 | 0.651757 |
NVIDIA/warp/warp/fem/space/basis_space.py | from typing import Optional
import warp as wp
from warp.fem import cache
from warp.fem.geometry import Geometry
from warp.fem.quadrature import Quadrature
from warp.fem.types import Coords, ElementIndex, make_free_sample
from .shape import ShapeFunction
from .topology import DiscontinuousSpaceTopology, SpaceTopology
class BasisSpace:
"""Interface class for defining a scalar-valued basis over a geometry.
A basis space makes it easy to define multiple function spaces sharing the same basis (and thus nodes) but with different valuation functions;
however, it is not a required ingredient of a function space.
See also: :func:`make_polynomial_basis_space`, :func:`make_collocated_function_space`
"""
@wp.struct
class BasisArg:
"""Argument structure to be passed to device functions"""
pass
def __init__(self, topology: SpaceTopology):
self._topology = topology
self.NODES_PER_ELEMENT = self._topology.NODES_PER_ELEMENT
@property
def topology(self) -> SpaceTopology:
"""Underlying topology of the basis space"""
return self._topology
@property
def geometry(self) -> Geometry:
"""Underlying geometry of the basis space"""
return self._topology.geometry
def basis_arg_value(self, device) -> "BasisArg":
"""Value for the argument structure to be passed to device functions"""
return BasisSpace.BasisArg()
# Helpers for generating node positions
def node_positions(self, out: Optional[wp.array] = None) -> wp.array:
"""Returns a temporary array containing the world position for each node"""
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
pos_type = cache.cached_vec_type(length=self.geometry.dimension, dtype=float)
node_coords_in_element = self.make_node_coords_in_element()
@cache.dynamic_kernel(suffix=self.name, kernel_options={"max_unroll": 4, "enable_backward": False})
def fill_node_positions(
geo_cell_arg: self.geometry.CellArg,
basis_arg: self.BasisArg,
topo_arg: self.topology.TopologyArg,
node_positions: wp.array(dtype=pos_type),
):
element_index = wp.tid()
for n in range(NODES_PER_ELEMENT):
node_index = self.topology.element_node_index(geo_cell_arg, topo_arg, element_index, n)
coords = node_coords_in_element(geo_cell_arg, basis_arg, element_index, n)
sample = make_free_sample(element_index, coords)
pos = self.geometry.cell_position(geo_cell_arg, sample)
node_positions[node_index] = pos
shape = (self.topology.node_count(),)
if out is None:
node_positions = wp.empty(
shape=shape,
dtype=pos_type,
)
else:
if out.shape != shape or not wp.types.types_equal(pos_type, out.dtype):
raise ValueError(
f"Out node positions array must have shape {shape} and data type {wp.types.type_repr(pos_type)}"
)
node_positions = out
wp.launch(
dim=self.geometry.cell_count(),
kernel=fill_node_positions,
inputs=[
self.geometry.cell_arg_value(device=node_positions.device),
self.basis_arg_value(device=node_positions.device),
self.topology.topo_arg_value(device=node_positions.device),
node_positions,
],
)
return node_positions
def make_node_coords_in_element(self):
raise NotImplementedError()
def make_node_quadrature_weight(self):
raise NotImplementedError()
def make_element_inner_weight(self):
raise NotImplementedError()
def make_element_outer_weight(self):
return self.make_element_inner_weight()
def make_element_inner_weight_gradient(self):
raise NotImplementedError()
def make_element_outer_weight_gradient(self):
return self.make_element_inner_weight_gradient()
def make_trace_node_quadrature_weight(self):
raise NotImplementedError()
def trace(self) -> "TraceBasisSpace":
return TraceBasisSpace(self)
class ShapeBasisSpace(BasisSpace):
"""Base class for defining shape-function-based basis spaces."""
def __init__(self, topology: SpaceTopology, shape: ShapeFunction):
super().__init__(topology)
self._shape = shape
self.ORDER = self._shape.ORDER
if hasattr(shape, "element_node_triangulation"):
self.node_triangulation = self._node_triangulation
if hasattr(shape, "element_node_tets"):
self.node_tets = self._node_tets
if hasattr(shape, "element_node_hexes"):
self.node_hexes = self._node_hexes
@property
def shape(self) -> ShapeFunction:
"""Shape functions used for defining individual element basis"""
return self._shape
@property
def name(self):
return f"{self.topology.name}_{self._shape.name}"
def make_node_coords_in_element(self):
shape_node_coords_in_element = self._shape.make_node_coords_in_element()
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
elt_arg: self.geometry.CellArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return shape_node_coords_in_element(node_index_in_elt)
return node_coords_in_element
def make_node_quadrature_weight(self):
shape_node_quadrature_weight = self._shape.make_node_quadrature_weight()
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(
elt_arg: self.geometry.CellArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return shape_node_quadrature_weight(node_index_in_elt)
return node_quadrature_weight
def make_element_inner_weight(self):
shape_element_inner_weight = self._shape.make_element_inner_weight()
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
elt_arg: self.geometry.CellArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return shape_element_inner_weight(coords, node_index_in_elt)
return element_inner_weight
def make_element_inner_weight_gradient(self):
shape_element_inner_weight_gradient = self._shape.make_element_inner_weight_gradient()
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
elt_arg: self.geometry.CellArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return shape_element_inner_weight_gradient(coords, node_index_in_elt)
return element_inner_weight_gradient
def make_trace_node_quadrature_weight(self, trace_basis):
shape_trace_node_quadrature_weight = self._shape.make_trace_node_quadrature_weight()
@cache.dynamic_func(suffix=self.name)
def trace_node_quadrature_weight(
geo_side_arg: trace_basis.geometry.SideArg,
basis_arg: trace_basis.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
neighbour_elem, index_in_neighbour = trace_basis.topology.neighbor_cell_index(
geo_side_arg, element_index, node_index_in_elt
)
return shape_trace_node_quadrature_weight(index_in_neighbour)
return trace_node_quadrature_weight
def _node_triangulation(self):
element_node_indices = self._topology.element_node_indices().numpy()
element_triangles = self._shape.element_node_triangulation()
tri_indices = element_node_indices[:, element_triangles].reshape(-1, 3)
return tri_indices
def _node_tets(self):
element_node_indices = self._topology.element_node_indices().numpy()
element_tets = self._shape.element_node_tets()
tet_indices = element_node_indices[:, element_tets].reshape(-1, 4)
return tet_indices
def _node_hexes(self):
element_node_indices = self._topology.element_node_indices().numpy()
element_hexes = self._shape.element_node_hexes()
hex_indices = element_node_indices[:, element_hexes].reshape(-1, 8)
return hex_indices
class TraceBasisSpace(BasisSpace):
"""Auto-generated trace space evaluating the cell-defined basis on the geometry sides"""
def __init__(self, basis: BasisSpace):
super().__init__(basis.topology.trace())
self.ORDER = basis.ORDER
self._basis = basis
self.BasisArg = self._basis.BasisArg
self.basis_arg_value = self._basis.basis_arg_value
@property
def name(self):
return f"{self._basis.name}_Trace"
def make_node_coords_in_element(self):
node_coords_in_cell = self._basis.make_node_coords_in_element()
@cache.dynamic_func(suffix=self._basis.name)
def trace_node_coords_in_element(
geo_side_arg: self.geometry.SideArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
neighbour_elem, index_in_neighbour = self.topology.neighbor_cell_index(
geo_side_arg, element_index, node_index_in_elt
)
geo_cell_arg = self.geometry.side_to_cell_arg(geo_side_arg)
neighbour_coords = node_coords_in_cell(
geo_cell_arg,
basis_arg,
neighbour_elem,
index_in_neighbour,
)
return self.geometry.side_from_cell_coords(geo_side_arg, element_index, neighbour_elem, neighbour_coords)
return trace_node_coords_in_element
def make_node_quadrature_weight(self):
return self._basis.make_trace_node_quadrature_weight(self)
def make_element_inner_weight(self):
cell_inner_weight = self._basis.make_element_inner_weight()
@cache.dynamic_func(suffix=self._basis.name)
def trace_element_inner_weight(
geo_side_arg: self.geometry.SideArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
cell_index, index_in_cell = self.topology.inner_cell_index(geo_side_arg, element_index, node_index_in_elt)
if index_in_cell < 0:
return 0.0
cell_coords = self.geometry.side_inner_cell_coords(geo_side_arg, element_index, coords)
geo_cell_arg = self.geometry.side_to_cell_arg(geo_side_arg)
return cell_inner_weight(
geo_cell_arg,
basis_arg,
cell_index,
cell_coords,
index_in_cell,
)
return trace_element_inner_weight
def make_element_outer_weight(self):
cell_outer_weight = self._basis.make_element_outer_weight()
@cache.dynamic_func(suffix=self._basis.name)
def trace_element_outer_weight(
geo_side_arg: self.geometry.SideArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
cell_index, index_in_cell = self.topology.outer_cell_index(geo_side_arg, element_index, node_index_in_elt)
if index_in_cell < 0:
return 0.0
cell_coords = self.geometry.side_outer_cell_coords(geo_side_arg, element_index, coords)
geo_cell_arg = self.geometry.side_to_cell_arg(geo_side_arg)
return cell_outer_weight(
geo_cell_arg,
basis_arg,
cell_index,
cell_coords,
index_in_cell,
)
return trace_element_outer_weight
def make_element_inner_weight_gradient(self):
cell_inner_weight_gradient = self._basis.make_element_inner_weight_gradient()
grad_vec_type = wp.vec(length=self.geometry.dimension, dtype=float)
@cache.dynamic_func(suffix=self._basis.name)
def trace_element_inner_weight_gradient(
geo_side_arg: self.geometry.SideArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
cell_index, index_in_cell = self.topology.inner_cell_index(geo_side_arg, element_index, node_index_in_elt)
if index_in_cell < 0:
return grad_vec_type(0.0)
cell_coords = self.geometry.side_inner_cell_coords(geo_side_arg, element_index, coords)
geo_cell_arg = self.geometry.side_to_cell_arg(geo_side_arg)
return cell_inner_weight_gradient(geo_cell_arg, basis_arg, cell_index, cell_coords, index_in_cell)
return trace_element_inner_weight_gradient
def make_element_outer_weight_gradient(self):
cell_outer_weight_gradient = self._basis.make_element_outer_weight_gradient()
grad_vec_type = wp.vec(length=self.geometry.dimension, dtype=float)
@cache.dynamic_func(suffix=self._basis.name)
def trace_element_outer_weight_gradient(
geo_side_arg: self.geometry.SideArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
cell_index, index_in_cell = self.topology.outer_cell_index(geo_side_arg, element_index, node_index_in_elt)
if index_in_cell < 0:
return grad_vec_type(0.0)
cell_coords = self.geometry.side_outer_cell_coords(geo_side_arg, element_index, coords)
geo_cell_arg = self.geometry.side_to_cell_arg(geo_side_arg)
return cell_outer_weight_gradient(geo_cell_arg, basis_arg, cell_index, cell_coords, index_in_cell)
return trace_element_outer_weight_gradient
def __eq__(self, other: "TraceBasisSpace") -> bool:
return self._topo == other._topo
class PiecewiseConstantBasisSpace(ShapeBasisSpace):
class Trace(TraceBasisSpace):
def make_node_coords_in_element(self):
# Makes the single node visible to all sides; useful for interpolating on boundaries
# For higher-order non-conforming elements direct interpolation on boundary is not possible,
# need to do proper integration then solve with mass matrix
CENTER_COORDS = Coords(self.geometry.reference_side().center())
@cache.dynamic_func(suffix=self._basis.name)
def trace_node_coords_in_element(
geo_side_arg: self.geometry.SideArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return CENTER_COORDS
return trace_node_coords_in_element
def trace(self):
return PiecewiseConstantBasisSpace.Trace(self)
def make_discontinuous_basis_space(geometry: Geometry, shape: ShapeFunction):
topology = DiscontinuousSpaceTopology(geometry, shape.NODES_PER_ELEMENT)
if shape.NODES_PER_ELEMENT == 1:
# piecewise-constant space
return PiecewiseConstantBasisSpace(topology=topology, shape=shape)
return ShapeBasisSpace(topology=topology, shape=shape)
class PointBasisSpace(BasisSpace):
"""An unstructured :class:`BasisSpace` that is non-zero at a finite set of points only.
The node locations and nodal quadrature weights are defined by a :class:`Quadrature` formula.
"""
def __init__(self, quadrature: Quadrature):
self._quadrature = quadrature
if quadrature.points_per_element() is None:
raise NotImplementedError("Varying number of points per element is not supported yet")
topology = DiscontinuousSpaceTopology(
geometry=quadrature.domain.geometry, nodes_per_element=quadrature.points_per_element()
)
super().__init__(topology)
self.BasisArg = quadrature.Arg
self.basis_arg_value = quadrature.arg_value
self.ORDER = 0
self.make_element_outer_weight = self.make_element_inner_weight
self.make_element_outer_weight_gradient = self.make_element_outer_weight_gradient
@property
def name(self):
return f"{self._quadrature.name}_Point"
def make_node_coords_in_element(self):
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
elt_arg: self._quadrature.domain.ElementArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return self._quadrature.point_coords(elt_arg, basis_arg, element_index, node_index_in_elt)
return node_coords_in_element
def make_node_quadrature_weight(self):
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(
elt_arg: self._quadrature.domain.ElementArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return self._quadrature.point_weight(elt_arg, basis_arg, element_index, node_index_in_elt)
return node_quadrature_weight
def make_element_inner_weight(self):
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
elt_arg: self._quadrature.domain.ElementArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
qp_coord = self._quadrature.point_coords(elt_arg, basis_arg, element_index, node_index_in_elt)
return wp.select(wp.length_sq(coords - qp_coord) < 0.001, 0.0, 1.0)
return element_inner_weight
def make_element_inner_weight_gradient(self):
gradient_vec = cache.cached_vec_type(length=self.geometry.dimension, dtype=float)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
elt_arg: self._quadrature.domain.ElementArg,
basis_arg: self.BasisArg,
element_index: ElementIndex,
coords: Coords,
node_index_in_elt: int,
):
return gradient_vec(0.0)
return element_inner_weight_gradient
def make_trace_node_quadrature_weight(self, trace_basis):
@cache.dynamic_func(suffix=self.name)
def trace_node_quadrature_weight(
elt_arg: trace_basis.geometry.SideArg,
basis_arg: trace_basis.BasisArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return 0.0
return trace_node_quadrature_weight
| 19,174 | Python | 35.66348 | 146 | 0.623448 |
NVIDIA/warp/warp/fem/space/__init__.py | # isort: skip_file
from enum import Enum
from typing import Optional
import warp.fem.domain as _domain
import warp.fem.geometry as _geometry
import warp.fem.polynomial as _polynomial
from .function_space import FunctionSpace
from .topology import SpaceTopology
from .basis_space import BasisSpace, PointBasisSpace, ShapeBasisSpace, make_discontinuous_basis_space
from .collocated_function_space import CollocatedFunctionSpace
from .shape import ElementBasis, get_shape_function
from .grid_2d_function_space import make_grid_2d_space_topology
from .grid_3d_function_space import make_grid_3d_space_topology
from .trimesh_2d_function_space import make_trimesh_2d_space_topology
from .tetmesh_function_space import make_tetmesh_space_topology
from .quadmesh_2d_function_space import make_quadmesh_2d_space_topology
from .hexmesh_function_space import make_hexmesh_space_topology
from .nanogrid_function_space import make_nanogrid_space_topology
from .partition import SpacePartition, make_space_partition
from .restriction import SpaceRestriction
from .dof_mapper import DofMapper, IdentityMapper, SymmetricTensorMapper, SkewSymmetricTensorMapper
def make_space_restriction(
space: Optional[FunctionSpace] = None,
space_partition: Optional[SpacePartition] = None,
domain: Optional[_domain.GeometryDomain] = None,
space_topology: Optional[SpaceTopology] = None,
device=None,
temporary_store: "Optional[warp.fem.cache.TemporaryStore]" = None, # noqa: F821
) -> SpaceRestriction:
"""
Restricts a function space partition to a Domain, i.e. a subset of its elements.
One of `space_partition`, `space_topology`, or `space` must be provided (and will be considered in that order).
Args:
space: (deprecated) if neither `space_partition` nor `space_topology` are provided, the space defining the topology to restrict
space_partition: the subset of nodes from the space topology to consider
domain: the domain to restrict the space to, defaults to all cells of the space geometry or partition.
space_topology: the space topology to be restricted, if `space_partition` is ``None``.
device: device on which to perform and store computations
temporary_store: shared pool from which to allocate temporary arrays
"""
if space_partition is None:
if space_topology is None:
assert space is not None
space_topology = space.topology
if domain is None:
domain = _domain.Cells(geometry=space_topology.geometry)
space_partition = make_space_partition(
space_topology=space_topology, geometry_partition=domain.geometry_partition
)
elif domain is None:
domain = _domain.Cells(geometry=space_partition.geo_partition)
return SpaceRestriction(
space_partition=space_partition, domain=domain, device=device, temporary_store=temporary_store
)
def make_polynomial_basis_space(
geo: _geometry.Geometry,
degree: int = 1,
element_basis: Optional[ElementBasis] = None,
discontinuous: bool = False,
family: Optional[_polynomial.Polynomial] = None,
) -> BasisSpace:
"""
Equips a geometry with a polynomial basis.
Args:
geo: the Geometry on which to build the space
degree: polynomial degree of the per-element shape functions
discontinuous: if True, use Discontinuous Galerkin shape functions. Discontinuous is implied if degree is 0, i.e, piecewise-constant shape functions.
element_basis: type of basis function for the individual elements
family: Polynomial family used to generate the shape function basis. If not provided, a reasonable basis is chosen.
Returns:
the constructed basis space
"""
base_geo = geo.base if isinstance(geo, _geometry.DeformedGeometry) else geo
if element_basis is None:
element_basis = ElementBasis.LAGRANGE
elif element_basis == ElementBasis.SERENDIPITY and degree == 1:
# Degree-1 serendipity is always equivalent to Lagrange
element_basis = ElementBasis.LAGRANGE
shape = get_shape_function(geo.reference_cell(), geo.dimension, degree, element_basis, family)
if discontinuous or degree == 0 or element_basis == ElementBasis.NONCONFORMING_POLYNOMIAL:
return make_discontinuous_basis_space(geo, shape)
topology = None
if isinstance(base_geo, _geometry.Grid2D):
topology = make_grid_2d_space_topology(geo, shape)
elif isinstance(base_geo, _geometry.Grid3D):
topology = make_grid_3d_space_topology(geo, shape)
elif isinstance(base_geo, _geometry.Trimesh2D):
topology = make_trimesh_2d_space_topology(geo, shape)
elif isinstance(base_geo, _geometry.Tetmesh):
topology = make_tetmesh_space_topology(geo, shape)
elif isinstance(base_geo, _geometry.Quadmesh2D):
topology = make_quadmesh_2d_space_topology(geo, shape)
elif isinstance(base_geo, _geometry.Hexmesh):
topology = make_hexmesh_space_topology(geo, shape)
elif isinstance(base_geo, _geometry.Nanogrid):
topology = make_nanogrid_space_topology(geo, shape)
if topology is None:
raise NotImplementedError(f"Unsupported geometry type {geo.name}")
return ShapeBasisSpace(topology, shape)
def make_collocated_function_space(
basis_space: BasisSpace, dtype: type = float, dof_mapper: Optional[DofMapper] = None
) -> CollocatedFunctionSpace:
"""
Constructs a function space from a basis space and a value type, such that all degrees of freedom of the value type are stored at each of the basis nodes.
Args:
geo: the Geometry on which to build the space
dtype: value type the function space. If ``dof_mapper`` is provided, the value type from the DofMapper will be used instead.
dof_mapper: mapping from node degrees of freedom to function values, defaults to Identity. Useful for reduced coordinates, e.g. :py:class:`SymmetricTensorMapper` maps 2x2 (resp 3x3) symmetric tensors to 3 (resp 6) degrees of freedom.
Returns:
the constructed function space
"""
return CollocatedFunctionSpace(basis_space, dtype=dtype, dof_mapper=dof_mapper)
def make_polynomial_space(
geo: _geometry.Geometry,
dtype: type = float,
dof_mapper: Optional[DofMapper] = None,
degree: int = 1,
element_basis: Optional[ElementBasis] = None,
discontinuous: bool = False,
family: Optional[_polynomial.Polynomial] = None,
) -> CollocatedFunctionSpace:
"""
Equips a geometry with a collocated, polynomial function space.
Equivalent to successive calls to :func:`make_polynomial_basis_space` and `make_collocated_function_space`.
Args:
geo: the Geometry on which to build the space
dtype: value type the function space. If ``dof_mapper`` is provided, the value type from the DofMapper will be used instead.
dof_mapper: mapping from node degrees of freedom to function values, defaults to Identity. Useful for reduced coordinates, e.g. :py:class:`SymmetricTensorMapper` maps 2x2 (resp 3x3) symmetric tensors to 3 (resp 6) degrees of freedom.
degree: polynomial degree of the per-element shape functions
discontinuous: if True, use Discontinuous Galerkin shape functions. Discontinuous is implied if degree is 0, i.e, piecewise-constant shape functions.
element_basis: type of basis function for the individual elements
family: Polynomial family used to generate the shape function basis. If not provided, a reasonable basis is chosen.
Returns:
the constructed function space
"""
basis_space = make_polynomial_basis_space(geo, degree, element_basis, discontinuous, family)
return CollocatedFunctionSpace(basis_space, dtype=dtype, dof_mapper=dof_mapper)
| 7,828 | Python | 42.494444 | 241 | 0.728922 |
NVIDIA/warp/warp/fem/space/topology.py | from typing import Optional, Type
import warp as wp
from warp.fem import cache
from warp.fem.geometry import DeformedGeometry, Geometry
from warp.fem.types import ElementIndex
class SpaceTopology:
"""
Interface class for defining the topology of a function space.
The topology only considers the indices of the nodes in each element, and as such,
the connectivity pattern of the function space.
It does not specify the actual location of the nodes within the elements, or the valuation function.
"""
dimension: int
"""Embedding dimension of the function space"""
NODES_PER_ELEMENT: int
"""Number of interpolation nodes per element of the geometry.
.. note:: This will change to be defined per-element in future versions
"""
@wp.struct
class TopologyArg:
"""Structure containing arguments to be passed to device functions"""
pass
def __init__(self, geometry: Geometry, nodes_per_element: int):
self._geometry = geometry
self.dimension = geometry.dimension
self.NODES_PER_ELEMENT = wp.constant(nodes_per_element)
self.ElementArg = geometry.CellArg
@property
def geometry(self) -> Geometry:
"""Underlying geometry"""
return self._geometry
def node_count(self) -> int:
"""Number of nodes in the interpolation basis"""
raise NotImplementedError
def topo_arg_value(self, device) -> "TopologyArg":
"""Value of the topology argument structure to be passed to device functions"""
return SpaceTopology.TopologyArg()
@property
def name(self):
return f"{self.__class__.__name__}_{self.NODES_PER_ELEMENT}"
def __str__(self):
return self.name
@staticmethod
def element_node_index(
geo_arg: "ElementArg", # noqa: F821
topo_arg: "TopologyArg",
element_index: ElementIndex,
node_index_in_elt: int,
):
"""Global node index for a given node in a given element"""
raise NotImplementedError
def element_node_indices(self, out: Optional[wp.array] = None) -> wp.array:
"""Returns a temporary array containing the global index for each node of each element"""
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
@cache.dynamic_kernel(suffix=self.name)
def fill_element_node_indices(
geo_cell_arg: self.geometry.CellArg,
topo_arg: self.TopologyArg,
element_node_indices: wp.array2d(dtype=int),
):
element_index = wp.tid()
for n in range(NODES_PER_ELEMENT):
element_node_indices[element_index, n] = self.element_node_index(
geo_cell_arg, topo_arg, element_index, n
)
shape = (self.geometry.cell_count(), NODES_PER_ELEMENT)
if out is None:
element_node_indices = wp.empty(
shape=shape,
dtype=int,
)
else:
if out.shape != shape or out.dtype != wp.int32:
raise ValueError(f"Out element node indices array must have shape {shape} and data type 'int32'")
element_node_indices = out
wp.launch(
dim=element_node_indices.shape[0],
kernel=fill_element_node_indices,
inputs=[
self.geometry.cell_arg_value(device=element_node_indices.device),
self.topo_arg_value(device=element_node_indices.device),
element_node_indices,
],
device=element_node_indices.device,
)
return element_node_indices
# Interface generating trace space topology
def trace(self) -> "TraceSpaceTopology":
"""Trace of the function space over lower-dimensional elements of the geometry"""
return TraceSpaceTopology(self)
@property
def is_trace(self) -> bool:
"""Whether this topology is defined on the trace of the geometry"""
return self.dimension == self.geometry.dimension - 1
def full_space_topology(self) -> "SpaceTopology":
"""Returns the full space topology from which this topology is derived"""
return self
def __eq__(self, other: "SpaceTopology") -> bool:
"""Checks whether two topologies are compatible"""
return self.geometry == other.geometry and self.name == other.name
def is_derived_from(self, other: "SpaceTopology") -> bool:
"""Checks whether two topologies are equal, or `self` is the trace of `other`"""
if self.dimension == other.dimension:
return self == other
if self.dimension + 1 == other.dimension:
return self.full_space_topology() == other
return False
class TraceSpaceTopology(SpaceTopology):
"""Auto-generated trace topology defining the node indices associated to the geometry sides"""
def __init__(self, topo: SpaceTopology):
super().__init__(topo.geometry, 2 * topo.NODES_PER_ELEMENT)
self._topo = topo
self.dimension = topo.dimension - 1
self.ElementArg = topo.geometry.SideArg
self.TopologyArg = topo.TopologyArg
self.topo_arg_value = topo.topo_arg_value
self.inner_cell_index = self._make_inner_cell_index()
self.outer_cell_index = self._make_outer_cell_index()
self.neighbor_cell_index = self._make_neighbor_cell_index()
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return self._topo.node_count()
@property
def name(self):
return f"{self._topo.name}_Trace"
def _make_inner_cell_index(self):
NODES_PER_ELEMENT = self._topo.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def inner_cell_index(args: self.geometry.SideArg, element_index: ElementIndex, node_index_in_elt: int):
index_in_inner_cell = wp.select(node_index_in_elt < NODES_PER_ELEMENT, -1, node_index_in_elt)
return self.geometry.side_inner_cell_index(args, element_index), index_in_inner_cell
return inner_cell_index
def _make_outer_cell_index(self):
NODES_PER_ELEMENT = self._topo.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def outer_cell_index(args: self.geometry.SideArg, element_index: ElementIndex, node_index_in_elt: int):
return self.geometry.side_outer_cell_index(args, element_index), node_index_in_elt - NODES_PER_ELEMENT
return outer_cell_index
def _make_neighbor_cell_index(self):
NODES_PER_ELEMENT = self._topo.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def neighbor_cell_index(args: self.geometry.SideArg, element_index: ElementIndex, node_index_in_elt: int):
if node_index_in_elt < NODES_PER_ELEMENT:
return self.geometry.side_inner_cell_index(args, element_index), node_index_in_elt
else:
return (
self.geometry.side_outer_cell_index(args, element_index),
node_index_in_elt - NODES_PER_ELEMENT,
)
return neighbor_cell_index
def _make_element_node_index(self):
@cache.dynamic_func(suffix=self.name)
def trace_element_node_index(
geo_side_arg: self.geometry.SideArg,
topo_arg: self._topo.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
cell_index, index_in_cell = self.neighbor_cell_index(geo_side_arg, element_index, node_index_in_elt)
geo_cell_arg = self.geometry.side_to_cell_arg(geo_side_arg)
return self._topo.element_node_index(geo_cell_arg, topo_arg, cell_index, index_in_cell)
return trace_element_node_index
def full_space_topology(self) -> SpaceTopology:
"""Returns the full space topology from which this topology is derived"""
return self._topo
def __eq__(self, other: "TraceSpaceTopology") -> bool:
return self._topo == other._topo
class DiscontinuousSpaceTopologyMixin:
"""Helper for defining discontinuous topologies (per-element nodes)"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.element_node_index = self._make_element_node_index()
def node_count(self):
return self.geometry.cell_count() * self.NODES_PER_ELEMENT
@property
def name(self):
return f"{self.geometry.name}_D{self.NODES_PER_ELEMENT}"
def _make_element_node_index(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def element_node_index(
elt_arg: self.geometry.CellArg,
topo_arg: self.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return NODES_PER_ELEMENT * element_index + node_index_in_elt
return element_node_index
class DiscontinuousSpaceTopology(DiscontinuousSpaceTopologyMixin, SpaceTopology):
"""Topology for generic discontinuous spaces"""
pass
class DeformedGeometrySpaceTopology(SpaceTopology):
def __init__(self, geometry: DeformedGeometry, base_topology: SpaceTopology):
super().__init__(geometry, base_topology.NODES_PER_ELEMENT)
self.base = base_topology
self.node_count = self.base.node_count
self.topo_arg_value = self.base.topo_arg_value
self.TopologyArg = self.base.TopologyArg
self.element_node_index = self._make_element_node_index()
@property
def name(self):
return f"{self.base.name}_{self.geometry.field.name}"
def _make_element_node_index(self):
@cache.dynamic_func(suffix=self.name)
def element_node_index(
elt_arg: self.geometry.CellArg,
topo_arg: self.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
return self.base.element_node_index(elt_arg.elt_arg, topo_arg, element_index, node_index_in_elt)
return element_node_index
def forward_base_topology(topology_class: Type[SpaceTopology], geometry: Geometry, *args, **kwargs) -> SpaceTopology:
"""
If `geometry` is *not* a :class:`DeformedGeometry`, constructs a normal instance of `topology_class` over `geometry`, forwarding additional arguments.
If `geometry` *is* a :class:`DeformedGeometry`, constructs an instance of `topology_class` over the base (undeformed) geometry of `geometry`, then warp it
in a :class:`DeformedGeometrySpaceTopology` forwarding the calls to the underlying topology.
"""
if isinstance(geometry, DeformedGeometry):
base_topo = topology_class(geometry.base, *args, **kwargs)
return DeformedGeometrySpaceTopology(geometry, base_topo)
return topology_class(geometry, *args, **kwargs)
| 10,898 | Python | 35.573825 | 158 | 0.640852 |
NVIDIA/warp/warp/fem/space/dof_mapper.py | import math
from enum import Enum
from typing import Any
import warp as wp
import warp.types
vec6 = wp.types.vector(length=6, dtype=wp.float32)
_SQRT_2 = wp.constant(math.sqrt(2.0))
_SQRT_3 = wp.constant(math.sqrt(3.0))
_SQRT_1_2 = wp.constant(math.sqrt(1.0 / 2.0))
_SQRT_1_3 = wp.constant(math.sqrt(1.0 / 3.0))
class DofMapper:
"""Base class from mapping node degrees of freedom to function values"""
value_dtype: type
dof_dtype: type
DOF_SIZE: int
@wp.func
def dof_to_value(dof: Any):
raise NotImplementedError
@wp.func
def value_to_dof(val: Any):
raise NotImplementedError
def __str__(self):
return f"{self.value_dtype.__name__}_{self.DOF_SIZE}"
class IdentityMapper(DofMapper):
"""Identity mapper"""
def __init__(self, dtype: type):
if dtype == float:
dtype = wp.float32
self.value_dtype = dtype
self.dof_dtype = dtype
size = warp.types.type_length(dtype)
self.DOF_SIZE = wp.constant(size)
@wp.func
def dof_to_value(dof: Any):
return dof
@wp.func
def value_to_dof(val: Any):
return val
class SymmetricTensorMapper(DofMapper):
"""Orthonormal isomorphism from R^{n (n+1)} to nxn symmetric tensors,
using usual L2 norm for vectors and half Frobenius norm, (tau : tau)/2 for tensors.
"""
class Mapping(Enum):
VOIGT = 0
"""Voigt ordering of vector coefficients:
first the three diagonal terms, then off-diagonal coefficients"""
DB16 = 1
"""Ordering that also separates normal from tangential coefficients:
first trace, then other diagonal terms, then off-diagonal coefficients.
See [Daviet and Bertails-Descoubes 2016]"""
def __init__(self, dtype: type, mapping: Mapping = Mapping.VOIGT):
self.value_dtype = dtype
self.mapping = mapping
if dtype == wp.mat22:
self.dof_dtype = wp.vec3
self.DOF_SIZE = wp.constant(3)
if mapping == SymmetricTensorMapper.Mapping.VOIGT:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_2d_voigt
self.value_to_dof = SymmetricTensorMapper.value_to_dof_2d_voigt
else:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_2d
self.value_to_dof = SymmetricTensorMapper.value_to_dof_2d
elif dtype == wp.mat33:
self.dof_dtype = vec6
self.DOF_SIZE = wp.constant(6)
if mapping == SymmetricTensorMapper.Mapping.VOIGT:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_3d_voigt
self.value_to_dof = SymmetricTensorMapper.value_to_dof_3d_voigt
else:
self.dof_to_value = SymmetricTensorMapper.dof_to_value_3d
self.value_to_dof = SymmetricTensorMapper.value_to_dof_3d
else:
raise ValueError("Unsupported value dtype: ", dtype)
def __str__(self):
return f"{self.mapping}_{self.DOF_SIZE}"
@wp.func
def dof_to_value_2d(dof: wp.vec3):
a = dof[0]
b = dof[1]
c = dof[2]
return wp.mat22(a + b, c, c, a - b)
@wp.func
def value_to_dof_2d(val: wp.mat22):
a = 0.5 * (val[0, 0] + val[1, 1])
b = 0.5 * (val[0, 0] - val[1, 1])
c = 0.5 * (val[0, 1] + val[1, 0])
return wp.vec3(a, b, c)
@wp.func
def dof_to_value_2d_voigt(dof: wp.vec3):
a = _SQRT_2 * dof[0]
b = _SQRT_2 * dof[1]
c = dof[2]
return wp.mat22(a, c, c, b)
@wp.func
def value_to_dof_2d_voigt(val: wp.mat22):
a = _SQRT_1_2 * val[0, 0]
b = _SQRT_1_2 * val[1, 1]
c = 0.5 * (val[0, 1] + val[1, 0])
return wp.vec3(a, b, c)
@wp.func
def dof_to_value_3d(dof: vec6):
a = dof[0] * _SQRT_2 * _SQRT_1_3
b = dof[1]
c = dof[2] * _SQRT_1_3
d = dof[3]
e = dof[4]
f = dof[5]
return wp.mat33(
a + b - c,
f,
e,
f,
a - b - c,
d,
e,
d,
a + 2.0 * c,
)
@wp.func
def value_to_dof_3d(val: wp.mat33):
a = (val[0, 0] + val[1, 1] + val[2, 2]) * _SQRT_1_3 * _SQRT_1_2
b = 0.5 * (val[0, 0] - val[1, 1])
c = 0.5 * (val[2, 2] - (val[0, 0] + val[1, 1] + val[2, 2]) / 3.0) * _SQRT_3
d = 0.5 * (val[2, 1] + val[1, 2])
e = 0.5 * (val[0, 2] + val[2, 0])
f = 0.5 * (val[1, 0] + val[0, 1])
return vec6(a, b, c, d, e, f)
@wp.func
def dof_to_value_3d_voigt(dof: vec6):
a = _SQRT_2 * dof[0]
b = _SQRT_2 * dof[1]
c = _SQRT_2 * dof[2]
d = dof[3]
e = dof[4]
f = dof[5]
return wp.mat33(
a,
f,
e,
f,
b,
d,
e,
d,
c,
)
@wp.func
def value_to_dof_3d_voigt(val: wp.mat33):
a = _SQRT_1_2 * val[0, 0]
b = _SQRT_1_2 * val[1, 1]
c = _SQRT_1_2 * val[2, 2]
d = 0.5 * (val[2, 1] + val[1, 2])
e = 0.5 * (val[0, 2] + val[2, 0])
f = 0.5 * (val[1, 0] + val[0, 1])
return vec6(a, b, c, d, e, f)
class SkewSymmetricTensorMapper(DofMapper):
"""Orthonormal isomorphism from R^{n (n-1)} to nxn skew-symmetric tensors,
using usual L2 norm for vectors and half Frobenius norm, (tau : tau)/2 for tensors.
"""
def __init__(self, dtype: type):
self.value_dtype = dtype
if dtype == wp.mat22:
self.dof_dtype = float
self.DOF_SIZE = wp.constant(1)
self.dof_to_value = SkewSymmetricTensorMapper.dof_to_value_2d
self.value_to_dof = SkewSymmetricTensorMapper.value_to_dof_2d
elif dtype == wp.mat33:
self.dof_dtype = wp.vec3
self.DOF_SIZE = wp.constant(3)
self.dof_to_value = SkewSymmetricTensorMapper.dof_to_value_3d
self.value_to_dof = SkewSymmetricTensorMapper.value_to_dof_3d
else:
raise ValueError("Unsupported value dtype: ", dtype)
def __str__(self):
return f"{self.__class__.__name__}_{self.DOF_SIZE}"
@wp.func
def dof_to_value_2d(dof: float):
return wp.mat22(0.0, -dof, dof, 0.0)
@wp.func
def value_to_dof_2d(val: wp.mat22):
return 0.5 * (val[1, 0] - val[0, 1])
@wp.func
def dof_to_value_3d(dof: wp.vec3):
a = dof[0]
b = dof[1]
c = dof[2]
return wp.mat33(0.0, -c, b, c, 0.0, -a, -b, a, 0.0)
@wp.func
def value_to_dof_3d(val: wp.mat33):
a = 0.5 * (val[2, 1] - val[1, 2])
b = 0.5 * (val[0, 2] - val[2, 0])
c = 0.5 * (val[1, 0] - val[0, 1])
return wp.vec3(a, b, c)
| 6,859 | Python | 27.945148 | 87 | 0.516402 |
NVIDIA/warp/warp/fem/space/hexmesh_function_space.py | import warp as wp
from warp.fem import cache
from warp.fem.geometry import Hexmesh
from warp.fem.geometry.hexmesh import (
EDGE_VERTEX_INDICES,
FACE_ORIENTATION,
FACE_TRANSLATION,
)
from warp.fem.polynomial import is_closed
from warp.fem.types import ElementIndex
from .shape import (
CubeSerendipityShapeFunctions,
CubeTripolynomialShapeFunctions,
ShapeFunction,
)
from .topology import SpaceTopology, forward_base_topology
_FACE_ORIENTATION_I = wp.constant(wp.mat(shape=(16, 2), dtype=int)(FACE_ORIENTATION))
_FACE_TRANSLATION_I = wp.constant(wp.mat(shape=(4, 2), dtype=int)(FACE_TRANSLATION))
# map from shape function vertex indexing to hexmesh vertex indexing
_CUBE_TO_HEX_VERTEX = wp.constant(wp.vec(length=8, dtype=int)([0, 4, 3, 7, 1, 5, 2, 6]))
# map from shape function edge indexing to hexmesh edge indexing
_CUBE_TO_HEX_EDGE = wp.constant(wp.vec(length=12, dtype=int)([0, 4, 2, 6, 3, 1, 7, 5, 8, 11, 9, 10]))
@wp.struct
class HexmeshTopologyArg:
hex_edge_indices: wp.array2d(dtype=int)
hex_face_indices: wp.array2d(dtype=wp.vec2i)
vertex_count: int
edge_count: int
face_count: int
class HexmeshSpaceTopology(SpaceTopology):
TopologyArg = HexmeshTopologyArg
def __init__(
self,
mesh: Hexmesh,
shape: ShapeFunction,
need_hex_edge_indices: bool = True,
need_hex_face_indices: bool = True,
):
if not is_closed(shape.family):
raise ValueError("A closed polynomial family is required to define a continuous function space")
super().__init__(mesh, shape.NODES_PER_ELEMENT)
self._mesh = mesh
self.shape = shape
if need_hex_edge_indices:
self._hex_edge_indices = self._mesh.hex_edge_indices
self._edge_count = self._mesh.edge_count()
else:
self._hex_edge_indices = wp.empty(shape=(0, 0), dtype=int)
self._edge_count = 0
if need_hex_face_indices:
self._compute_hex_face_indices()
else:
self._hex_face_indices = wp.empty(shape=(0, 0), dtype=wp.vec2i)
self._compute_hex_face_indices()
@cache.cached_arg_value
def topo_arg_value(self, device):
arg = HexmeshTopologyArg()
arg.hex_edge_indices = self._hex_edge_indices.to(device)
arg.hex_face_indices = self._hex_face_indices.to(device)
arg.vertex_count = self._mesh.vertex_count()
arg.face_count = self._mesh.side_count()
arg.edge_count = self._edge_count
return arg
def _compute_hex_face_indices(self):
self._hex_face_indices = wp.empty(
dtype=wp.vec2i, device=self._mesh.hex_vertex_indices.device, shape=(self._mesh.cell_count(), 6)
)
wp.launch(
kernel=HexmeshSpaceTopology._compute_hex_face_indices_kernel,
dim=self._mesh.side_count(),
device=self._mesh.hex_vertex_indices.device,
inputs=[
self._mesh.face_hex_indices,
self._mesh._face_hex_face_orientation,
self._hex_face_indices,
],
)
@wp.kernel
def _compute_hex_face_indices_kernel(
face_hex_indices: wp.array(dtype=wp.vec2i),
face_hex_face_ori: wp.array(dtype=wp.vec4i),
hex_face_indices: wp.array2d(dtype=wp.vec2i),
):
f = wp.tid()
hx0 = face_hex_indices[f][0]
local_face_0 = face_hex_face_ori[f][0]
ori_0 = face_hex_face_ori[f][1]
hex_face_indices[hx0, local_face_0] = wp.vec2i(f, ori_0)
hx1 = face_hex_indices[f][1]
local_face_1 = face_hex_face_ori[f][2]
ori_1 = face_hex_face_ori[f][3]
hex_face_indices[hx1, local_face_1] = wp.vec2i(f, ori_1)
class HexmeshTripolynomialSpaceTopology(HexmeshSpaceTopology):
def __init__(self, mesh: Hexmesh, shape: CubeTripolynomialShapeFunctions):
super().__init__(mesh, shape, need_hex_edge_indices=shape.ORDER >= 2, need_hex_face_indices=shape.ORDER >= 2)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
ORDER = self.shape.ORDER
INTERIOR_NODES_PER_EDGE = max(0, ORDER - 1)
INTERIOR_NODES_PER_FACE = INTERIOR_NODES_PER_EDGE**2
INTERIOR_NODES_PER_CELL = INTERIOR_NODES_PER_EDGE**3
return (
self._mesh.vertex_count()
+ self._mesh.edge_count() * INTERIOR_NODES_PER_EDGE
+ self._mesh.side_count() * INTERIOR_NODES_PER_FACE
+ self._mesh.cell_count() * INTERIOR_NODES_PER_CELL
)
@wp.func
def _rotate_face_index(type_index: int, ori: int, size: int):
i = type_index // size
j = type_index - i * size
coords = wp.vec2i(i, j)
fv = ori // 2
rot_i = wp.dot(_FACE_ORIENTATION_I[2 * ori], coords) + _FACE_TRANSLATION_I[fv, 0]
rot_j = wp.dot(_FACE_ORIENTATION_I[2 * ori + 1], coords) + _FACE_TRANSLATION_I[fv, 1]
return rot_i * size + rot_j
def _make_element_node_index(self):
ORDER = self.shape.ORDER
INTERIOR_NODES_PER_EDGE = wp.constant(max(0, ORDER - 1))
INTERIOR_NODES_PER_FACE = wp.constant(INTERIOR_NODES_PER_EDGE**2)
INTERIOR_NODES_PER_CELL = wp.constant(INTERIOR_NODES_PER_EDGE**3)
@cache.dynamic_func(suffix=self.name)
def element_node_index(
geo_arg: Hexmesh.CellArg,
topo_arg: HexmeshTopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_instance, type_index = self.shape.node_type_and_type_index(node_index_in_elt)
if node_type == CubeTripolynomialShapeFunctions.VERTEX:
return geo_arg.hex_vertex_indices[element_index, _CUBE_TO_HEX_VERTEX[type_instance]]
offset = topo_arg.vertex_count
if node_type == CubeTripolynomialShapeFunctions.EDGE:
hex_edge = _CUBE_TO_HEX_EDGE[type_instance]
edge_index = topo_arg.hex_edge_indices[element_index, hex_edge]
v0 = geo_arg.hex_vertex_indices[element_index, EDGE_VERTEX_INDICES[hex_edge, 0]]
v1 = geo_arg.hex_vertex_indices[element_index, EDGE_VERTEX_INDICES[hex_edge, 1]]
if v0 > v1:
type_index = ORDER - 1 - type_index
return offset + INTERIOR_NODES_PER_EDGE * edge_index + type_index
offset += INTERIOR_NODES_PER_EDGE * topo_arg.edge_count
if node_type == CubeTripolynomialShapeFunctions.FACE:
face_index_and_ori = topo_arg.hex_face_indices[element_index, type_instance]
face_index = face_index_and_ori[0]
face_orientation = face_index_and_ori[1]
type_index = HexmeshTripolynomialSpaceTopology._rotate_face_index(
type_index, face_orientation, ORDER - 1
)
return offset + INTERIOR_NODES_PER_FACE * face_index + type_index
offset += INTERIOR_NODES_PER_FACE * topo_arg.face_count
return offset + INTERIOR_NODES_PER_CELL * element_index + type_index
return element_node_index
class HexmeshSerendipitySpaceTopology(HexmeshSpaceTopology):
def __init__(
self,
grid: Hexmesh,
shape: CubeSerendipityShapeFunctions,
):
super().__init__(grid, shape, need_hex_edge_indices=True, need_hex_face_indices=False)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return self.geometry.vertex_count() + (self.shape.ORDER - 1) * self.geometry.edge_count()
def _make_element_node_index(self):
ORDER = self.shape.ORDER
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Hexmesh.CellArg,
topo_arg: HexmeshSpaceTopology.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self.shape.node_type_and_type_index(node_index_in_elt)
if node_type == CubeSerendipityShapeFunctions.VERTEX:
return cell_arg.hex_vertex_indices[element_index, _CUBE_TO_HEX_VERTEX[type_index]]
type_instance, index_in_edge = CubeSerendipityShapeFunctions._cube_edge_index(node_type, type_index)
hex_edge = _CUBE_TO_HEX_EDGE[type_instance]
edge_index = topo_arg.hex_edge_indices[element_index, hex_edge]
v0 = cell_arg.hex_vertex_indices[element_index, EDGE_VERTEX_INDICES[hex_edge, 0]]
v1 = cell_arg.hex_vertex_indices[element_index, EDGE_VERTEX_INDICES[hex_edge, 1]]
if v0 > v1:
index_in_edge = ORDER - 1 - index_in_edge
return topo_arg.vertex_count + (ORDER - 1) * edge_index + index_in_edge
return element_node_index
def make_hexmesh_space_topology(mesh: Hexmesh, shape: ShapeFunction):
if isinstance(shape, CubeSerendipityShapeFunctions):
return forward_base_topology(HexmeshSerendipitySpaceTopology, mesh, shape)
if isinstance(shape, CubeTripolynomialShapeFunctions):
return forward_base_topology(HexmeshTripolynomialSpaceTopology, mesh, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 9,317 | Python | 35.685039 | 117 | 0.622089 |
NVIDIA/warp/warp/fem/space/trimesh_2d_function_space.py | import warp as wp
from warp.fem import cache
from warp.fem.geometry import Trimesh2D
from warp.fem.types import ElementIndex
from .shape import (
ShapeFunction,
Triangle2DPolynomialShapeFunctions,
)
from .topology import SpaceTopology, forward_base_topology
@wp.struct
class Trimesh2DTopologyArg:
edge_vertex_indices: wp.array(dtype=wp.vec2i)
tri_edge_indices: wp.array2d(dtype=int)
vertex_count: int
edge_count: int
class Trimesh2DSpaceTopology(SpaceTopology):
TopologyArg = Trimesh2DTopologyArg
def __init__(self, mesh: Trimesh2D, shape: ShapeFunction):
super().__init__(mesh, shape.NODES_PER_ELEMENT)
self._mesh = mesh
self._shape = shape
self._compute_tri_edge_indices()
@cache.cached_arg_value
def topo_arg_value(self, device):
arg = Trimesh2DTopologyArg()
arg.tri_edge_indices = self._tri_edge_indices.to(device)
arg.edge_vertex_indices = self._mesh.edge_vertex_indices.to(device)
arg.vertex_count = self._mesh.vertex_count()
arg.edge_count = self._mesh.side_count()
return arg
def _compute_tri_edge_indices(self):
self._tri_edge_indices = wp.empty(
dtype=int, device=self._mesh.tri_vertex_indices.device, shape=(self._mesh.cell_count(), 3)
)
wp.launch(
kernel=Trimesh2DSpaceTopology._compute_tri_edge_indices_kernel,
dim=self._mesh.edge_tri_indices.shape,
device=self._mesh.tri_vertex_indices.device,
inputs=[
self._mesh.edge_tri_indices,
self._mesh.edge_vertex_indices,
self._mesh.tri_vertex_indices,
self._tri_edge_indices,
],
)
@wp.func
def _find_edge_index_in_tri(
edge_vtx: wp.vec2i,
tri_vtx: wp.vec3i,
):
for k in range(2):
if (edge_vtx[0] == tri_vtx[k] and edge_vtx[1] == tri_vtx[k + 1]) or (
edge_vtx[1] == tri_vtx[k] and edge_vtx[0] == tri_vtx[k + 1]
):
return k
return 2
@wp.kernel
def _compute_tri_edge_indices_kernel(
edge_tri_indices: wp.array(dtype=wp.vec2i),
edge_vertex_indices: wp.array(dtype=wp.vec2i),
tri_vertex_indices: wp.array2d(dtype=int),
tri_edge_indices: wp.array2d(dtype=int),
):
e = wp.tid()
edge_vtx = edge_vertex_indices[e]
edge_tris = edge_tri_indices[e]
t0 = edge_tris[0]
t0_vtx = wp.vec3i(tri_vertex_indices[t0, 0], tri_vertex_indices[t0, 1], tri_vertex_indices[t0, 2])
t0_edge = Trimesh2DSpaceTopology._find_edge_index_in_tri(edge_vtx, t0_vtx)
tri_edge_indices[t0, t0_edge] = e
t1 = edge_tris[1]
if t1 != t0:
t1_vtx = wp.vec3i(tri_vertex_indices[t1, 0], tri_vertex_indices[t1, 1], tri_vertex_indices[t1, 2])
t1_edge = Trimesh2DSpaceTopology._find_edge_index_in_tri(edge_vtx, t1_vtx)
tri_edge_indices[t1, t1_edge] = e
class Trimesh2DPolynomialSpaceTopology(Trimesh2DSpaceTopology):
def __init__(self, mesh: Trimesh2D, shape: Triangle2DPolynomialShapeFunctions):
super().__init__(mesh, shape)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
INTERIOR_NODES_PER_SIDE = max(0, self._shape.ORDER - 1)
INTERIOR_NODES_PER_CELL = max(0, self._shape.ORDER - 2) * max(0, self._shape.ORDER - 1) // 2
return (
self._mesh.vertex_count()
+ self._mesh.side_count() * INTERIOR_NODES_PER_SIDE
+ self._mesh.cell_count() * INTERIOR_NODES_PER_CELL
)
def _make_element_node_index(self):
INTERIOR_NODES_PER_SIDE = wp.constant(max(0, self._shape.ORDER - 1))
INTERIOR_NODES_PER_CELL = wp.constant(max(0, self._shape.ORDER - 2) * max(0, self._shape.ORDER - 1) // 2)
@cache.dynamic_func(suffix=self.name)
def element_node_index(
geo_arg: Trimesh2D.CellArg,
topo_arg: Trimesh2DTopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
return geo_arg.tri_vertex_indices[element_index][type_index]
global_offset = topo_arg.vertex_count
if node_type == Triangle2DPolynomialShapeFunctions.EDGE:
edge = type_index // INTERIOR_NODES_PER_SIDE
edge_node = type_index - INTERIOR_NODES_PER_SIDE * edge
global_edge_index = topo_arg.tri_edge_indices[element_index][edge]
if (
topo_arg.edge_vertex_indices[global_edge_index][0]
!= geo_arg.tri_vertex_indices[element_index][edge]
):
edge_node = INTERIOR_NODES_PER_SIDE - 1 - edge_node
return global_offset + INTERIOR_NODES_PER_SIDE * global_edge_index + edge_node
global_offset += INTERIOR_NODES_PER_SIDE * topo_arg.edge_count
return global_offset + INTERIOR_NODES_PER_CELL * element_index + type_index
return element_node_index
def make_trimesh_2d_space_topology(mesh: Trimesh2D, shape: ShapeFunction):
if isinstance(shape, Triangle2DPolynomialShapeFunctions):
return forward_base_topology(Trimesh2DPolynomialSpaceTopology, mesh, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 5,569 | Python | 35.168831 | 113 | 0.610882 |
NVIDIA/warp/warp/fem/space/collocated_function_space.py | from typing import Optional
import warp as wp
from warp.fem import cache, utils
from warp.fem.types import DofIndex, get_node_coord
from .basis_space import BasisSpace
from .dof_mapper import DofMapper, IdentityMapper
from .function_space import FunctionSpace
from .partition import SpacePartition, make_space_partition
class CollocatedFunctionSpace(FunctionSpace):
"""Function space where values are collocated at nodes"""
def __init__(self, basis: BasisSpace, dtype: type = float, dof_mapper: DofMapper = None):
super().__init__(topology=basis.topology)
self.dof_mapper = IdentityMapper(dtype) if dof_mapper is None else dof_mapper
self.dtype = self.dof_mapper.value_dtype
self.dof_dtype = self.dof_mapper.dof_dtype
self.VALUE_DOF_COUNT = self.dof_mapper.DOF_SIZE
self._basis = basis
self.SpaceArg = self._basis.BasisArg
self.ORDER = self._basis.ORDER
self.unit_dof_value = self._make_unit_dof_value(self.dof_mapper)
self.node_coords_in_element = self._basis.make_node_coords_in_element()
self.node_quadrature_weight = self._basis.make_node_quadrature_weight()
self.element_inner_weight = self._basis.make_element_inner_weight()
self.element_inner_weight_gradient = self._basis.make_element_inner_weight_gradient()
self.element_outer_weight = self._basis.make_element_outer_weight()
self.element_outer_weight_gradient = self._basis.make_element_outer_weight_gradient()
# For backward compatibility
if hasattr(basis.topology, "node_grid"):
self.node_grid = basis.node_grid
if hasattr(basis, "node_triangulation"):
self.node_triangulation = basis.node_triangulation
if hasattr(basis, "node_tets"):
self.node_tets = basis.node_tets
if hasattr(basis, "node_hexes"):
self.node_hexes = basis.node_hexes
def space_arg_value(self, device):
return self._basis.basis_arg_value(device)
@property
def name(self):
return f"{self._basis.name}_{self.dof_mapper}".replace(".", "_")
@property
def degree(self):
"""Maximum polynomial degree of the underlying basis"""
return self.ORDER
def make_field(
self,
space_partition: Optional[SpacePartition] = None,
) -> "wp.fem.field.NodalField":
from warp.fem.field import NodalField
if space_partition is None:
space_partition = make_space_partition(space_topology=self.topology)
return NodalField(space=self, space_partition=space_partition)
def _make_unit_dof_value(self, dof_mapper: DofMapper):
@cache.dynamic_func(suffix=self.name)
def unit_dof_value(geo_arg: self.topology.ElementArg, space_arg: self.SpaceArg, dof: DofIndex):
return dof_mapper.dof_to_value(utils.unit_element(dof_mapper.dof_dtype(0.0), get_node_coord(dof)))
return unit_dof_value
def node_count(self):
return self.topology.node_count()
def node_positions(self, out: Optional[wp.array] = None) -> wp.array:
return self._basis.node_positions(out=out)
def trace(self) -> "CollocatedFunctionSpace":
return CollocatedFunctionSpaceTrace(self)
class CollocatedFunctionSpaceTrace(CollocatedFunctionSpace):
"""Trace of a :class:`CollocatedFunctionSpace`"""
def __init__(self, space: CollocatedFunctionSpace):
self._space = space
super().__init__(space._basis.trace(), space.dtype, space.dof_mapper)
@property
def name(self):
return f"{self._space.name}_Trace"
def __eq__(self, other: "CollocatedFunctionSpaceTrace") -> bool:
return self._space == other._space
| 3,736 | Python | 36 | 110 | 0.672109 |
NVIDIA/warp/warp/fem/space/grid_2d_function_space.py | import numpy as np
import warp as wp
from warp.fem import cache
from warp.fem.geometry import Grid2D
from warp.fem.polynomial import is_closed
from warp.fem.types import ElementIndex
from .shape import (
ShapeFunction,
SquareBipolynomialShapeFunctions,
SquareSerendipityShapeFunctions,
)
from .topology import SpaceTopology, forward_base_topology
class Grid2DSpaceTopology(SpaceTopology):
def __init__(self, grid: Grid2D, shape: ShapeFunction):
if not is_closed(shape.family):
raise ValueError("A closed polynomial family is required to define a continuous function space")
super().__init__(grid, shape.NODES_PER_ELEMENT)
self._shape = shape
@wp.func
def _vertex_coords(vidx_in_cell: int):
x = vidx_in_cell // 2
y = vidx_in_cell - 2 * x
return wp.vec2i(x, y)
@wp.func
def _vertex_index(cell_arg: Grid2D.CellArg, cell_index: ElementIndex, vidx_in_cell: int):
res = cell_arg.res
x_stride = res[1] + 1
corner = Grid2D.get_cell(res, cell_index) + Grid2DSpaceTopology._vertex_coords(vidx_in_cell)
return Grid2D._from_2d_index(x_stride, corner)
class GridBipolynomialSpaceTopology(Grid2DSpaceTopology):
def __init__(self, grid: Grid2D, shape: SquareBipolynomialShapeFunctions):
super().__init__(grid, shape)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
return (self.geometry.res[0] * self._shape.ORDER + 1) * (self.geometry.res[1] * self._shape.ORDER + 1)
def _make_element_node_index(self):
ORDER = self._shape.ORDER
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Grid2D.CellArg,
topo_arg: Grid2DSpaceTopology.TopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
res = cell_arg.res
cell = Grid2D.get_cell(res, element_index)
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
node_x = ORDER * cell[0] + node_i
node_y = ORDER * cell[1] + node_j
node_pitch = (res[1] * ORDER) + 1
node_index = node_pitch * node_x + node_y
return node_index
return element_node_index
def _node_grid(self):
res = self.geometry.res
cell_coords = np.array(self._shape.LOBATTO_COORDS)[:-1]
grid_coords_x = np.repeat(np.arange(0, res[0], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[0]
)
grid_coords_x = np.append(grid_coords_x, res[0])
X = grid_coords_x * self._grid.cell_size[0] + self._grid.origin[0]
grid_coords_y = np.repeat(np.arange(0, res[1], dtype=float), len(cell_coords)) + np.tile(
cell_coords, reps=res[1]
)
grid_coords_y = np.append(grid_coords_y, res[1])
Y = grid_coords_y * self._grid.cell_size[1] + self._grid.origin[1]
return np.meshgrid(X, Y, indexing="ij")
class GridSerendipitySpaceTopology(Grid2DSpaceTopology):
def __init__(self, grid: Grid2D, shape: SquareSerendipityShapeFunctions):
super().__init__(grid, shape)
self.element_node_index = self._make_element_node_index()
TopologyArg = Grid2D.SideArg
def topo_arg_value(self, device):
return self.geometry.side_arg_value(device)
def node_count(self) -> int:
return self.geometry.vertex_count() + (self._shape.ORDER - 1) * self.geometry.side_count()
def _make_element_node_index(self):
ORDER = self._shape.ORDER
@cache.dynamic_func(suffix=self.name)
def element_node_index(
cell_arg: Grid2D.CellArg,
topo_arg: Grid2D.SideArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == SquareSerendipityShapeFunctions.VERTEX:
return Grid2DSpaceTopology._vertex_index(cell_arg, element_index, type_index)
side_offset, index_in_side = SquareSerendipityShapeFunctions.side_offset_and_index(type_index)
axis = 1 - (node_type - SquareSerendipityShapeFunctions.EDGE_X)
cell = Grid2D.get_cell(cell_arg.res, element_index)
origin = wp.vec2i(cell[Grid2D.ROTATION[axis, 0]] + side_offset, cell[Grid2D.ROTATION[axis, 1]])
side = Grid2D.Side(axis, origin)
side_index = Grid2D.side_index(topo_arg, side)
res = cell_arg.res
vertex_count = (res[0] + 1) * (res[1] + 1)
return vertex_count + (ORDER - 1) * side_index + index_in_side
return element_node_index
def make_grid_2d_space_topology(grid: Grid2D, shape: ShapeFunction):
if isinstance(shape, SquareSerendipityShapeFunctions):
return forward_base_topology(GridSerendipitySpaceTopology, grid, shape)
if isinstance(shape, SquareBipolynomialShapeFunctions):
return forward_base_topology(GridBipolynomialSpaceTopology, grid, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 5,238 | Python | 34.161074 | 110 | 0.62963 |
NVIDIA/warp/warp/fem/space/tetmesh_function_space.py | import warp as wp
from warp.fem import cache
from warp.fem.geometry import Tetmesh
from warp.fem.types import ElementIndex
from .shape import (
ShapeFunction,
TetrahedronPolynomialShapeFunctions,
)
from .topology import SpaceTopology, forward_base_topology
@wp.struct
class TetmeshTopologyArg:
tet_edge_indices: wp.array2d(dtype=int)
tet_face_indices: wp.array2d(dtype=int)
face_vertex_indices: wp.array(dtype=wp.vec3i)
vertex_count: int
edge_count: int
face_count: int
class TetmeshSpaceTopology(SpaceTopology):
TopologyArg = TetmeshTopologyArg
def __init__(
self,
mesh: Tetmesh,
shape: ShapeFunction,
need_tet_edge_indices: bool = True,
need_tet_face_indices: bool = True,
):
super().__init__(mesh, shape.NODES_PER_ELEMENT)
self._mesh = mesh
self._shape = shape
if need_tet_edge_indices:
self._tet_edge_indices = self._mesh.tet_edge_indices
self._edge_count = self._mesh.edge_count()
else:
self._tet_edge_indices = wp.empty(shape=(0, 0), dtype=int)
self._edge_count = 0
if need_tet_face_indices:
self._compute_tet_face_indices()
else:
self._tet_face_indices = wp.empty(shape=(0, 0), dtype=int)
@cache.cached_arg_value
def topo_arg_value(self, device):
arg = TetmeshTopologyArg()
arg.tet_face_indices = self._tet_face_indices.to(device)
arg.tet_edge_indices = self._tet_edge_indices.to(device)
arg.face_vertex_indices = self._mesh.face_vertex_indices.to(device)
arg.vertex_count = self._mesh.vertex_count()
arg.face_count = self._mesh.side_count()
arg.edge_count = self._edge_count
return arg
def _compute_tet_face_indices(self):
self._tet_face_indices = wp.empty(
dtype=int, device=self._mesh.tet_vertex_indices.device, shape=(self._mesh.cell_count(), 4)
)
wp.launch(
kernel=TetmeshSpaceTopology._compute_tet_face_indices_kernel,
dim=self._mesh._face_tet_indices.shape,
device=self._mesh.tet_vertex_indices.device,
inputs=[
self._mesh.face_tet_indices,
self._mesh.face_vertex_indices,
self._mesh.tet_vertex_indices,
self._tet_face_indices,
],
)
@wp.func
def _find_face_index_in_tet(
face_vtx: wp.vec3i,
tet_vtx: wp.vec4i,
):
for k in range(3):
tvk = wp.vec3i(tet_vtx[k], tet_vtx[(k + 1) % 4], tet_vtx[(k + 2) % 4])
# Use fact that face always start with min vertex
min_t = wp.min(tvk)
max_t = wp.max(tvk)
mid_t = tvk[0] + tvk[1] + tvk[2] - min_t - max_t
if min_t == face_vtx[0] and (
(face_vtx[2] == max_t and face_vtx[1] == mid_t) or (face_vtx[1] == max_t and face_vtx[2] == mid_t)
):
return k
return 3
@wp.kernel
def _compute_tet_face_indices_kernel(
face_tet_indices: wp.array(dtype=wp.vec2i),
face_vertex_indices: wp.array(dtype=wp.vec3i),
tet_vertex_indices: wp.array2d(dtype=int),
tet_face_indices: wp.array2d(dtype=int),
):
e = wp.tid()
face_vtx = face_vertex_indices[e]
face_tets = face_tet_indices[e]
t0 = face_tets[0]
t0_vtx = wp.vec4i(
tet_vertex_indices[t0, 0], tet_vertex_indices[t0, 1], tet_vertex_indices[t0, 2], tet_vertex_indices[t0, 3]
)
t0_face = TetmeshSpaceTopology._find_face_index_in_tet(face_vtx, t0_vtx)
tet_face_indices[t0, t0_face] = e
t1 = face_tets[1]
if t1 != t0:
t1_vtx = wp.vec4i(
tet_vertex_indices[t1, 0],
tet_vertex_indices[t1, 1],
tet_vertex_indices[t1, 2],
tet_vertex_indices[t1, 3],
)
t1_face = TetmeshSpaceTopology._find_face_index_in_tet(face_vtx, t1_vtx)
tet_face_indices[t1, t1_face] = e
class TetmeshPolynomialSpaceTopology(TetmeshSpaceTopology):
def __init__(self, mesh: Tetmesh, shape: TetrahedronPolynomialShapeFunctions):
super().__init__(mesh, shape, need_tet_edge_indices=shape.ORDER >= 2, need_tet_face_indices=shape.ORDER >= 3)
self.element_node_index = self._make_element_node_index()
def node_count(self) -> int:
ORDER = self._shape.ORDER
INTERIOR_NODES_PER_EDGE = max(0, ORDER - 1)
INTERIOR_NODES_PER_FACE = max(0, ORDER - 2) * max(0, ORDER - 1) // 2
INTERIOR_NODES_PER_CELL = max(0, ORDER - 3) * max(0, ORDER - 2) * max(0, ORDER - 1) // 6
return (
self._mesh.vertex_count()
+ self._mesh.edge_count() * INTERIOR_NODES_PER_EDGE
+ self._mesh.side_count() * INTERIOR_NODES_PER_FACE
+ self._mesh.cell_count() * INTERIOR_NODES_PER_CELL
)
def _make_element_node_index(self):
ORDER = self._shape.ORDER
INTERIOR_NODES_PER_EDGE = wp.constant(max(0, ORDER - 1))
INTERIOR_NODES_PER_FACE = wp.constant(max(0, ORDER - 2) * max(0, ORDER - 1) // 2)
INTERIOR_NODES_PER_CELL = wp.constant(max(0, ORDER - 3) * max(0, ORDER - 2) * max(0, ORDER - 1) // 6)
@cache.dynamic_func(suffix=self.name)
def element_node_index(
geo_arg: Tetmesh.CellArg,
topo_arg: TetmeshTopologyArg,
element_index: ElementIndex,
node_index_in_elt: int,
):
node_type, type_index = self._shape.node_type_and_type_index(node_index_in_elt)
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
return geo_arg.tet_vertex_indices[element_index][type_index]
global_offset = topo_arg.vertex_count
if node_type == TetrahedronPolynomialShapeFunctions.EDGE:
edge = type_index // INTERIOR_NODES_PER_EDGE
edge_node = type_index - INTERIOR_NODES_PER_EDGE * edge
global_edge_index = topo_arg.tet_edge_indices[element_index][edge]
# Test if we need to swap edge direction
if INTERIOR_NODES_PER_EDGE > 1:
if edge < 3:
c1 = edge
c2 = (edge + 1) % 3
else:
c1 = edge - 3
c2 = 3
if geo_arg.tet_vertex_indices[element_index][c1] > geo_arg.tet_vertex_indices[element_index][c2]:
edge_node = INTERIOR_NODES_PER_EDGE - 1 - edge_node
return global_offset + INTERIOR_NODES_PER_EDGE * global_edge_index + edge_node
global_offset += INTERIOR_NODES_PER_EDGE * topo_arg.edge_count
if node_type == TetrahedronPolynomialShapeFunctions.FACE:
face = type_index // INTERIOR_NODES_PER_FACE
face_node = type_index - INTERIOR_NODES_PER_FACE * face
global_face_index = topo_arg.tet_face_indices[element_index][face]
if INTERIOR_NODES_PER_FACE == 3:
# Hard code for P4 case, 3 nodes per face
# Higher orders would require rotating triangle coordinates, this is not supported yet
vidx = geo_arg.tet_vertex_indices[element_index][(face + face_node) % 4]
fvi = topo_arg.face_vertex_indices[global_face_index]
if vidx == fvi[0]:
face_node = 0
elif vidx == fvi[1]:
face_node = 1
else:
face_node = 2
return global_offset + INTERIOR_NODES_PER_FACE * global_face_index + face_node
global_offset += INTERIOR_NODES_PER_FACE * topo_arg.face_count
return global_offset + INTERIOR_NODES_PER_CELL * element_index + type_index
return element_node_index
def make_tetmesh_space_topology(mesh: Tetmesh, shape: ShapeFunction):
if isinstance(shape, TetrahedronPolynomialShapeFunctions):
return forward_base_topology(TetmeshPolynomialSpaceTopology, mesh, shape)
raise ValueError(f"Unsupported shape function {shape.name}")
| 8,321 | Python | 35.986667 | 118 | 0.569403 |
NVIDIA/warp/warp/fem/space/shape/cube_shape_function.py | import math
import numpy as np
import warp as wp
from warp.fem import cache
from warp.fem.geometry import Grid3D
from warp.fem.polynomial import Polynomial, is_closed, lagrange_scales, quadrature_1d
from warp.fem.types import Coords
from .tet_shape_function import TetrahedronPolynomialShapeFunctions
class CubeTripolynomialShapeFunctions:
VERTEX = 0
EDGE = 1
FACE = 2
INTERIOR = 3
def __init__(self, degree: int, family: Polynomial):
self.family = family
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) ** 3)
self.NODES_PER_EDGE = wp.constant(degree + 1)
lobatto_coords, lobatto_weight = quadrature_1d(point_count=degree + 1, family=family)
lagrange_scale = lagrange_scales(lobatto_coords)
NodeVec = wp.types.vector(length=degree + 1, dtype=wp.float32)
self.LOBATTO_COORDS = wp.constant(NodeVec(lobatto_coords))
self.LOBATTO_WEIGHT = wp.constant(NodeVec(lobatto_weight))
self.LAGRANGE_SCALE = wp.constant(NodeVec(lagrange_scale))
self.ORDER_PLUS_ONE = wp.constant(self.ORDER + 1)
self._node_ijk = self._make_node_ijk()
self.node_type_and_type_index = self._make_node_type_and_type_index()
@property
def name(self) -> str:
return f"Cube_Q{self.ORDER}_{self.family}"
@wp.func
def _vertex_coords_f(vidx_in_cell: int):
x = vidx_in_cell // 4
y = (vidx_in_cell - 4 * x) // 2
z = vidx_in_cell - 4 * x - 2 * y
return wp.vec3(float(x), float(y), float(z))
def _make_node_ijk(self):
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
def node_ijk(
node_index_in_elt: int,
):
node_i = node_index_in_elt // (ORDER_PLUS_ONE * ORDER_PLUS_ONE)
node_jk = node_index_in_elt - ORDER_PLUS_ONE * ORDER_PLUS_ONE * node_i
node_j = node_jk // ORDER_PLUS_ONE
node_k = node_jk - ORDER_PLUS_ONE * node_j
return node_i, node_j, node_k
return cache.get_func(node_ijk, self.name)
def _make_node_type_and_type_index(self):
ORDER = self.ORDER
@cache.dynamic_func(suffix=self.name)
def node_type_and_type_index(
node_index_in_elt: int,
):
i, j, k = self._node_ijk(node_index_in_elt)
zi = wp.select(i == 0, 0, 1)
zj = wp.select(j == 0, 0, 1)
zk = wp.select(k == 0, 0, 1)
mi = wp.select(i == ORDER, 0, 1)
mj = wp.select(j == ORDER, 0, 1)
mk = wp.select(k == ORDER, 0, 1)
if zi + mi == 1:
if zj + mj == 1:
if zk + mk == 1:
# vertex
type_instance = mi * 4 + mj * 2 + mk
return CubeTripolynomialShapeFunctions.VERTEX, type_instance, 0
# z edge
type_instance = 8 + mi * 2 + mj
type_index = k - 1
return CubeTripolynomialShapeFunctions.EDGE, type_instance, type_index
if zk + mk == 1:
# y edge
type_instance = 4 + mk * 2 + mi
type_index = j - 1
return CubeTripolynomialShapeFunctions.EDGE, type_instance, type_index
# x face
type_instance = mi
type_index = wp.select(mi == 1, (j - 1) * (ORDER - 1) + k - 1, (k - 1) * (ORDER - 1) + j - 1)
return CubeTripolynomialShapeFunctions.FACE, type_instance, type_index
if zj + mj == 1:
if zk + mk == 1:
# x edge
type_instance = mj * 2 + mk
type_index = i - 1
return CubeTripolynomialShapeFunctions.EDGE, type_instance, type_index
# y face
type_instance = 2 + mj
type_index = wp.select(mj == 1, (i - 1) * (ORDER - 1) + k - 1, (k - 1) * (ORDER - 1) + i - 1)
return CubeTripolynomialShapeFunctions.FACE, type_instance, type_index
if zk + mk == 1:
# z face
type_instance = 4 + mk
type_index = wp.select(mk == 1, (j - 1) * (ORDER - 1) + i - 1, (i - 1) * (ORDER - 1) + j - 1)
return CubeTripolynomialShapeFunctions.FACE, type_instance, type_index
type_index = ((i - 1) * (ORDER - 1) + (j - 1)) * (ORDER - 1) + k - 1
return CubeTripolynomialShapeFunctions.INTERIOR, 0, type_index
return node_type_and_type_index
def make_node_coords_in_element(self):
LOBATTO_COORDS = self.LOBATTO_COORDS
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
return Coords(LOBATTO_COORDS[node_i], LOBATTO_COORDS[node_j], LOBATTO_COORDS[node_k])
return node_coords_in_element
def make_node_quadrature_weight(self):
ORDER = self.ORDER
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def node_quadrature_weight(
node_index_in_elt: int,
):
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_j] * LOBATTO_WEIGHT[node_k]
def node_quadrature_weight_linear(
node_index_in_elt: int,
):
return 0.125
if ORDER == 1:
return cache.get_func(node_quadrature_weight_linear, self.name)
return cache.get_func(node_quadrature_weight, self.name)
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def trace_node_quadrature_weight(
node_index_in_elt: int,
):
# We're either on a side interior or at a vertex
# If we find one index at extremum, pick the two other
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
if node_i == 0 or node_i == ORDER:
return LOBATTO_WEIGHT[node_j] * LOBATTO_WEIGHT[node_k]
if node_j == 0 or node_j == ORDER:
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_k]
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_j]
def trace_node_quadrature_weight_linear(
node_index_in_elt: int,
):
return 0.25
def trace_node_quadrature_weight_open(
node_index_in_elt: int,
):
return 0.0
if not is_closed(self.family):
return cache.get_func(trace_node_quadrature_weight_open, self.name)
if ORDER == 1:
return cache.get_func(trace_node_quadrature_weight_linear, self.name)
return cache.get_func(trace_node_quadrature_weight, self.name)
def make_element_inner_weight(self):
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
w = float(1.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
w *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
w *= coords[1] - LOBATTO_COORDS[k]
if k != node_k:
w *= coords[2] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_i] * LAGRANGE_SCALE[node_j] * LAGRANGE_SCALE[node_k]
return w
def element_inner_weight_linear(
coords: Coords,
node_index_in_elt: int,
):
v = CubeTripolynomialShapeFunctions._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
wz = (1.0 - coords[2]) * (1.0 - v[2]) + v[2] * coords[2]
return wx * wy * wz
if self.ORDER == 1 and is_closed(self.family):
return cache.get_func(element_inner_weight_linear, self.name)
return cache.get_func(element_inner_weight, self.name)
def make_element_inner_weight_gradient(self):
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
node_i, node_j, node_k = self._node_ijk(node_index_in_elt)
prefix_xy = float(1.0)
prefix_yz = float(1.0)
prefix_zx = float(1.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
prefix_yz *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
prefix_zx *= coords[1] - LOBATTO_COORDS[k]
if k != node_k:
prefix_xy *= coords[2] - LOBATTO_COORDS[k]
prefix_x = prefix_zx * prefix_xy
prefix_y = prefix_yz * prefix_xy
prefix_z = prefix_zx * prefix_yz
grad_x = float(0.0)
grad_y = float(0.0)
grad_z = float(0.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
delta_x = coords[0] - LOBATTO_COORDS[k]
grad_x = grad_x * delta_x + prefix_x
prefix_x *= delta_x
if k != node_j:
delta_y = coords[1] - LOBATTO_COORDS[k]
grad_y = grad_y * delta_y + prefix_y
prefix_y *= delta_y
if k != node_k:
delta_z = coords[2] - LOBATTO_COORDS[k]
grad_z = grad_z * delta_z + prefix_z
prefix_z *= delta_z
grad = (
LAGRANGE_SCALE[node_i]
* LAGRANGE_SCALE[node_j]
* LAGRANGE_SCALE[node_k]
* wp.vec3(
grad_x,
grad_y,
grad_z,
)
)
return grad
def element_inner_weight_gradient_linear(
coords: Coords,
node_index_in_elt: int,
):
v = CubeTripolynomialShapeFunctions._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
wz = (1.0 - coords[2]) * (1.0 - v[2]) + v[2] * coords[2]
dx = 2.0 * v[0] - 1.0
dy = 2.0 * v[1] - 1.0
dz = 2.0 * v[2] - 1.0
return wp.vec3(dx * wy * wz, dy * wz * wx, dz * wx * wy)
if self.ORDER == 1 and is_closed(self.family):
return cache.get_func(element_inner_weight_gradient_linear, self.name)
return cache.get_func(element_inner_weight_gradient, self.name)
def element_node_hexes(self):
from warp.fem.utils import grid_to_hexes
return grid_to_hexes(self.ORDER, self.ORDER, self.ORDER)
def element_node_tets(self):
from warp.fem.utils import grid_to_tets
return grid_to_tets(self.ORDER, self.ORDER, self.ORDER)
class CubeSerendipityShapeFunctions:
"""
Serendipity element ~ tensor product space without interior nodes
Edge shape functions are usual Lagrange shape functions times a bilinear function in the normal directions
Corner shape functions are trilinear shape functions times a function of (x^{d-1} + y^{d-1})
"""
# Node categories
VERTEX = wp.constant(0)
EDGE_X = wp.constant(1)
EDGE_Y = wp.constant(2)
def __init__(self, degree: int, family: Polynomial):
if not is_closed(family):
raise ValueError("A closed polynomial family is required to define serendipity elements")
if degree not in [2, 3]:
raise NotImplementedError("Serendipity element only implemented for order 2 or 3")
self.family = family
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant(8 + 12 * (degree - 1))
self.NODES_PER_EDGE = wp.constant(degree + 1)
lobatto_coords, lobatto_weight = quadrature_1d(point_count=degree + 1, family=family)
lagrange_scale = lagrange_scales(lobatto_coords)
NodeVec = wp.types.vector(length=degree + 1, dtype=wp.float32)
self.LOBATTO_COORDS = wp.constant(NodeVec(lobatto_coords))
self.LOBATTO_WEIGHT = wp.constant(NodeVec(lobatto_weight))
self.LAGRANGE_SCALE = wp.constant(NodeVec(lagrange_scale))
self.ORDER_PLUS_ONE = wp.constant(self.ORDER + 1)
self.node_type_and_type_index = self._get_node_type_and_type_index()
self._node_lobatto_indices = self._get_node_lobatto_indices()
@property
def name(self) -> str:
return f"Cube_S{self.ORDER}_{self.family}"
def _get_node_type_and_type_index(self):
@cache.dynamic_func(suffix=self.name)
def node_type_and_index(
node_index_in_elt: int,
):
if node_index_in_elt < 8:
return CubeSerendipityShapeFunctions.VERTEX, node_index_in_elt
type_index = (node_index_in_elt - 8) // 3
side = node_index_in_elt - 8 - 3 * type_index
return CubeSerendipityShapeFunctions.EDGE_X + side, type_index
return node_type_and_index
@wp.func
def _vertex_coords(vidx_in_cell: int):
x = vidx_in_cell // 4
y = (vidx_in_cell - 4 * x) // 2
z = vidx_in_cell - 4 * x - 2 * y
return wp.vec3i(x, y, z)
@wp.func
def _edge_coords(type_index: int):
index_in_side = type_index // 4
side_offset = type_index - 4 * index_in_side
return wp.vec3i(index_in_side + 1, side_offset // 2, side_offset & 1)
@wp.func
def _edge_axis(node_type: int):
return node_type - CubeSerendipityShapeFunctions.EDGE_X
@wp.func
def _cube_edge_index(node_type: int, type_index: int):
index_in_side = type_index // 4
side_offset = type_index - 4 * index_in_side
return 4 * (node_type - CubeSerendipityShapeFunctions.EDGE_X) + side_offset, index_in_side
def _get_node_lobatto_indices(self):
ORDER = self.ORDER
@cache.dynamic_func(suffix=self.name)
def node_lobatto_indices(node_type: int, type_index: int):
if node_type == CubeSerendipityShapeFunctions.VERTEX:
return CubeSerendipityShapeFunctions._vertex_coords(type_index) * ORDER
axis = CubeSerendipityShapeFunctions._edge_axis(node_type)
local_coords = CubeSerendipityShapeFunctions._edge_coords(type_index)
local_indices = wp.vec3i(local_coords[0], local_coords[1] * ORDER, local_coords[2] * ORDER)
return Grid3D._local_to_world(axis, local_indices)
return node_lobatto_indices
def make_node_coords_in_element(self):
LOBATTO_COORDS = self.LOBATTO_COORDS
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
node_coords = self._node_lobatto_indices(node_type, type_index)
return Coords(
LOBATTO_COORDS[node_coords[0]], LOBATTO_COORDS[node_coords[1]], LOBATTO_COORDS[node_coords[2]]
)
return node_coords_in_element
def make_node_quadrature_weight(self):
ORDER = self.ORDER
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == CubeSerendipityShapeFunctions.VERTEX:
return 1.0 / float(8 * ORDER * ORDER * ORDER)
return (1.0 - 1.0 / float(ORDER * ORDER * ORDER)) / float(12 * (ORDER - 1))
return node_quadrature_weight
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
@cache.dynamic_func(suffix=self.name)
def trace_node_quadrature_weight(
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == CubeSerendipityShapeFunctions.VERTEX:
return 0.25 / float(ORDER * ORDER)
return (0.25 - 0.25 / float(ORDER * ORDER)) / float(ORDER - 1)
return trace_node_quadrature_weight
def make_element_inner_weight(self):
ORDER = self.ORDER
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
DEGREE_3_SPHERE_RAD = wp.constant(2 * 0.5**2 + (0.5 - LOBATTO_COORDS[1]) ** 2)
DEGREE_3_SPHERE_SCALE = 1.0 / (0.75 - DEGREE_3_SPHERE_RAD)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == CubeSerendipityShapeFunctions.VERTEX:
node_ijk = CubeSerendipityShapeFunctions._vertex_coords(type_index)
cx = wp.select(node_ijk[0] == 0, coords[0], 1.0 - coords[0])
cy = wp.select(node_ijk[1] == 0, coords[1], 1.0 - coords[1])
cz = wp.select(node_ijk[2] == 0, coords[2], 1.0 - coords[2])
w = cx * cy * cz
if ORDER == 2:
w *= cx + cy + cz - 3.0 + LOBATTO_COORDS[1]
return w * LAGRANGE_SCALE[0]
if ORDER == 3:
w *= (
(cx - 0.5) * (cx - 0.5)
+ (cy - 0.5) * (cy - 0.5)
+ (cz - 0.5) * (cz - 0.5)
- DEGREE_3_SPHERE_RAD
)
return w * DEGREE_3_SPHERE_SCALE
axis = CubeSerendipityShapeFunctions._edge_axis(node_type)
node_all = CubeSerendipityShapeFunctions._edge_coords(type_index)
local_coords = Grid3D._world_to_local(axis, coords)
w = float(1.0)
w *= wp.select(node_all[1] == 0, local_coords[1], 1.0 - local_coords[1])
w *= wp.select(node_all[2] == 0, local_coords[2], 1.0 - local_coords[2])
for k in range(ORDER_PLUS_ONE):
if k != node_all[0]:
w *= local_coords[0] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_all[0]]
return w
return element_inner_weight
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
DEGREE_3_SPHERE_RAD = wp.constant(2 * 0.5**2 + (0.5 - LOBATTO_COORDS[1]) ** 2)
DEGREE_3_SPHERE_SCALE = 1.0 / (0.75 - DEGREE_3_SPHERE_RAD)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == CubeSerendipityShapeFunctions.VERTEX:
node_ijk = CubeSerendipityShapeFunctions._vertex_coords(type_index)
cx = wp.select(node_ijk[0] == 0, coords[0], 1.0 - coords[0])
cy = wp.select(node_ijk[1] == 0, coords[1], 1.0 - coords[1])
cz = wp.select(node_ijk[2] == 0, coords[2], 1.0 - coords[2])
gx = wp.select(node_ijk[0] == 0, 1.0, -1.0)
gy = wp.select(node_ijk[1] == 0, 1.0, -1.0)
gz = wp.select(node_ijk[2] == 0, 1.0, -1.0)
if ORDER == 2:
w = cx + cy + cz - 3.0 + LOBATTO_COORDS[1]
grad_x = cy * cz * gx * (w + cx)
grad_y = cz * cx * gy * (w + cy)
grad_z = cx * cy * gz * (w + cz)
return wp.vec3(grad_x, grad_y, grad_z) * LAGRANGE_SCALE[0]
if ORDER == 3:
w = (
(cx - 0.5) * (cx - 0.5)
+ (cy - 0.5) * (cy - 0.5)
+ (cz - 0.5) * (cz - 0.5)
- DEGREE_3_SPHERE_RAD
)
dw_dcx = 2.0 * cx - 1.0
dw_dcy = 2.0 * cy - 1.0
dw_dcz = 2.0 * cz - 1.0
grad_x = cy * cz * gx * (w + dw_dcx * cx)
grad_y = cz * cx * gy * (w + dw_dcy * cy)
grad_z = cx * cy * gz * (w + dw_dcz * cz)
return wp.vec3(grad_x, grad_y, grad_z) * DEGREE_3_SPHERE_SCALE
axis = CubeSerendipityShapeFunctions._edge_axis(node_type)
node_all = CubeSerendipityShapeFunctions._edge_coords(type_index)
local_coords = Grid3D._world_to_local(axis, coords)
w_long = wp.select(node_all[1] == 0, local_coords[1], 1.0 - local_coords[1])
w_lat = wp.select(node_all[2] == 0, local_coords[2], 1.0 - local_coords[2])
g_long = wp.select(node_all[1] == 0, 1.0, -1.0)
g_lat = wp.select(node_all[2] == 0, 1.0, -1.0)
w_alt = LAGRANGE_SCALE[node_all[0]]
g_alt = float(0.0)
prefix_alt = LAGRANGE_SCALE[node_all[0]]
for k in range(ORDER_PLUS_ONE):
if k != node_all[0]:
delta_alt = local_coords[0] - LOBATTO_COORDS[k]
w_alt *= delta_alt
g_alt = g_alt * delta_alt + prefix_alt
prefix_alt *= delta_alt
local_grad = wp.vec3(g_alt * w_long * w_lat, w_alt * g_long * w_lat, w_alt * w_long * g_lat)
return Grid3D._local_to_world(axis, local_grad)
return element_inner_weight_gradient
def element_node_tets(self):
from warp.fem.utils import grid_to_tets
if self.ORDER == 2:
element_tets = np.array(
[
[0, 8, 9, 10],
[1, 11, 10, 15],
[2, 9, 14, 13],
[3, 15, 13, 17],
[4, 12, 8, 16],
[5, 18, 16, 11],
[6, 14, 12, 19],
[7, 19, 18, 17],
[16, 12, 18, 11],
[8, 16, 12, 11],
[12, 19, 18, 14],
[14, 19, 17, 18],
[10, 9, 15, 8],
[10, 8, 11, 15],
[9, 13, 15, 14],
[13, 14, 17, 15],
]
)
middle_hex = np.array([8, 11, 9, 15, 12, 18, 14, 17])
middle_tets = middle_hex[grid_to_tets(1, 1, 1)]
return np.concatenate((element_tets, middle_tets))
raise NotImplementedError()
class CubeNonConformingPolynomialShapeFunctions:
# embeds the largest regular tet centered at (0.5, 0.5, 0.5) into the reference cube
_tet_height = 2.0 / 3.0
_tet_side = math.sqrt(3.0 / 2.0) * _tet_height
_tet_face_height = math.sqrt(3.0) / 2.0 * _tet_side
_tet_to_cube = np.array(
[
[_tet_side, _tet_side / 2.0, _tet_side / 2.0],
[0.0, _tet_face_height, _tet_face_height / 3.0],
[0.0, 0.0, _tet_height],
]
)
_TET_OFFSET = wp.constant(wp.vec3(0.5 - 0.5 * _tet_side, 0.5 - _tet_face_height / 3.0, 0.5 - 0.25 * _tet_height))
def __init__(self, degree: int):
self._tet_shape = TetrahedronPolynomialShapeFunctions(degree=degree)
self.ORDER = self._tet_shape.ORDER
self.NODES_PER_ELEMENT = self._tet_shape.NODES_PER_ELEMENT
self.element_node_tets = self._tet_shape.element_node_tets
@property
def name(self) -> str:
return f"Cube_P{self.ORDER}d"
def make_node_coords_in_element(self):
node_coords_in_tet = self._tet_shape.make_node_coords_in_element()
TET_TO_CUBE = wp.constant(wp.mat33(self._tet_to_cube))
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
tet_coords = node_coords_in_tet(node_index_in_elt)
return TET_TO_CUBE * tet_coords + CubeNonConformingPolynomialShapeFunctions._TET_OFFSET
return node_coords_in_element
def make_node_quadrature_weight(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def node_uniform_quadrature_weight(
node_index_in_elt: int,
):
return 1.0 / float(NODES_PER_ELEMENT)
return node_uniform_quadrature_weight
def make_trace_node_quadrature_weight(self):
# Non-conforming, zero measure on sides
@wp.func
def zero(node_index_in_elt: int):
return 0.0
return zero
def make_element_inner_weight(self):
tet_inner_weight = self._tet_shape.make_element_inner_weight()
CUBE_TO_TET = wp.constant(wp.mat33(np.linalg.inv(self._tet_to_cube)))
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
tet_coords = CUBE_TO_TET * (coords - CubeNonConformingPolynomialShapeFunctions._TET_OFFSET)
return tet_inner_weight(tet_coords, node_index_in_elt)
return element_inner_weight
def make_element_inner_weight_gradient(self):
tet_inner_weight_gradient = self._tet_shape.make_element_inner_weight_gradient()
CUBE_TO_TET = wp.constant(wp.mat33(np.linalg.inv(self._tet_to_cube)))
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
tet_coords = CUBE_TO_TET * (coords - CubeNonConformingPolynomialShapeFunctions._TET_OFFSET)
grad = tet_inner_weight_gradient(tet_coords, node_index_in_elt)
return wp.transpose(CUBE_TO_TET) * grad
return element_inner_weight_gradient
| 26,552 | Python | 35.423868 | 117 | 0.532239 |
NVIDIA/warp/warp/fem/space/shape/__init__.py | from enum import Enum
from typing import Optional
from warp.fem.geometry import element as _element
from warp.fem.polynomial import Polynomial
from .cube_shape_function import (
CubeNonConformingPolynomialShapeFunctions,
CubeSerendipityShapeFunctions,
CubeTripolynomialShapeFunctions,
)
from .shape_function import ConstantShapeFunction, ShapeFunction
from .square_shape_function import (
SquareBipolynomialShapeFunctions,
SquareNonConformingPolynomialShapeFunctions,
SquareSerendipityShapeFunctions,
)
from .tet_shape_function import TetrahedronNonConformingPolynomialShapeFunctions, TetrahedronPolynomialShapeFunctions
from .triangle_shape_function import Triangle2DNonConformingPolynomialShapeFunctions, Triangle2DPolynomialShapeFunctions
class ElementBasis(Enum):
"""Choice of basis function to equip individual elements"""
LAGRANGE = 0
"""Lagrange basis functions :math:`P_k` for simplices, tensor products :math:`Q_k` for squares and cubes"""
SERENDIPITY = 1
"""Serendipity elements :math:`S_k`, corresponding to Lagrange nodes with interior points removed (for degree <= 3)"""
NONCONFORMING_POLYNOMIAL = 2
"""Simplex Lagrange basis functions :math:`P_{kd}` embedded into non conforming reference elements (e.g. squares or cubes). Discontinuous only."""
def get_shape_function(
element: _element.Element,
space_dimension: int,
degree: int,
element_basis: ElementBasis,
family: Optional[Polynomial] = None,
):
"""
Equips a reference element with a shape function basis.
Args:
element: the reference element on which to build the shape function
space_dimension: the dimension of the embedding space
degree: polynomial degree of the per-element shape functions
element_basis: type of basis function for the individual elements
family: Polynomial family used to generate the shape function basis. If not provided, a reasonable basis is chosen.
Returns:
the corresponding shape function
"""
if degree == 0:
return ConstantShapeFunction(element, space_dimension)
if family is None:
family = Polynomial.LOBATTO_GAUSS_LEGENDRE
if isinstance(element, _element.Square):
if element_basis == ElementBasis.NONCONFORMING_POLYNOMIAL:
return SquareNonConformingPolynomialShapeFunctions(degree=degree)
if element_basis == ElementBasis.SERENDIPITY and degree > 1:
return SquareSerendipityShapeFunctions(degree=degree, family=family)
return SquareBipolynomialShapeFunctions(degree=degree, family=family)
if isinstance(element, _element.Triangle):
if element_basis == ElementBasis.NONCONFORMING_POLYNOMIAL:
return Triangle2DNonConformingPolynomialShapeFunctions(degree=degree)
if element_basis == ElementBasis.SERENDIPITY and degree > 2:
raise NotImplementedError("Serendipity variant not implemented yet for Triangle elements")
return Triangle2DPolynomialShapeFunctions(degree=degree)
if isinstance(element, _element.Cube):
if element_basis == ElementBasis.NONCONFORMING_POLYNOMIAL:
return CubeNonConformingPolynomialShapeFunctions(degree=degree)
if element_basis == ElementBasis.SERENDIPITY and degree > 1:
return CubeSerendipityShapeFunctions(degree=degree, family=family)
return CubeTripolynomialShapeFunctions(degree=degree, family=family)
if isinstance(element, _element.Tetrahedron):
if element_basis == ElementBasis.NONCONFORMING_POLYNOMIAL:
return TetrahedronNonConformingPolynomialShapeFunctions(degree=degree)
if element_basis == ElementBasis.SERENDIPITY and degree > 2:
raise NotImplementedError("Serendipity variant not implemented yet for Tet elements")
return TetrahedronPolynomialShapeFunctions(degree=degree)
return NotImplementedError("Unrecognized element type")
| 3,962 | Python | 42.54945 | 150 | 0.751388 |
NVIDIA/warp/warp/fem/space/shape/square_shape_function.py | import math
import numpy as np
import warp as wp
from warp.fem import cache
from warp.fem.polynomial import Polynomial, is_closed, lagrange_scales, quadrature_1d
from warp.fem.types import Coords
from .triangle_shape_function import Triangle2DPolynomialShapeFunctions
class SquareBipolynomialShapeFunctions:
def __init__(self, degree: int, family: Polynomial):
self.family = family
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) * (degree + 1))
self.NODES_PER_SIDE = wp.constant(degree + 1)
lobatto_coords, lobatto_weight = quadrature_1d(point_count=degree + 1, family=family)
lagrange_scale = lagrange_scales(lobatto_coords)
NodeVec = wp.types.vector(length=degree + 1, dtype=wp.float32)
self.LOBATTO_COORDS = wp.constant(NodeVec(lobatto_coords))
self.LOBATTO_WEIGHT = wp.constant(NodeVec(lobatto_weight))
self.LAGRANGE_SCALE = wp.constant(NodeVec(lagrange_scale))
self.ORDER_PLUS_ONE = wp.constant(self.ORDER + 1)
@property
def name(self) -> str:
return f"Square_Q{self.ORDER}_{self.family}"
def make_node_coords_in_element(self):
ORDER = self.ORDER
LOBATTO_COORDS = self.LOBATTO_COORDS
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
return Coords(LOBATTO_COORDS[node_i], LOBATTO_COORDS[node_j], 0.0)
return node_coords_in_element
def make_node_quadrature_weight(self):
ORDER = self.ORDER
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def node_quadrature_weight(
node_index_in_elt: int,
):
node_i = node_index_in_elt // (ORDER + 1)
node_j = node_index_in_elt - (ORDER + 1) * node_i
return LOBATTO_WEIGHT[node_i] * LOBATTO_WEIGHT[node_j]
def node_quadrature_weight_linear(
node_index_in_elt: int,
):
return 0.25
if ORDER == 1:
return cache.get_func(node_quadrature_weight_linear, self.name)
return cache.get_func(node_quadrature_weight, self.name)
@wp.func
def _vertex_coords_f(vidx_in_cell: int):
x = vidx_in_cell // 2
y = vidx_in_cell - 2 * x
return wp.vec2(float(x), float(y))
def make_trace_node_quadrature_weight(self):
ORDER = self.ORDER
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
def trace_node_quadrature_weight(
node_index_in_elt: int,
):
# We're either on a side interior or at a vertex
# I.e., either both indices are at extrema, or only one is
# Pick the interior one if possible, if both are at extrema pick any one
node_i = node_index_in_elt // (ORDER + 1)
if node_i > 0 and node_i < ORDER:
return LOBATTO_WEIGHT[node_i]
node_j = node_index_in_elt - (ORDER + 1) * node_i
return LOBATTO_WEIGHT[node_j]
def trace_node_quadrature_weight_linear(
node_index_in_elt: int,
):
return 0.5
def trace_node_quadrature_weight_open(
node_index_in_elt: int,
):
return 0.0
if not is_closed(self.family):
return cache.get_func(trace_node_quadrature_weight_open, self.name)
if ORDER == 1:
return cache.get_func(trace_node_quadrature_weight_linear, self.name)
return cache.get_func(trace_node_quadrature_weight, self.name)
def make_element_inner_weight(self):
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
node_i = node_index_in_elt // ORDER_PLUS_ONE
node_j = node_index_in_elt - ORDER_PLUS_ONE * node_i
w = float(1.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
w *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
w *= coords[1] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_i] * LAGRANGE_SCALE[node_j]
return w
def element_inner_weight_linear(
coords: Coords,
node_index_in_elt: int,
):
v = SquareBipolynomialShapeFunctions._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
return wx * wy
if self.ORDER == 1 and is_closed(self.family):
return cache.get_func(element_inner_weight_linear, self.name)
return cache.get_func(element_inner_weight, self.name)
def make_element_inner_weight_gradient(self):
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
node_i = node_index_in_elt // ORDER_PLUS_ONE
node_j = node_index_in_elt - ORDER_PLUS_ONE * node_i
prefix_x = float(1.0)
prefix_y = float(1.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
prefix_y *= coords[0] - LOBATTO_COORDS[k]
if k != node_j:
prefix_x *= coords[1] - LOBATTO_COORDS[k]
grad_x = float(0.0)
grad_y = float(0.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
delta_x = coords[0] - LOBATTO_COORDS[k]
grad_x = grad_x * delta_x + prefix_x
prefix_x *= delta_x
if k != node_j:
delta_y = coords[1] - LOBATTO_COORDS[k]
grad_y = grad_y * delta_y + prefix_y
prefix_y *= delta_y
grad = LAGRANGE_SCALE[node_i] * LAGRANGE_SCALE[node_j] * wp.vec2(grad_x, grad_y)
return grad
def element_inner_weight_gradient_linear(
coords: Coords,
node_index_in_elt: int,
):
v = SquareBipolynomialShapeFunctions._vertex_coords_f(node_index_in_elt)
wx = (1.0 - coords[0]) * (1.0 - v[0]) + v[0] * coords[0]
wy = (1.0 - coords[1]) * (1.0 - v[1]) + v[1] * coords[1]
dx = 2.0 * v[0] - 1.0
dy = 2.0 * v[1] - 1.0
return wp.vec2(dx * wy, dy * wx)
if self.ORDER == 1 and is_closed(self.family):
return cache.get_func(element_inner_weight_gradient_linear, self.name)
return cache.get_func(element_inner_weight_gradient, self.name)
def element_node_triangulation(self):
from warp.fem.utils import grid_to_tris
return grid_to_tris(self.ORDER, self.ORDER)
class SquareSerendipityShapeFunctions:
"""
Serendipity element ~ tensor product space without interior nodes
Side shape functions are usual Lagrange shape functions times a linear function in the normal direction
Corner shape functions are bilinear shape functions times a function of (x^{d-1} + y^{d-1})
"""
# Node categories
VERTEX = wp.constant(0)
EDGE_X = wp.constant(1)
EDGE_Y = wp.constant(2)
def __init__(self, degree: int, family: Polynomial):
if not is_closed(family):
raise ValueError("A closed polynomial family is required to define serendipity elements")
if degree not in [2, 3]:
raise NotImplementedError("Serendipity element only implemented for order 2 or 3")
self.family = family
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant(4 * degree)
self.NODES_PER_SIDE = wp.constant(degree + 1)
lobatto_coords, lobatto_weight = quadrature_1d(point_count=degree + 1, family=family)
lagrange_scale = lagrange_scales(lobatto_coords)
NodeVec = wp.types.vector(length=degree + 1, dtype=wp.float32)
self.LOBATTO_COORDS = wp.constant(NodeVec(lobatto_coords))
self.LOBATTO_WEIGHT = wp.constant(NodeVec(lobatto_weight))
self.LAGRANGE_SCALE = wp.constant(NodeVec(lagrange_scale))
self.ORDER_PLUS_ONE = wp.constant(self.ORDER + 1)
self.node_type_and_type_index = self._get_node_type_and_type_index()
self._node_lobatto_indices = self._get_node_lobatto_indices()
@property
def name(self) -> str:
return f"Square_S{self.ORDER}_{self.family}"
def _get_node_type_and_type_index(self):
@cache.dynamic_func(suffix=self.name)
def node_type_and_index(
node_index_in_elt: int,
):
if node_index_in_elt < 4:
return SquareSerendipityShapeFunctions.VERTEX, node_index_in_elt
type_index = (node_index_in_elt - 4) // 2
side = node_index_in_elt - 4 - 2 * type_index
return SquareSerendipityShapeFunctions.EDGE_X + side, type_index
return node_type_and_index
@wp.func
def side_offset_and_index(type_index: int):
index_in_side = type_index // 2
side_offset = type_index - 2 * index_in_side
return side_offset, index_in_side
def _get_node_lobatto_indices(self):
ORDER = self.ORDER
@cache.dynamic_func(suffix=self.name)
def node_lobatto_indices(node_type: int, type_index: int):
if node_type == SquareSerendipityShapeFunctions.VERTEX:
node_i = type_index // 2
node_j = type_index - 2 * node_i
return node_i * ORDER, node_j * ORDER
side_offset, index_in_side = SquareSerendipityShapeFunctions.side_offset_and_index(type_index)
if node_type == SquareSerendipityShapeFunctions.EDGE_X:
node_i = 1 + index_in_side
node_j = side_offset * ORDER
else:
node_j = 1 + index_in_side
node_i = side_offset * ORDER
return node_i, node_j
return node_lobatto_indices
def make_node_coords_in_element(self):
LOBATTO_COORDS = self.LOBATTO_COORDS
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
node_i, node_j = self._node_lobatto_indices(node_type, type_index)
return Coords(LOBATTO_COORDS[node_i], LOBATTO_COORDS[node_j], 0.0)
return node_coords_in_element
def make_node_quadrature_weight(self):
ORDER = self.ORDER
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == SquareSerendipityShapeFunctions.VERTEX:
return 0.25 / float(ORDER * ORDER)
return (0.25 - 0.25 / float(ORDER * ORDER)) / float(ORDER - 1)
return node_quadrature_weight
def make_trace_node_quadrature_weight(self):
LOBATTO_WEIGHT = self.LOBATTO_WEIGHT
@cache.dynamic_func(suffix=self.name)
def trace_node_quadrature_weight(
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == SquareSerendipityShapeFunctions.VERTEX:
return LOBATTO_WEIGHT[0]
side_offset, index_in_side = SquareSerendipityShapeFunctions.side_offset_and_index(type_index)
return LOBATTO_WEIGHT[1 + index_in_side]
return trace_node_quadrature_weight
def make_element_inner_weight(self):
ORDER = self.ORDER
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
DEGREE_3_CIRCLE_RAD = wp.constant(0.5**2 + (0.5 - LOBATTO_COORDS[1]) ** 2)
DEGREE_3_CIRCLE_SCALE = 1.0 / (0.5 - DEGREE_3_CIRCLE_RAD)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
node_i, node_j = self._node_lobatto_indices(node_type, type_index)
if node_type == SquareSerendipityShapeFunctions.VERTEX:
cx = wp.select(node_i == 0, coords[0], 1.0 - coords[0])
cy = wp.select(node_j == 0, coords[1], 1.0 - coords[1])
w = cx * cy
if ORDER == 2:
w *= cx + cy - 2.0 + LOBATTO_COORDS[1]
return w * LAGRANGE_SCALE[0]
if ORDER == 3:
w *= (cx - 0.5) * (cx - 0.5) + (cy - 0.5) * (cy - 0.5) - DEGREE_3_CIRCLE_RAD
return w * DEGREE_3_CIRCLE_SCALE
w = float(1.0)
if node_type == SquareSerendipityShapeFunctions.EDGE_Y:
w *= wp.select(node_i == 0, coords[0], 1.0 - coords[0])
else:
for k in range(ORDER_PLUS_ONE):
if k != node_i:
w *= coords[0] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_i]
if node_type == SquareSerendipityShapeFunctions.EDGE_X:
w *= wp.select(node_j == 0, coords[1], 1.0 - coords[1])
else:
for k in range(ORDER_PLUS_ONE):
if k != node_j:
w *= coords[1] - LOBATTO_COORDS[k]
w *= LAGRANGE_SCALE[node_j]
return w
return element_inner_weight
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
ORDER_PLUS_ONE = self.ORDER_PLUS_ONE
LOBATTO_COORDS = self.LOBATTO_COORDS
LAGRANGE_SCALE = self.LAGRANGE_SCALE
DEGREE_3_CIRCLE_RAD = wp.constant(0.5**2 + (0.5 - LOBATTO_COORDS[1]) ** 2)
DEGREE_3_CIRCLE_SCALE = 1.0 / (0.5 - DEGREE_3_CIRCLE_RAD)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
node_i, node_j = self._node_lobatto_indices(node_type, type_index)
if node_type == SquareSerendipityShapeFunctions.VERTEX:
cx = wp.select(node_i == 0, coords[0], 1.0 - coords[0])
cy = wp.select(node_j == 0, coords[1], 1.0 - coords[1])
gx = wp.select(node_i == 0, 1.0, -1.0)
gy = wp.select(node_j == 0, 1.0, -1.0)
if ORDER == 2:
w = cx + cy - 2.0 + LOBATTO_COORDS[1]
grad_x = cy * gx * (w + cx)
grad_y = cx * gy * (w + cy)
return wp.vec2(grad_x, grad_y) * LAGRANGE_SCALE[0]
if ORDER == 3:
w = (cx - 0.5) * (cx - 0.5) + (cy - 0.5) * (cy - 0.5) - DEGREE_3_CIRCLE_RAD
dw_dcx = 2.0 * cx - 1.0
dw_dcy = 2.0 * cy - 1.0
grad_x = cy * gx * (w + cx * dw_dcx)
grad_y = cx * gy * (w + cy * dw_dcy)
return wp.vec2(grad_x, grad_y) * DEGREE_3_CIRCLE_SCALE
if node_type == SquareSerendipityShapeFunctions.EDGE_X:
prefix_x = wp.select(node_j == 0, coords[1], 1.0 - coords[1])
else:
prefix_x = LAGRANGE_SCALE[node_j]
for k in range(ORDER_PLUS_ONE):
if k != node_j:
prefix_x *= coords[1] - LOBATTO_COORDS[k]
if node_type == SquareSerendipityShapeFunctions.EDGE_Y:
prefix_y = wp.select(node_i == 0, coords[0], 1.0 - coords[0])
else:
prefix_y = LAGRANGE_SCALE[node_i]
for k in range(ORDER_PLUS_ONE):
if k != node_i:
prefix_y *= coords[0] - LOBATTO_COORDS[k]
if node_type == SquareSerendipityShapeFunctions.EDGE_X:
grad_y = wp.select(node_j == 0, 1.0, -1.0) * prefix_y
else:
prefix_y *= LAGRANGE_SCALE[node_j]
grad_y = float(0.0)
for k in range(ORDER_PLUS_ONE):
if k != node_j:
delta_y = coords[1] - LOBATTO_COORDS[k]
grad_y = grad_y * delta_y + prefix_y
prefix_y *= delta_y
if node_type == SquareSerendipityShapeFunctions.EDGE_Y:
grad_x = wp.select(node_i == 0, 1.0, -1.0) * prefix_x
else:
prefix_x *= LAGRANGE_SCALE[node_i]
grad_x = float(0.0)
for k in range(ORDER_PLUS_ONE):
if k != node_i:
delta_x = coords[0] - LOBATTO_COORDS[k]
grad_x = grad_x * delta_x + prefix_x
prefix_x *= delta_x
grad = wp.vec2(grad_x, grad_y)
return grad
return element_inner_weight_gradient
def element_node_triangulation(self):
if self.ORDER == 2:
element_triangles = [
[0, 4, 5],
[5, 4, 6],
[5, 6, 1],
[4, 2, 7],
[4, 7, 6],
[6, 7, 3],
]
else:
element_triangles = [
[0, 4, 5],
[2, 7, 8],
[3, 10, 11],
[1, 9, 6],
[5, 6, 9],
[5, 4, 6],
[8, 11, 10],
[8, 7, 11],
[4, 8, 10],
[4, 10, 6],
]
return element_triangles
class SquareNonConformingPolynomialShapeFunctions:
# embeds the largest equilateral triangle centered at (0.5, 0.5) into the reference square
_tri_height = 0.75
_tri_side = 2.0 / math.sqrt(3.0) * _tri_height
_tri_to_square = np.array([[_tri_side, _tri_side / 2.0], [0.0, _tri_height]])
_TRI_OFFSET = wp.constant(wp.vec2(0.5 - 0.5 * _tri_side, 0.5 - _tri_height / 3.0))
def __init__(self, degree: int):
self._tri_shape = Triangle2DPolynomialShapeFunctions(degree=degree)
self.ORDER = self._tri_shape.ORDER
self.NODES_PER_ELEMENT = self._tri_shape.NODES_PER_ELEMENT
self.element_node_triangulation = self._tri_shape.element_node_triangulation
@property
def name(self) -> str:
return f"Square_P{self.ORDER}d"
def make_node_coords_in_element(self):
node_coords_in_tet = self._tri_shape.make_node_coords_in_element()
TRI_TO_SQUARE = wp.constant(wp.mat22(self._tri_to_square))
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
tri_coords = node_coords_in_tet(node_index_in_elt)
coords = (
TRI_TO_SQUARE * wp.vec2(tri_coords[1], tri_coords[2])
) + SquareNonConformingPolynomialShapeFunctions._TRI_OFFSET
return Coords(coords[0], coords[1], 0.0)
return node_coords_in_element
def make_node_quadrature_weight(self):
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
if self.ORDER == 2:
# Intrinsic quadrature (order 2)
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight_quadratic(
node_index_in_elt: int,
):
node_type, type_index = self._tri_shape.node_type_and_type_index(node_index_in_elt)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
return 0.18518521
return 0.14814811
return node_quadrature_weight_quadratic
@cache.dynamic_func(suffix=self.name)
def node_uniform_quadrature_weight(
node_index_in_elt: int,
):
return 1.0 / float(NODES_PER_ELEMENT)
return node_uniform_quadrature_weight
def make_trace_node_quadrature_weight(self):
# Non-conforming, zero measure on sides
@wp.func
def zero(node_index_in_elt: int):
return 0.0
return zero
def make_element_inner_weight(self):
tri_inner_weight = self._tri_shape.make_element_inner_weight()
SQUARE_TO_TRI = wp.constant(wp.mat22(np.linalg.inv(self._tri_to_square)))
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
tri_param = SQUARE_TO_TRI * (
wp.vec2(coords[0], coords[1]) - SquareNonConformingPolynomialShapeFunctions._TRI_OFFSET
)
tri_coords = Coords(1.0 - tri_param[0] - tri_param[1], tri_param[0], tri_param[1])
return tri_inner_weight(tri_coords, node_index_in_elt)
return element_inner_weight
def make_element_inner_weight_gradient(self):
tri_inner_weight_gradient = self._tri_shape.make_element_inner_weight_gradient()
SQUARE_TO_TRI = wp.constant(wp.mat22(np.linalg.inv(self._tri_to_square)))
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
tri_param = SQUARE_TO_TRI * (
wp.vec2(coords[0], coords[1]) - SquareNonConformingPolynomialShapeFunctions._TRI_OFFSET
)
tri_coords = Coords(1.0 - tri_param[0] - tri_param[1], tri_param[0], tri_param[1])
grad = tri_inner_weight_gradient(tri_coords, node_index_in_elt)
return wp.transpose(SQUARE_TO_TRI) * grad
return element_inner_weight_gradient
| 22,214 | Python | 35.29902 | 107 | 0.547673 |
NVIDIA/warp/warp/fem/space/shape/triangle_shape_function.py | import numpy as np
import warp as wp
from warp.fem import cache
from warp.fem.types import Coords
def _triangle_node_index(tx: int, ty: int, degree: int):
VERTEX_NODE_COUNT = 3
SIDE_INTERIOR_NODE_COUNT = degree - 1
# Index in similar order to e.g. VTK
# First vertices, then edge (counterclockwise) then interior points (recursively)
if tx == 0:
if ty == 0:
return 0
elif ty == degree:
return 2
else:
edge_index = 2
return VERTEX_NODE_COUNT + SIDE_INTERIOR_NODE_COUNT * edge_index + (SIDE_INTERIOR_NODE_COUNT - ty)
elif ty == 0:
if tx == degree:
return 1
else:
edge_index = 0
return VERTEX_NODE_COUNT + SIDE_INTERIOR_NODE_COUNT * edge_index + tx - 1
elif tx + ty == degree:
edge_index = 1
return VERTEX_NODE_COUNT + SIDE_INTERIOR_NODE_COUNT * edge_index + ty - 1
vertex_edge_node_count = 3 * degree
return vertex_edge_node_count + _triangle_node_index(tx - 1, ty - 1, degree - 3)
class Triangle2DPolynomialShapeFunctions:
VERTEX = wp.constant(0)
EDGE = wp.constant(1)
INTERIOR = wp.constant(2)
def __init__(self, degree: int):
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) * (degree + 2) // 2)
self.NODES_PER_SIDE = wp.constant(degree + 1)
triangle_coords = np.empty((self.NODES_PER_ELEMENT, 2), dtype=int)
for tx in range(degree + 1):
for ty in range(degree + 1 - tx):
index = _triangle_node_index(tx, ty, degree)
triangle_coords[index] = [tx, ty]
CoordTypeVec = wp.mat(dtype=int, shape=(self.NODES_PER_ELEMENT, 2))
self.NODE_TRIANGLE_COORDS = wp.constant(CoordTypeVec(triangle_coords))
self.node_type_and_type_index = self._get_node_type_and_type_index()
self._node_triangle_coordinates = self._get_node_triangle_coordinates()
@property
def name(self) -> str:
return f"Tri_P{self.ORDER}"
def _get_node_triangle_coordinates(self):
NODE_TRIANGLE_COORDS = self.NODE_TRIANGLE_COORDS
def node_triangle_coordinates(
node_index_in_elt: int,
):
return wp.vec2i(NODE_TRIANGLE_COORDS[node_index_in_elt, 0], NODE_TRIANGLE_COORDS[node_index_in_elt, 1])
return cache.get_func(node_triangle_coordinates, self.name)
def _get_node_type_and_type_index(self):
ORDER = self.ORDER
def node_type_and_index(
node_index_in_elt: int,
):
if node_index_in_elt < 3:
return Triangle2DPolynomialShapeFunctions.VERTEX, node_index_in_elt
if node_index_in_elt < 3 * ORDER:
return Triangle2DPolynomialShapeFunctions.EDGE, (node_index_in_elt - 3)
return Triangle2DPolynomialShapeFunctions.INTERIOR, (node_index_in_elt - 3 * ORDER)
return cache.get_func(node_type_and_index, self.name)
def make_node_coords_in_element(self):
ORDER = self.ORDER
def node_coords_in_element(
node_index_in_elt: int,
):
tri_coords = self._node_triangle_coordinates(node_index_in_elt)
cx = float(tri_coords[0]) / float(ORDER)
cy = float(tri_coords[1]) / float(ORDER)
return Coords(1.0 - cx - cy, cx, cy)
return cache.get_func(node_coords_in_element, self.name)
def make_node_quadrature_weight(self):
if self.ORDER == 3:
# P3 intrisic quadrature
vertex_weight = 1.0 / 30
edge_weight = 0.075
interior_weight = 0.45
elif self.ORDER == 2:
# Order 1, but optimized quadrature weights for monomials of order <= 4
vertex_weight = 0.022335964126
edge_weight = 0.310997369207
interior_weight = 0.0
else:
vertex_weight = 1.0 / self.NODES_PER_ELEMENT
edge_weight = 1.0 / self.NODES_PER_ELEMENT
interior_weight = 1.0 / self.NODES_PER_ELEMENT
VERTEX_WEIGHT = wp.constant(vertex_weight)
EDGE_WEIGHT = wp.constant(edge_weight)
INTERIOR_WEIGHT = wp.constant(interior_weight)
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(node_index_in_element: int):
node_type, type_index = self.node_type_and_type_index(node_index_in_element)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
return VERTEX_WEIGHT
elif node_type == Triangle2DPolynomialShapeFunctions.EDGE:
return EDGE_WEIGHT
return INTERIOR_WEIGHT
return node_quadrature_weight
def make_trace_node_quadrature_weight(self):
# Closed Newton-Cotes
if self.ORDER == 3:
vertex_weight = 1.0 / 8.0
edge_weight = 3.0 / 8.0
elif self.ORDER == 2:
vertex_weight = 1.0 / 6.0
edge_weight = 2.0 / 3.0
else:
vertex_weight = 1.0 / self.NODES_PER_SIDE
edge_weight = 1.0 / self.NODES_PER_SIDE
VERTEX_WEIGHT = wp.constant(vertex_weight)
EDGE_WEIGHT = wp.constant(edge_weight)
@cache.dynamic_func(suffix=self.name)
def trace_node_quadrature_weight(node_index_in_element: int):
node_type, type_index = self.node_type_and_type_index(node_index_in_element)
return wp.select(node_type == Triangle2DPolynomialShapeFunctions.VERTEX, EDGE_WEIGHT, VERTEX_WEIGHT)
return trace_node_quadrature_weight
def make_element_inner_weight(self):
ORDER = self.ORDER
def element_inner_weight_linear(
coords: Coords,
node_index_in_elt: int,
):
return coords[node_index_in_elt]
def element_inner_weight_quadratic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
# Vertex
return coords[type_index] * (2.0 * coords[type_index] - 1.0)
# Edge
c1 = type_index
c2 = (type_index + 1) % 3
return 4.0 * coords[c1] * coords[c2]
def element_inner_weight_cubic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
# Vertex
return 0.5 * coords[type_index] * (3.0 * coords[type_index] - 1.0) * (3.0 * coords[type_index] - 2.0)
elif node_type == Triangle2DPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
k = type_index - 2 * edge
c1 = (edge + k) % 3
c2 = (edge + 1 - k) % 3
return 4.5 * coords[c1] * coords[c2] * (3.0 * coords[c1] - 1.0)
# Interior
return 27.0 * coords[0] * coords[1] * coords[2]
if ORDER == 1:
return cache.get_func(element_inner_weight_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_cubic, self.name)
return None
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
def element_inner_weight_gradient_linear(
coords: Coords,
node_index_in_elt: int,
):
dw_dc = wp.vec3(0.0)
dw_dc[node_index_in_elt] = 1.0
dw_du = wp.vec2(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0])
return dw_du
def element_inner_weight_gradient_quadratic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
dw_dc = wp.vec3(0.0)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = 4.0 * coords[type_index] - 1.0
else:
# Edge
c1 = type_index
c2 = (type_index + 1) % 3
dw_dc[c1] = 4.0 * coords[c2]
dw_dc[c2] = 4.0 * coords[c1]
dw_du = wp.vec2(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0])
return dw_du
def element_inner_weight_gradient_cubic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
dw_dc = wp.vec3(0.0)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = (
0.5 * 27.0 * coords[type_index] * coords[type_index] - 9.0 * coords[type_index] + 1.0
)
elif node_type == Triangle2DPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
k = type_index - 2 * edge
c1 = (edge + k) % 3
c2 = (edge + 1 - k) % 3
dw_dc[c1] = 4.5 * coords[c2] * (6.0 * coords[c1] - 1.0)
dw_dc[c2] = 4.5 * coords[c1] * (3.0 * coords[c1] - 1.0)
else:
# Interior
dw_dc = wp.vec3(
27.0 * coords[1] * coords[2], 27.0 * coords[2] * coords[0], 27.0 * coords[0] * coords[1]
)
dw_du = wp.vec2(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0])
return dw_du
if ORDER == 1:
return cache.get_func(element_inner_weight_gradient_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_gradient_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_gradient_cubic, self.name)
return None
def element_node_triangulation(self):
if self.ORDER == 1:
element_triangles = [[0, 1, 2]]
if self.ORDER == 2:
element_triangles = [[0, 3, 5], [3, 1, 4], [2, 5, 4], [3, 4, 5]]
elif self.ORDER == 3:
element_triangles = [
[0, 3, 8],
[3, 4, 9],
[4, 1, 5],
[8, 3, 9],
[4, 5, 9],
[8, 9, 7],
[9, 5, 6],
[6, 7, 9],
[7, 6, 2],
]
return np.array(element_triangles)
class Triangle2DNonConformingPolynomialShapeFunctions:
def __init__(self, degree: int):
self._tri_shape = Triangle2DPolynomialShapeFunctions(degree=degree)
self.ORDER = self._tri_shape.ORDER
self.NODES_PER_ELEMENT = self._tri_shape.NODES_PER_ELEMENT
self.element_node_triangulation = self._tri_shape.element_node_triangulation
# Coordinates (a, b, b) of embedded triangle
if self.ORDER == 1:
# Order 2
a = 2.0 / 3.0
elif self.ORDER == 2:
# Order 2, optimized for small intrinsic quadrature error up to degree 4
a = 0.7790771484375001
elif self.ORDER == 3:
# Order 3, optimized for small intrinsic quadrature error up to degree 6
a = 0.8429443359375002
else:
a = 1.0
b = 0.5 * (1.0 - a)
self._small_to_big = np.full((3, 3), b) + (a - b) * np.eye(3)
self._tri_scale = a - b
@property
def name(self) -> str:
return f"Tri_P{self.ORDER}d"
def make_node_quadrature_weight(self):
# Intrinsic quadrature -- precomputed integral of node shape functions
# over element. Order equal to self.ORDER
if self.ORDER == 2:
vertex_weight = 0.13743348
edge_weight = 0.19589985
interior_weight = 0.0
elif self.ORDER == 3:
vertex_weight = 0.07462578
edge_weight = 0.1019807
interior_weight = 0.16423881
else:
vertex_weight = 1.0 / self.NODES_PER_ELEMENT
edge_weight = 1.0 / self.NODES_PER_ELEMENT
interior_weight = 1.0 / self.NODES_PER_ELEMENT
VERTEX_WEIGHT = wp.constant(vertex_weight)
EDGE_WEIGHT = wp.constant(edge_weight)
INTERIOR_WEIGHT = wp.constant(interior_weight)
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(node_index_in_element: int):
node_type, type_index = self._tri_shape.node_type_and_type_index(node_index_in_element)
if node_type == Triangle2DPolynomialShapeFunctions.VERTEX:
return VERTEX_WEIGHT
elif node_type == Triangle2DPolynomialShapeFunctions.EDGE:
return EDGE_WEIGHT
return INTERIOR_WEIGHT
return node_quadrature_weight
def make_trace_node_quadrature_weight(self):
# Non-conforming, zero measure on sides
@wp.func
def zero(node_index_in_elt: int):
return 0.0
return zero
def make_node_coords_in_element(self):
node_coords_in_tet = self._tri_shape.make_node_coords_in_element()
SMALL_TO_BIG = wp.constant(wp.mat33(self._small_to_big))
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
tri_coords = node_coords_in_tet(node_index_in_elt)
return SMALL_TO_BIG * tri_coords
return node_coords_in_element
def make_element_inner_weight(self):
tri_inner_weight = self._tri_shape.make_element_inner_weight()
BIG_TO_SMALL = wp.constant(wp.mat33(np.linalg.inv(self._small_to_big)))
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
tri_coords = BIG_TO_SMALL * coords
return tri_inner_weight(tri_coords, node_index_in_elt)
return element_inner_weight
def make_element_inner_weight_gradient(self):
tri_inner_weight_gradient = self._tri_shape.make_element_inner_weight_gradient()
BIG_TO_SMALL = wp.constant(wp.mat33(np.linalg.inv(self._small_to_big)))
INV_TRI_SCALE = wp.constant(1.0 / self._tri_scale)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
tri_coords = BIG_TO_SMALL * coords
grad = tri_inner_weight_gradient(tri_coords, node_index_in_elt)
return INV_TRI_SCALE * grad
return element_inner_weight_gradient
| 14,886 | Python | 33.62093 | 117 | 0.555757 |
NVIDIA/warp/warp/fem/space/shape/tet_shape_function.py | import numpy as np
import warp as wp
from warp.fem import cache
from warp.fem.types import Coords
def _tet_node_index(tx: int, ty: int, tz: int, degree: int):
from .triangle_shape_function import _triangle_node_index
VERTEX_NODE_COUNT = 4
EDGE_INTERIOR_NODE_COUNT = degree - 1
VERTEX_EDGE_NODE_COUNT = VERTEX_NODE_COUNT + 6 * EDGE_INTERIOR_NODE_COUNT
FACE_INTERIOR_NODE_COUNT = (degree - 1) * (degree - 2) // 2
VERTEX_EDGE_FACE_NODE_COUNT = VERTEX_EDGE_NODE_COUNT + 4 * FACE_INTERIOR_NODE_COUNT
# Index in similar order to e.g. VTK
# First vertices, then edges (counterclockwise), then faces, then interior points (recursively)
if tx == 0:
if ty == 0:
if tz == 0:
return 0
elif tz == degree:
return 3
else:
# 0-3 edge
edge_index = 3
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tz - 1)
elif tz == 0:
if ty == degree:
return 2
else:
# 2-0 edge
edge_index = 2
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (EDGE_INTERIOR_NODE_COUNT - ty)
elif tz + ty == degree:
# 2-3 edge
edge_index = 5
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tz - 1)
else:
# 2-3-0 face
face_index = 2
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(degree - 1 - ty - tz, tz - 1, degree - 3)
)
elif ty == 0:
if tz == 0:
if tx == degree:
return 1
else:
# 0-1 edge
edge_index = 0
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tx - 1)
elif tz + tx == degree:
# 1-3 edge
edge_index = 4
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (tz - 1)
else:
# 3-0-1 face
face_index = 3
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(tx - 1, tz - 1, degree - 3)
)
elif tz == 0:
if tx + ty == degree:
# 1-2 edge
edge_index = 1
return VERTEX_NODE_COUNT + EDGE_INTERIOR_NODE_COUNT * edge_index + (ty - 1)
else:
# 0-1-2 face
face_index = 0
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(tx - 1, ty - 1, degree - 3)
)
elif tx + ty + tz == degree:
# 1-2-3 face
face_index = 1
return (
VERTEX_EDGE_NODE_COUNT
+ FACE_INTERIOR_NODE_COUNT * face_index
+ _triangle_node_index(tx - 1, tz - 1, degree - 3)
)
return VERTEX_EDGE_FACE_NODE_COUNT + _tet_node_index(tx - 1, ty - 1, tz - 1, degree - 4)
class TetrahedronPolynomialShapeFunctions:
INVALID = wp.constant(-1)
VERTEX = wp.constant(0)
EDGE = wp.constant(1)
FACE = wp.constant(2)
INTERIOR = wp.constant(3)
def __init__(self, degree: int):
self.ORDER = wp.constant(degree)
self.NODES_PER_ELEMENT = wp.constant((degree + 1) * (degree + 2) * (degree + 3) // 6)
self.NODES_PER_SIDE = wp.constant((degree + 1) * (degree + 2) // 2)
tet_coords = np.empty((self.NODES_PER_ELEMENT, 3), dtype=int)
for tx in range(degree + 1):
for ty in range(degree + 1 - tx):
for tz in range(degree + 1 - tx - ty):
index = _tet_node_index(tx, ty, tz, degree)
tet_coords[index] = [tx, ty, tz]
CoordTypeVec = wp.mat(dtype=int, shape=(self.NODES_PER_ELEMENT, 3))
self.NODE_TET_COORDS = wp.constant(CoordTypeVec(tet_coords))
self.node_type_and_type_index = self._get_node_type_and_type_index()
self._node_tet_coordinates = self._get_node_tet_coordinates()
@property
def name(self) -> str:
return f"Tet_P{self.ORDER}"
def _get_node_tet_coordinates(self):
NODE_TET_COORDS = self.NODE_TET_COORDS
def node_tet_coordinates(
node_index_in_elt: int,
):
return wp.vec3i(
NODE_TET_COORDS[node_index_in_elt, 0],
NODE_TET_COORDS[node_index_in_elt, 1],
NODE_TET_COORDS[node_index_in_elt, 2],
)
return cache.get_func(node_tet_coordinates, self.name)
def _get_node_type_and_type_index(self):
ORDER = self.ORDER
NODES_PER_ELEMENT = self.NODES_PER_ELEMENT
def node_type_and_index(
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= NODES_PER_ELEMENT:
return TetrahedronPolynomialShapeFunctions.INVALID, TetrahedronPolynomialShapeFunctions.INVALID
if node_index_in_elt < 4:
return TetrahedronPolynomialShapeFunctions.VERTEX, node_index_in_elt
if node_index_in_elt < (6 * ORDER - 2):
return TetrahedronPolynomialShapeFunctions.EDGE, (node_index_in_elt - 4)
if node_index_in_elt < (2 * ORDER * ORDER + 2):
return TetrahedronPolynomialShapeFunctions.FACE, (node_index_in_elt - (6 * ORDER - 2))
return TetrahedronPolynomialShapeFunctions.INTERIOR, (node_index_in_elt - (2 * ORDER * ORDER + 2))
return cache.get_func(node_type_and_index, self.name)
def make_node_coords_in_element(self):
ORDER = self.ORDER
def node_coords_in_element(
node_index_in_elt: int,
):
tet_coords = self._node_tet_coordinates(node_index_in_elt)
cx = float(tet_coords[0]) / float(ORDER)
cy = float(tet_coords[1]) / float(ORDER)
cz = float(tet_coords[2]) / float(ORDER)
return Coords(cx, cy, cz)
return cache.get_func(node_coords_in_element, self.name)
def make_node_quadrature_weight(self):
if self.ORDER == 3:
# Order 1, but optimized quadrature weights for monomials of order <= 6
vertex_weight = 0.007348845656
edge_weight = 0.020688129855
face_weight = 0.180586764778
interior_weight = 0.0
else:
vertex_weight = 1.0 / self.NODES_PER_ELEMENT
edge_weight = 1.0 / self.NODES_PER_ELEMENT
face_weight = 1.0 / self.NODES_PER_ELEMENT
interior_weight = 1.0 / self.NODES_PER_ELEMENT
VERTEX_WEIGHT = wp.constant(vertex_weight)
EDGE_WEIGHT = wp.constant(edge_weight)
FACE_WEIGHT = wp.constant(face_weight)
INTERIOR_WEIGHT = wp.constant(interior_weight)
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(node_index_in_element: int):
node_type, type_index = self.node_type_and_type_index(node_index_in_element)
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
return VERTEX_WEIGHT
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
return EDGE_WEIGHT
elif node_type == TetrahedronPolynomialShapeFunctions.FACE:
return FACE_WEIGHT
return INTERIOR_WEIGHT
return node_quadrature_weight
def make_trace_node_quadrature_weight(self):
if self.ORDER == 3:
# P3 intrisic quadrature
vertex_weight = 1.0 / 30
edge_weight = 0.075
interior_weight = 0.45
elif self.ORDER == 2:
# Order 1, but optimized quadrature weights for monomials of order <= 4
vertex_weight = 0.022335964126
edge_weight = 0.310997369207
interior_weight = 0.0
else:
vertex_weight = 1.0 / self.NODES_PER_SIDE
edge_weight = 1.0 / self.NODES_PER_SIDE
interior_weight = 1.0 / self.NODES_PER_SIDE
VERTEX_WEIGHT = wp.constant(vertex_weight)
EDGE_WEIGHT = wp.constant(edge_weight)
FACE_INTERIOR_WEIGHT = wp.constant(interior_weight)
@cache.dynamic_func(suffix=self.name)
def trace_node_quadrature_weight(node_index_in_element: int):
node_type, type_index = self.node_type_and_type_index(node_index_in_element)
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
return VERTEX_WEIGHT
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
return EDGE_WEIGHT
return FACE_INTERIOR_WEIGHT
return trace_node_quadrature_weight
def make_element_inner_weight(self):
ORDER = self.ORDER
def element_inner_weight_linear(
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 4:
return 0.0
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
return tet_coords[node_index_in_elt]
def element_inner_weight_quadratic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
# Vertex
return tet_coords[type_index] * (2.0 * tet_coords[type_index] - 1.0)
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
# Edge
if type_index < 3:
c1 = type_index
c2 = (type_index + 1) % 3
else:
c1 = type_index - 3
c2 = 3
return 4.0 * tet_coords[c1] * tet_coords[c2]
return 0.0
def element_inner_weight_cubic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
# Vertex
return (
0.5
* tet_coords[type_index]
* (3.0 * tet_coords[type_index] - 1.0)
* (3.0 * tet_coords[type_index] - 2.0)
)
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
edge_node = type_index - 2 * edge
if edge < 3:
c1 = (edge + edge_node) % 3
c2 = (edge + 1 - edge_node) % 3
elif edge_node == 0:
c1 = edge - 3
c2 = 3
else:
c1 = 3
c2 = edge - 3
return 4.5 * tet_coords[c1] * tet_coords[c2] * (3.0 * tet_coords[c1] - 1.0)
elif node_type == TetrahedronPolynomialShapeFunctions.FACE:
# Interior
c1 = type_index
c2 = (c1 + 1) % 4
c3 = (c1 + 2) % 4
return 27.0 * tet_coords[c1] * tet_coords[c2] * tet_coords[c3]
return 0.0
if ORDER == 1:
return cache.get_func(element_inner_weight_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_cubic, self.name)
return None
def make_element_inner_weight_gradient(self):
ORDER = self.ORDER
def element_inner_weight_gradient_linear(
coords: Coords,
node_index_in_elt: int,
):
if node_index_in_elt < 0 or node_index_in_elt >= 4:
return wp.vec3(0.0)
dw_dc = wp.vec4(0.0)
dw_dc[node_index_in_elt] = 1.0
dw_du = wp.vec3(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0], dw_dc[3] - dw_dc[0])
return dw_du
def element_inner_weight_gradient_quadratic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
dw_dc = wp.vec4(0.0)
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = 4.0 * tet_coords[type_index] - 1.0
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
# Edge
if type_index < 3:
c1 = type_index
c2 = (type_index + 1) % 3
else:
c1 = type_index - 3
c2 = 3
dw_dc[c1] = 4.0 * tet_coords[c2]
dw_dc[c2] = 4.0 * tet_coords[c1]
dw_du = wp.vec3(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0], dw_dc[3] - dw_dc[0])
return dw_du
def element_inner_weight_gradient_cubic(
coords: Coords,
node_index_in_elt: int,
):
node_type, type_index = self.node_type_and_type_index(node_index_in_elt)
tet_coords = wp.vec4(1.0 - coords[0] - coords[1] - coords[2], coords[0], coords[1], coords[2])
dw_dc = wp.vec4(0.0)
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
# Vertex
dw_dc[type_index] = (
0.5 * 27.0 * tet_coords[type_index] * tet_coords[type_index] - 9.0 * tet_coords[type_index] + 1.0
)
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
# Edge
edge = type_index // 2
edge_node = type_index - 2 * edge
if edge < 3:
c1 = (edge + edge_node) % 3
c2 = (edge + 1 - edge_node) % 3
elif edge_node == 0:
c1 = edge - 3
c2 = 3
else:
c1 = 3
c2 = edge - 3
dw_dc[c1] = 4.5 * tet_coords[c2] * (6.0 * tet_coords[c1] - 1.0)
dw_dc[c2] = 4.5 * tet_coords[c1] * (3.0 * tet_coords[c1] - 1.0)
elif node_type == TetrahedronPolynomialShapeFunctions.FACE:
# Interior
c1 = type_index
c2 = (c1 + 1) % 4
c3 = (c1 + 2) % 4
dw_dc[c1] = 27.0 * tet_coords[c2] * tet_coords[c3]
dw_dc[c2] = 27.0 * tet_coords[c3] * tet_coords[c1]
dw_dc[c3] = 27.0 * tet_coords[c1] * tet_coords[c2]
dw_du = wp.vec3(dw_dc[1] - dw_dc[0], dw_dc[2] - dw_dc[0], dw_dc[3] - dw_dc[0])
return dw_du
if ORDER == 1:
return cache.get_func(element_inner_weight_gradient_linear, self.name)
elif ORDER == 2:
return cache.get_func(element_inner_weight_gradient_quadratic, self.name)
elif ORDER == 3:
return cache.get_func(element_inner_weight_gradient_cubic, self.name)
return None
def element_node_tets(self):
if self.ORDER == 1:
element_tets = [[0, 1, 2, 3]]
if self.ORDER == 2:
element_tets = [
[0, 4, 6, 7],
[1, 5, 4, 8],
[2, 6, 5, 9],
[3, 7, 8, 9],
[4, 5, 6, 8],
[8, 7, 9, 6],
[6, 5, 9, 8],
[6, 8, 7, 4],
]
elif self.ORDER == 3:
raise NotImplementedError()
return np.array(element_tets)
class TetrahedronNonConformingPolynomialShapeFunctions:
def __init__(self, degree: int):
self._tet_shape = TetrahedronPolynomialShapeFunctions(degree=degree)
self.ORDER = self._tet_shape.ORDER
self.NODES_PER_ELEMENT = self._tet_shape.NODES_PER_ELEMENT
self.element_node_tets = self._tet_shape.element_node_tets
if self.ORDER == 1:
self._TET_SCALE = 0.4472135955 # so v at 0.5854101966249680 (order 2)
elif self.ORDER == 2:
self._TET_SCALE = 0.6123779296874996 # optimized for low intrinsic quadrature error of deg 4
elif self.ORDER == 3:
self._TET_SCALE = 0.7153564453124999 # optimized for low intrinsic quadrature error of deg 6
else:
self._TET_SCALE = 1.0
self._TET_SCALE = wp.constant(self._TET_SCALE)
self._TET_OFFSET = wp.constant((1.0 - self._TET_SCALE) * wp.vec3(0.25, 0.25, 0.25))
@property
def name(self) -> str:
return f"Tet_P{self.ORDER}d"
def make_node_coords_in_element(self):
node_coords_in_tet = self._tet_shape.make_node_coords_in_element()
TET_SCALE = self._TET_SCALE
TET_OFFSET = self._TET_OFFSET
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
tet_coords = node_coords_in_tet(node_index_in_elt)
return TET_SCALE * tet_coords + TET_OFFSET
return node_coords_in_element
def make_node_quadrature_weight(self):
# Intrinsic quadrature -- precomputed integral of node shape functions
# over element. Order euqla to self.ORDER
if self.ORDER == 2:
vertex_weight = 0.07499641
edge_weight = 0.11666908
face_interior_weight = 0.0
elif self.ORDER == 3:
vertex_weight = 0.03345134
edge_weight = 0.04521887
face_interior_weight = 0.08089206
else:
vertex_weight = 1.0 / self.NODES_PER_ELEMENT
edge_weight = 1.0 / self.NODES_PER_ELEMENT
face_interior_weight = 1.0 / self.NODES_PER_ELEMENT
VERTEX_WEIGHT = wp.constant(vertex_weight)
EDGE_WEIGHT = wp.constant(edge_weight)
FACE_INTERIOR_WEIGHT = wp.constant(face_interior_weight)
@cache.dynamic_func(suffix=self.name)
def node_quadrature_weight(node_index_in_element: int):
node_type, type_index = self._tet_shape.node_type_and_type_index(node_index_in_element)
if node_type == TetrahedronPolynomialShapeFunctions.VERTEX:
return VERTEX_WEIGHT
elif node_type == TetrahedronPolynomialShapeFunctions.EDGE:
return EDGE_WEIGHT
return FACE_INTERIOR_WEIGHT
return node_quadrature_weight
def make_trace_node_quadrature_weight(self):
# Non-conforming, zero measure on sides
@wp.func
def zero(node_index_in_elt: int):
return 0.0
return zero
def make_element_inner_weight(self):
tet_inner_weight = self._tet_shape.make_element_inner_weight()
TET_SCALE = self._TET_SCALE
TET_OFFSET = self._TET_OFFSET
@cache.dynamic_func(suffix=self.name)
def element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
tet_coords = (coords - TET_OFFSET) / TET_SCALE
return tet_inner_weight(tet_coords, node_index_in_elt)
return element_inner_weight
def make_element_inner_weight_gradient(self):
tet_inner_weight_gradient = self._tet_shape.make_element_inner_weight_gradient()
TET_SCALE = self._TET_SCALE
TET_OFFSET = self._TET_OFFSET
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
tet_coords = (coords - TET_OFFSET) / TET_SCALE
grad = tet_inner_weight_gradient(tet_coords, node_index_in_elt)
return grad / TET_SCALE
return element_inner_weight_gradient
| 20,400 | Python | 35.04417 | 117 | 0.531667 |
NVIDIA/warp/warp/fem/space/shape/shape_function.py | import warp as wp
from warp.fem import cache
from warp.fem.geometry import Element
from warp.fem.types import Coords
class ShapeFunction:
"""Interface class for defining scalar-valued shape functions over a single element"""
ORDER: int
"""Maximum degree of the polynomials used to define the shape function"""
NODES_PER_ELEMENT: int
"""Number of shape function nodes"""
@property
def name(self) -> str:
"""Unique name encoding all parameters defining the shape function"""
raise NotImplementedError()
def make_node_coords_in_element(self):
"""Creates a device function returning the coordinates of each node"""
raise NotImplementedError()
def make_node_quadrature_weight(self):
"""Creates a device function returning the weight of each node when use as a quadrature point over the element"""
raise NotImplementedError()
def make_trace_node_quadrature_weight(self):
"""Creates a device function returning the weight of each node when use as a quadrature point over the element boundary"""
raise NotImplementedError()
def make_element_inner_weight(self):
"""Creates a device function returning the value of the shape function associated to a given node at given coordinates"""
raise NotImplementedError()
def make_element_inner_weight_gradient(self):
"""Creates a device function returning the gradient of the shape function associated to a given node at given coordinates"""
raise NotImplementedError()
class ConstantShapeFunction:
"""Shape function that is constant over the element"""
def __init__(self, element: Element, space_dimension: int):
self._element = element
self._dimension = space_dimension
self.ORDER = wp.constant(0)
self.NODES_PER_ELEMENT = wp.constant(1)
coords, _ = element.instantiate_quadrature(order=0, family=None)
self.COORDS = wp.constant(coords[0])
@property
def name(self) -> str:
return f"{self._element.__class__.__name__}{self._dimension}"
def make_node_coords_in_element(self):
COORDS = self.COORDS
@cache.dynamic_func(suffix=self.name)
def node_coords_in_element(
node_index_in_elt: int,
):
return COORDS
return node_coords_in_element
@wp.func
def _node_quadrature_weight(
node_index_in_elt: int,
):
return 1.0
def make_node_quadrature_weight(self):
return ConstantShapeFunction._node_quadrature_weight
def make_trace_node_quadrature_weight(self):
return ConstantShapeFunction._node_quadrature_weight
@wp.func
def _element_inner_weight(
coords: Coords,
node_index_in_elt: int,
):
return 1.0
def make_element_inner_weight(self):
return ConstantShapeFunction._element_inner_weight
def make_element_inner_weight_gradient(self):
grad_type = wp.vec(length=self._dimension, dtype=float)
@cache.dynamic_func(suffix=self.name)
def element_inner_weight_gradient(
coords: Coords,
node_index_in_elt: int,
):
return grad_type(0.0)
return element_inner_weight_gradient
| 3,278 | Python | 30.834951 | 132 | 0.664124 |
NVIDIA/warp/warp/fem/geometry/geometry.py | from typing import Any
import warp as wp
from warp.fem.types import Coords, ElementIndex, Sample
from .element import Element
class Geometry:
"""
Interface class for discrete geometries
A geometry is composed of cells and sides. Sides may be boundary or interior (between cells).
"""
dimension: int = 0
def cell_count(self):
"""Number of cells in the geometry"""
raise NotImplementedError
def side_count(self):
"""Number of sides in the geometry"""
raise NotImplementedError
def boundary_side_count(self):
"""Number of boundary sides (sides with a single neighbour cell) in the geometry"""
raise NotImplementedError
def reference_cell(self) -> Element:
"""Prototypical element for a cell"""
raise NotImplementedError
def reference_side(self) -> Element:
"""Prototypical element for a side"""
raise NotImplementedError
@property
def name(self) -> str:
return self.__class__.__name__
def __str__(self) -> str:
return self.name
CellArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device functions evaluating cell-related quantities"""
SideArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device functions evaluating side-related quantities"""
SideIndexArg: wp.codegen.Struct
"""Structure containing arguments to be passed to device functions for indexing sides"""
@staticmethod
def cell_arg_value(self, device) -> "Geometry.CellArg":
"""Value of the arguments to be passed to cell-related device functions"""
raise NotImplementedError
@staticmethod
def cell_position(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the world position of a cell sample point"""
raise NotImplementedError
@staticmethod
def cell_deformation_gradient(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the transpose of the gradient of world position with respect to reference cell"""
raise NotImplementedError
@staticmethod
def cell_inverse_deformation_gradient(args: "Geometry.CellArg", cell_index: ElementIndex, coords: Coords):
"""Device function returning the matrix right-transforming a gradient w.r.t. cell space to a gradient w.r.t. world space
(i.e. the inverse deformation gradient)
"""
raise NotImplementedError
@staticmethod
def cell_lookup(args: "Geometry.CellArg", pos: Any):
"""Device function returning the cell sample point corresponding to a world position"""
raise NotImplementedError
@staticmethod
def cell_lookup(args: "Geometry.CellArg", pos: Any, guess: "Sample"):
"""Device function returning the cell sample point corresponding to a world position. Can use guess for faster lookup"""
raise NotImplementedError
@staticmethod
def cell_measure(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
raise NotImplementedError
@wp.func
def cell_measure_ratio(args: Any, s: Sample):
return 1.0
@staticmethod
def cell_normal(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the element normal at a sample point.
For elements with the same dimension as the embedding space, this will be zero."""
raise NotImplementedError
@staticmethod
def side_arg_value(self, device) -> "Geometry.SideArg":
"""Value of the arguments to be passed to side-related device functions"""
raise NotImplementedError
@staticmethod
def boundary_side_index(args: "Geometry.SideIndexArg", boundary_side_index: int):
"""Device function returning the side index corresponding to a boundary side"""
raise NotImplementedError
@staticmethod
def side_position(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the side position at a sample point"""
raise NotImplementedError
@staticmethod
def side_deformation_gradient(args: "Geometry.CellArg", s: "Sample"):
"""Device function returning the gradient of world position with respect to reference cell"""
raise NotImplementedError
@staticmethod
def side_inner_inverse_deformation_gradient(args: "Geometry.CellArg", side_index: ElementIndex, coords: Coords):
"""Device function returning the matrix right-transforming a gradient w.r.t. inner cell space to a gradient w.r.t. world space
(i.e. the inverse deformation gradient)
"""
raise NotImplementedError
@staticmethod
def side_outer_inverse_deformation_gradient(args: "Geometry.CellArg", side_index: ElementIndex, coords: Coords):
"""Device function returning the matrix right-transforming a gradient w.r.t. outer cell space to a gradient w.r.t. world space
(i.e. the inverse deformation gradient)
"""
raise NotImplementedError
@staticmethod
def side_measure(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the measure determinant (e.g. volume, area) at a given point"""
raise NotImplementedError
@staticmethod
def side_measure_ratio(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the ratio of the measure of a side to that of its neighbour cells"""
raise NotImplementedError
@staticmethod
def side_normal(args: "Geometry.SideArg", s: "Sample"):
"""Device function returning the element normal at a sample point"""
raise NotImplementedError
@staticmethod
def side_inner_cell_index(args: "Geometry.SideArg", side_index: ElementIndex):
"""Device function returning the inner cell index for a given side"""
raise NotImplementedError
@staticmethod
def side_outer_cell_index(args: "Geometry.SideArg", side_index: ElementIndex):
"""Device function returning the outer cell index for a given side"""
raise NotImplementedError
@staticmethod
def side_inner_cell_coords(args: "Geometry.SideArg", side_index: ElementIndex, side_coords: Coords):
"""Device function returning the coordinates of a point on a side in the inner cell"""
raise NotImplementedError
@staticmethod
def side_outer_cell_coords(args: "Geometry.SideArg", side_index: ElementIndex, side_coords: Coords):
"""Device function returning the coordinates of a point on a side in the outer cell"""
raise NotImplementedError
@staticmethod
def side_from_cell_coords(
args: "Geometry.SideArg",
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
"""Device function converting coordinates on a cell to coordinates on a side, or ``OUTSIDE``"""
raise NotImplementedError
@staticmethod
def side_to_cell_arg(side_arg: "Geometry.SideArg"):
"""Device function converting a side-related argument value to a cell-related argument value, for promoting trace samples to the full space"""
raise NotImplementedError
| 7,260 | Python | 38.248648 | 150 | 0.689532 |
NVIDIA/warp/warp/fem/geometry/quadmesh_2d.py | from typing import Optional
import warp as wp
from warp.fem.cache import (
TemporaryStore,
borrow_temporary,
borrow_temporary_like,
cached_arg_value,
)
from warp.fem.types import OUTSIDE, Coords, ElementIndex, Sample, make_free_sample
from .element import LinearEdge, Square
from .geometry import Geometry
# from .closest_point import project_on_tet_at_origin
@wp.struct
class Quadmesh2DCellArg:
quad_vertex_indices: wp.array2d(dtype=int)
positions: wp.array(dtype=wp.vec2)
# for neighbor cell lookup
vertex_quad_offsets: wp.array(dtype=int)
vertex_quad_indices: wp.array(dtype=int)
@wp.struct
class Quadmesh2DSideArg:
cell_arg: Quadmesh2DCellArg
edge_vertex_indices: wp.array(dtype=wp.vec2i)
edge_quad_indices: wp.array(dtype=wp.vec2i)
class Quadmesh2D(Geometry):
"""Two-dimensional quadrilateral mesh geometry"""
dimension = 2
def __init__(
self, quad_vertex_indices: wp.array, positions: wp.array, temporary_store: Optional[TemporaryStore] = None
):
"""
Constructs a two-dimensional quadrilateral mesh.
Args:
quad_vertex_indices: warp array of shape (num_tris, 4) containing vertex indices for each quad, in counter-clockwise order
positions: warp array of shape (num_vertices, 2) containing 2d position for each vertex
temporary_store: shared pool from which to allocate temporary arrays
"""
self.quad_vertex_indices = quad_vertex_indices
self.positions = positions
self._edge_vertex_indices: wp.array = None
self._edge_quad_indices: wp.array = None
self._vertex_quad_offsets: wp.array = None
self._vertex_quad_indices: wp.array = None
self._build_topology(temporary_store)
def cell_count(self):
return self.quad_vertex_indices.shape[0]
def vertex_count(self):
return self.positions.shape[0]
def side_count(self):
return self._edge_vertex_indices.shape[0]
def boundary_side_count(self):
return self._boundary_edge_indices.shape[0]
def reference_cell(self) -> Square:
return Square()
def reference_side(self) -> LinearEdge:
return LinearEdge()
@property
def edge_quad_indices(self) -> wp.array:
return self._edge_quad_indices
@property
def edge_vertex_indices(self) -> wp.array:
return self._edge_vertex_indices
CellArg = Quadmesh2DCellArg
SideArg = Quadmesh2DSideArg
@wp.struct
class SideIndexArg:
boundary_edge_indices: wp.array(dtype=int)
# Geometry device interface
@cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.quad_vertex_indices = self.quad_vertex_indices.to(device)
args.positions = self.positions.to(device)
args.vertex_quad_offsets = self._vertex_quad_offsets.to(device)
args.vertex_quad_indices = self._vertex_quad_indices.to(device)
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
quad_idx = args.quad_vertex_indices[s.element_index]
w_p = s.element_coords
w_m = Coords(1.0) - s.element_coords
# 0 : m m
# 1 : p m
# 2 : p p
# 3 : m p
return (
w_m[0] * w_m[1] * args.positions[quad_idx[0]]
+ w_p[0] * w_m[1] * args.positions[quad_idx[1]]
+ w_p[0] * w_p[1] * args.positions[quad_idx[2]]
+ w_m[0] * w_p[1] * args.positions[quad_idx[3]]
)
@wp.func
def cell_deformation_gradient(cell_arg: CellArg, s: Sample):
"""Deformation gradient at `coords`"""
quad_idx = cell_arg.quad_vertex_indices[s.element_index]
w_p = s.element_coords
w_m = Coords(1.0) - s.element_coords
return (
wp.outer(cell_arg.positions[quad_idx[0]], wp.vec2(-w_m[1], -w_m[0]))
+ wp.outer(cell_arg.positions[quad_idx[1]], wp.vec2(w_m[1], -w_p[0]))
+ wp.outer(cell_arg.positions[quad_idx[2]], wp.vec2(w_p[1], w_p[0]))
+ wp.outer(cell_arg.positions[quad_idx[3]], wp.vec2(-w_p[1], w_m[0]))
)
@wp.func
def cell_inverse_deformation_gradient(cell_arg: CellArg, s: Sample):
return wp.inverse(Quadmesh2D.cell_deformation_gradient(cell_arg, s))
@wp.func
def cell_measure(args: CellArg, s: Sample):
return wp.abs(wp.determinant(Quadmesh2D.cell_deformation_gradient(args, s)))
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec2(0.0)
@cached_arg_value
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_edge_indices = self._boundary_edge_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_edge_indices[boundary_side_index]
@cached_arg_value
def side_arg_value(self, device) -> CellArg:
args = self.SideArg()
args.cell_arg = self.cell_arg_value(device)
args.edge_vertex_indices = self._edge_vertex_indices.to(device)
args.edge_quad_indices = self._edge_quad_indices.to(device)
return args
@wp.func
def side_position(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
return (1.0 - s.element_coords[0]) * args.cell_arg.positions[edge_idx[0]] + s.element_coords[
0
] * args.cell_arg.positions[edge_idx[1]]
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.cell_arg.positions[edge_idx[0]]
v1 = args.cell_arg.positions[edge_idx[1]]
return v1 - v0
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Quadmesh2D.side_inner_cell_index(args, s.element_index)
cell_coords = Quadmesh2D.side_inner_cell_coords(args, s.element_index, s.element_coords)
return Quadmesh2D.cell_inverse_deformation_gradient(args.cell_arg, make_free_sample(cell_index, cell_coords))
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Quadmesh2D.side_outer_cell_index(args, s.element_index)
cell_coords = Quadmesh2D.side_outer_cell_coords(args, s.element_index, s.element_coords)
return Quadmesh2D.cell_inverse_deformation_gradient(args.cell_arg, make_free_sample(cell_index, cell_coords))
@wp.func
def side_measure(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.cell_arg.positions[edge_idx[0]]
v1 = args.cell_arg.positions[edge_idx[1]]
return wp.length(v1 - v0)
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
inner = Quadmesh2D.side_inner_cell_index(args, s.element_index)
outer = Quadmesh2D.side_outer_cell_index(args, s.element_index)
inner_coords = Quadmesh2D.side_inner_cell_coords(args, s.element_index, s.element_coords)
outer_coords = Quadmesh2D.side_outer_cell_coords(args, s.element_index, s.element_coords)
return Quadmesh2D.side_measure(args, s) / wp.min(
Quadmesh2D.cell_measure(args.cell_arg, make_free_sample(inner, inner_coords)),
Quadmesh2D.cell_measure(args.cell_arg, make_free_sample(outer, outer_coords)),
)
@wp.func
def side_normal(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.cell_arg.positions[edge_idx[0]]
v1 = args.cell_arg.positions[edge_idx[1]]
e = v1 - v0
return wp.normalize(wp.vec2(-e[1], e[0]))
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.edge_quad_indices[side_index][0]
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.edge_quad_indices[side_index][1]
@wp.func
def edge_to_quad_coords(args: SideArg, side_index: ElementIndex, quad_index: ElementIndex, side_coords: Coords):
edge_vidx = args.edge_vertex_indices[side_index]
quad_vidx = args.cell_arg.quad_vertex_indices[quad_index]
vs = edge_vidx[0]
ve = edge_vidx[1]
s = side_coords[0]
if vs == quad_vidx[0]:
return wp.select(ve == quad_vidx[1], Coords(0.0, s, 0.0), Coords(s, 0.0, 0.0))
elif vs == quad_vidx[1]:
return wp.select(ve == quad_vidx[2], Coords(1.0 - s, 0.0, 0.0), Coords(1.0, s, 0.0))
elif vs == quad_vidx[2]:
return wp.select(ve == quad_vidx[3], Coords(1.0, 1.0 - s, 0.0), Coords(1.0 - s, 1.0, 0.0))
return wp.select(ve == quad_vidx[0], Coords(s, 1.0, 0.0), Coords(0.0, 1.0 - s, 0.0))
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
inner_cell_index = Quadmesh2D.side_inner_cell_index(args, side_index)
return Quadmesh2D.edge_to_quad_coords(args, side_index, inner_cell_index, side_coords)
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
outer_cell_index = Quadmesh2D.side_outer_cell_index(args, side_index)
return Quadmesh2D.edge_to_quad_coords(args, side_index, outer_cell_index, side_coords)
@wp.func
def side_from_cell_coords(
args: SideArg,
side_index: ElementIndex,
quad_index: ElementIndex,
quad_coords: Coords,
):
edge_vidx = args.edge_vertex_indices[side_index]
quad_vidx = args.cell_arg.quad_vertex_indices[quad_index]
vs = edge_vidx[0]
ve = edge_vidx[1]
cx = quad_coords[0]
cy = quad_coords[1]
if vs == quad_vidx[0]:
oc = wp.select(ve == quad_vidx[1], cx, cy)
ec = wp.select(ve == quad_vidx[1], cy, cx)
elif vs == quad_vidx[1]:
oc = wp.select(ve == quad_vidx[2], cy, 1.0 - cx)
ec = wp.select(ve == quad_vidx[2], 1.0 - cx, cy)
elif vs == quad_vidx[2]:
oc = wp.select(ve == quad_vidx[3], 1.0 - cx, 1.0 - cy)
ec = wp.select(ve == quad_vidx[3], 1.0 - cy, 1.0 - cx)
else:
oc = wp.select(ve == quad_vidx[0], 1.0 - cy, cx)
ec = wp.select(ve == quad_vidx[0], cx, 1.0 - cy)
return wp.select(oc == 0.0, Coords(OUTSIDE), Coords(ec, 0.0, 0.0))
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
def _build_topology(self, temporary_store: TemporaryStore):
from warp.fem.utils import compress_node_indices, masked_indices
from warp.utils import array_scan
device = self.quad_vertex_indices.device
vertex_quad_offsets, vertex_quad_indices, _, __ = compress_node_indices(
self.vertex_count(), self.quad_vertex_indices, temporary_store=temporary_store
)
self._vertex_quad_offsets = vertex_quad_offsets.detach()
self._vertex_quad_indices = vertex_quad_indices.detach()
vertex_start_edge_count = borrow_temporary(temporary_store, dtype=int, device=device, shape=self.vertex_count())
vertex_start_edge_count.array.zero_()
vertex_start_edge_offsets = borrow_temporary_like(vertex_start_edge_count, temporary_store=temporary_store)
vertex_edge_ends = borrow_temporary(temporary_store, dtype=int, device=device, shape=(4 * self.cell_count()))
vertex_edge_quads = borrow_temporary(
temporary_store, dtype=int, device=device, shape=(4 * self.cell_count(), 2)
)
# Count face edges starting at each vertex
wp.launch(
kernel=Quadmesh2D._count_starting_edges_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.quad_vertex_indices, vertex_start_edge_count.array],
)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_start_edge_offsets.array, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_edge_count = vertex_start_edge_count
wp.launch(
kernel=Quadmesh2D._count_unique_starting_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_quad_offsets,
self._vertex_quad_indices,
self.quad_vertex_indices,
vertex_start_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
vertex_edge_quads.array,
],
)
vertex_unique_edge_offsets = borrow_temporary_like(vertex_start_edge_offsets, temporary_store=temporary_store)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_unique_edge_offsets.array, inclusive=False)
# Get back edge count to host
if device.is_cuda:
edge_count = borrow_temporary(temporary_store, shape=(1,), dtype=int, device="cpu", pinned=True)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(
dest=edge_count.array, src=vertex_unique_edge_offsets.array, src_offset=self.vertex_count() - 1, count=1
)
wp.synchronize_stream(wp.get_stream(device))
edge_count = int(edge_count.array.numpy()[0])
else:
edge_count = int(vertex_unique_edge_offsets.array.numpy()[self.vertex_count() - 1])
self._edge_vertex_indices = wp.empty(shape=(edge_count,), dtype=wp.vec2i, device=device)
self._edge_quad_indices = wp.empty(shape=(edge_count,), dtype=wp.vec2i, device=device)
boundary_mask = borrow_temporary(temporary_store=temporary_store, shape=(edge_count,), dtype=int, device=device)
# Compress edge data
wp.launch(
kernel=Quadmesh2D._compress_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
vertex_start_edge_offsets.array,
vertex_unique_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
vertex_edge_quads.array,
self._edge_vertex_indices,
self._edge_quad_indices,
boundary_mask.array,
],
)
vertex_start_edge_offsets.release()
vertex_unique_edge_offsets.release()
vertex_unique_edge_count.release()
vertex_edge_ends.release()
vertex_edge_quads.release()
# Flip normals if necessary
wp.launch(
kernel=Quadmesh2D._flip_edge_normals,
device=device,
dim=self.side_count(),
inputs=[self._edge_vertex_indices, self._edge_quad_indices, self.quad_vertex_indices, self.positions],
)
boundary_edge_indices, _ = masked_indices(boundary_mask.array, temporary_store=temporary_store)
self._boundary_edge_indices = boundary_edge_indices.detach()
boundary_mask.release()
@wp.kernel
def _count_starting_edges_kernel(
quad_vertex_indices: wp.array2d(dtype=int), vertex_start_edge_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(4):
v0 = quad_vertex_indices[t, k]
v1 = quad_vertex_indices[t, (k + 1) % 4]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
@wp.func
def _find(
needle: int,
values: wp.array(dtype=int),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_edges_kernel(
vertex_quad_offsets: wp.array(dtype=int),
vertex_quad_indices: wp.array(dtype=int),
quad_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_start_edge_count: wp.array(dtype=int),
edge_ends: wp.array(dtype=int),
edge_quads: wp.array2d(dtype=int),
):
v = wp.tid()
edge_beg = vertex_start_edge_offsets[v]
quad_beg = vertex_quad_offsets[v]
quad_end = vertex_quad_offsets[v + 1]
edge_cur = edge_beg
for quad in range(quad_beg, quad_end):
q = vertex_quad_indices[quad]
for k in range(4):
v0 = quad_vertex_indices[q, k]
v1 = quad_vertex_indices[q, (k + 1) % 4]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
# Check if other_v has been seen
seen_idx = Quadmesh2D._find(other_v, edge_ends, edge_beg, edge_cur)
if seen_idx == -1:
edge_ends[edge_cur] = other_v
edge_quads[edge_cur, 0] = q
edge_quads[edge_cur, 1] = q
edge_cur += 1
else:
edge_quads[seen_idx, 1] = q
vertex_start_edge_count[v] = edge_cur - edge_beg
@wp.kernel
def _compress_edges_kernel(
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_count: wp.array(dtype=int),
uncompressed_edge_ends: wp.array(dtype=int),
uncompressed_edge_quads: wp.array2d(dtype=int),
edge_vertex_indices: wp.array(dtype=wp.vec2i),
edge_quad_indices: wp.array(dtype=wp.vec2i),
boundary_mask: wp.array(dtype=int),
):
v = wp.tid()
start_beg = vertex_start_edge_offsets[v]
unique_beg = vertex_unique_edge_offsets[v]
unique_count = vertex_unique_edge_count[v]
for e in range(unique_count):
src_index = start_beg + e
edge_index = unique_beg + e
edge_vertex_indices[edge_index] = wp.vec2i(v, uncompressed_edge_ends[src_index])
q0 = uncompressed_edge_quads[src_index, 0]
q1 = uncompressed_edge_quads[src_index, 1]
edge_quad_indices[edge_index] = wp.vec2i(q0, q1)
if q0 == q1:
boundary_mask[edge_index] = 1
else:
boundary_mask[edge_index] = 0
@wp.kernel
def _flip_edge_normals(
edge_vertex_indices: wp.array(dtype=wp.vec2i),
edge_quad_indices: wp.array(dtype=wp.vec2i),
quad_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec2),
):
e = wp.tid()
tri = edge_quad_indices[e][0]
quad_vidx = quad_vertex_indices[tri]
edge_vidx = edge_vertex_indices[e]
quad_centroid = (
positions[quad_vidx[0]] + positions[quad_vidx[1]] + positions[quad_vidx[2]] + positions[quad_vidx[3]]
) / 4.0
v0 = positions[edge_vidx[0]]
v1 = positions[edge_vidx[1]]
edge_center = 0.5 * (v1 + v0)
edge_vec = v1 - v0
edge_normal = wp.vec2(-edge_vec[1], edge_vec[0])
# if edge normal points toward first triangle centroid, flip indices
if wp.dot(quad_centroid - edge_center, edge_normal) > 0.0:
edge_vertex_indices[e] = wp.vec2i(edge_vidx[1], edge_vidx[0])
| 19,553 | Python | 35.686679 | 134 | 0.602823 |
NVIDIA/warp/warp/fem/geometry/closest_point.py | from typing import Any
import warp as wp
from warp.fem.types import Coords
@wp.func
def project_on_seg_at_origin(q: Any, seg: Any, len_sq: float):
s = wp.clamp(wp.dot(q, seg) / len_sq, 0.0, 1.0)
return wp.length_sq(q - s * seg), s
@wp.func
def project_on_tri_at_origin(q: Any, e1: Any, e2: Any):
e1e1 = wp.dot(e1, e1)
e1e2 = wp.dot(e1, e2)
e2e2 = wp.dot(e2, e2)
det = e1e1 * e2e2 - e1e2 * e1e2
if det > e1e1 * e2e2 * 1.0e-6:
e1p = wp.dot(e1, q)
e2p = wp.dot(e2, q)
s = (e2e2 * e1p - e1e2 * e2p) / det
t = (e1e1 * e2p - e1e2 * e1p) / det
if s >= 0.0 and t >= 0.0 and s + t <= 1.0:
# point inside triangle (distance can be non-zero in 3D case)
return wp.length_sq(q - s * e1 - t * e2), Coords(1.0 - s - t, s, t)
d1, s1 = project_on_seg_at_origin(q, e1, e1e1)
d2, s2 = project_on_seg_at_origin(q, e2, e2e2)
d12, s12 = project_on_seg_at_origin(q - e1, e2 - e1, wp.length_sq(e2 - e1))
if d1 <= d2:
if d1 <= d12:
return d1, Coords(1.0 - s1, s1, 0.0)
elif d2 <= d12:
return d2, Coords(1.0 - s2, 0.0, s2)
return d12, Coords(0.0, 1.0 - s12, s12)
@wp.func
def project_on_tet_at_origin(q: wp.vec3, e1: wp.vec3, e2: wp.vec3, e3: wp.vec3):
mat = wp.inverse(wp.mat33(e1, e2, e3))
coords = mat * q
if wp.min(coords) >= 0.0 and coords[0] + coords[1] + coords[2] <= 1.0:
return 0.0, coords
# Not inside tet, compare closest point on each tri
d12, s12 = project_on_tri_at_origin(q, e1, e2)
d23, s23 = project_on_tri_at_origin(q, e2, e3)
d31, s31 = project_on_tri_at_origin(q, e3, e1)
d123, s123 = project_on_tri_at_origin(q - e1, e2 - e1, e3 - e1)
dmin = wp.min(wp.vec4(d12, d23, d31, d123))
if dmin == d12:
return dmin, Coords(s12[1], s12[2], 0.0)
elif dmin == d23:
return dmin, Coords(0.0, s23[1], s23[2])
elif dmin == d31:
return dmin, Coords(s31[2], 0.0, s31[1])
else:
return dmin, s123
| 2,028 | Python | 27.985714 | 80 | 0.54783 |
NVIDIA/warp/warp/fem/geometry/partition.py | from typing import Any
import warp as wp
from warp.fem.cache import TemporaryStore, borrow_temporary, cached_arg_value
from warp.fem.types import NULL_ELEMENT_INDEX, ElementIndex
from warp.fem.utils import masked_indices
from .geometry import Geometry
wp.set_module_options({"enable_backward": False})
class GeometryPartition:
"""Base class for geometry partitions, i.e. subset of cells and sides"""
class CellArg:
pass
class SideArg:
pass
def __init__(self, geometry: Geometry):
self.geometry = geometry
def cell_count(self) -> int:
"""Number of cells that are 'owned' by this partition"""
raise NotImplementedError()
def side_count(self) -> int:
"""Number of sides that are 'owned' by this partition"""
raise NotImplementedError()
def boundary_side_count(self) -> int:
"""Number of geo-boundary sides that are 'owned' by this partition"""
raise NotImplementedError()
def frontier_side_count(self) -> int:
"""Number of sides with neighbors owned by this and another partition"""
raise NotImplementedError()
@property
def name(self) -> str:
return f"{self.geometry.name}_{self.__class__.__name__}"
def __str__(self) -> str:
return self.name
def cell_arg_value(self, device):
raise NotImplementedError()
def side_arg_value(self, device):
raise NotImplementedError()
@staticmethod
def cell_index(args: CellArg, partition_cell_index: int):
"""Index in the geometry of a partition cell"""
raise NotImplementedError()
@staticmethod
def partition_cell_index(args: CellArg, cell_index: int):
"""Index of a geometry cell in the partition (or ``NULL_ELEMENT_INDEX``)"""
raise NotImplementedError()
@staticmethod
def side_index(args: SideArg, partition_side_index: int):
"""Partition side to side index"""
raise NotImplementedError()
@staticmethod
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
raise NotImplementedError()
@staticmethod
def frontier_side_index(args: SideArg, frontier_side_index: int):
"""Frontier side to side index"""
raise NotImplementedError()
class WholeGeometryPartition(GeometryPartition):
"""Trivial (NOP) partition"""
def __init__(
self,
geometry: Geometry,
):
super().__init__(geometry)
self.SideArg = geometry.SideIndexArg
self.side_arg_value = geometry.side_index_arg_value
self.cell_index = WholeGeometryPartition._identity_element_index
self.partition_cell_index = WholeGeometryPartition._identity_element_index
self.side_index = WholeGeometryPartition._identity_element_index
self.boundary_side_index = geometry.boundary_side_index
self.frontier_side_index = WholeGeometryPartition._identity_element_index
def __eq__(self, other: GeometryPartition) -> bool:
# Ensures that two whole partition instances of the same geometry are considered equal
return isinstance(other, WholeGeometryPartition) and self.geometry == other.geometry
def cell_count(self) -> int:
return self.geometry.cell_count()
def side_count(self) -> int:
return self.geometry.side_count()
def boundary_side_count(self) -> int:
return self.geometry.boundary_side_count()
def frontier_side_count(self) -> int:
return 0
@wp.struct
class CellArg:
pass
def cell_arg_value(self, device):
arg = WholeGeometryPartition.CellArg()
return arg
@wp.func
def _identity_element_index(args: Any, idx: ElementIndex):
return idx
@property
def name(self) -> str:
return self.geometry.name
class CellBasedGeometryPartition(GeometryPartition):
"""Geometry partition based on a subset of cells. Interior, boundary and frontier sides are automatically categorized."""
def __init__(
self,
geometry: Geometry,
device=None,
):
super().__init__(geometry)
@wp.struct
class SideArg:
partition_side_indices: wp.array(dtype=int)
boundary_side_indices: wp.array(dtype=int)
frontier_side_indices: wp.array(dtype=int)
def side_count(self) -> int:
return self._partition_side_indices.array.shape[0]
def boundary_side_count(self) -> int:
return self._boundary_side_indices.array.shape[0]
def frontier_side_count(self) -> int:
return self._frontier_side_indices.array.shape[0]
@cached_arg_value
def side_arg_value(self, device):
arg = LinearGeometryPartition.SideArg()
arg.partition_side_indices = self._partition_side_indices.array.to(device)
arg.boundary_side_indices = self._boundary_side_indices.array.to(device)
arg.frontier_side_indices = self._frontier_side_indices.array.to(device)
return arg
@wp.func
def side_index(args: SideArg, partition_side_index: int):
"""partition side to side index"""
return args.partition_side_indices[partition_side_index]
@wp.func
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_side_indices[boundary_side_index]
@wp.func
def frontier_side_index(args: SideArg, frontier_side_index: int):
"""Frontier side to side index"""
return args.frontier_side_indices[frontier_side_index]
def compute_side_indices_from_cells(
self, cell_arg_value: Any, cell_inclusion_test_func: wp.Function, device, temporary_store: TemporaryStore = None
):
from warp.fem import cache
cell_arg_type = next(iter(cell_inclusion_test_func.input_types.values()))
@cache.dynamic_kernel(suffix=f"{self.geometry.name}_{cell_inclusion_test_func.key}")
def count_sides(
geo_arg: self.geometry.SideArg,
cell_arg_value: cell_arg_type,
partition_side_mask: wp.array(dtype=int),
boundary_side_mask: wp.array(dtype=int),
frontier_side_mask: wp.array(dtype=int),
):
side_index = wp.tid()
inner_cell_index = self.geometry.side_inner_cell_index(geo_arg, side_index)
outer_cell_index = self.geometry.side_outer_cell_index(geo_arg, side_index)
inner_in = cell_inclusion_test_func(cell_arg_value, inner_cell_index)
outer_in = cell_inclusion_test_func(cell_arg_value, outer_cell_index)
if inner_in:
# Inner neighbor in partition; count as partition side
partition_side_mask[side_index] = 1
# Inner and outer element as the same -- this is a boundary side
if inner_cell_index == outer_cell_index:
boundary_side_mask[side_index] = 1
if inner_in != outer_in:
# Exactly one neighbor in partition; count as frontier side
frontier_side_mask[side_index] = 1
partition_side_mask = borrow_temporary(
temporary_store,
shape=(self.geometry.side_count(),),
dtype=int,
device=device,
)
boundary_side_mask = borrow_temporary(
temporary_store,
shape=(self.geometry.side_count(),),
dtype=int,
device=device,
)
frontier_side_mask = borrow_temporary(
temporary_store,
shape=(self.geometry.side_count(),),
dtype=int,
device=device,
)
partition_side_mask.array.zero_()
boundary_side_mask.array.zero_()
frontier_side_mask.array.zero_()
wp.launch(
dim=partition_side_mask.array.shape[0],
kernel=count_sides,
inputs=[
self.geometry.side_arg_value(device),
cell_arg_value,
partition_side_mask.array,
boundary_side_mask.array,
frontier_side_mask.array,
],
device=device,
)
# Convert counts to indices
self._partition_side_indices, _ = masked_indices(partition_side_mask.array, temporary_store=temporary_store)
self._boundary_side_indices, _ = masked_indices(boundary_side_mask.array, temporary_store=temporary_store)
self._frontier_side_indices, _ = masked_indices(frontier_side_mask.array, temporary_store=temporary_store)
partition_side_mask.release()
boundary_side_mask.release()
frontier_side_mask.release()
class LinearGeometryPartition(CellBasedGeometryPartition):
def __init__(
self,
geometry: Geometry,
partition_rank: int,
partition_count: int,
device=None,
temporary_store: TemporaryStore = None,
):
"""Creates a geometry partition by uniformly partionning cell indices
Args:
geometry: the geometry to partition
partition_rank: the index of the partition being created
partition_count: the number of partitions that will be created over the geometry
device: Warp device on which to perform and store computations
"""
super().__init__(geometry)
total_cell_count = geometry.cell_count()
cells_per_partition = (total_cell_count + partition_count - 1) // partition_count
self.cell_begin = cells_per_partition * partition_rank
self.cell_end = min(self.cell_begin + cells_per_partition, total_cell_count)
super().compute_side_indices_from_cells(
self.cell_arg_value(device),
LinearGeometryPartition._cell_inclusion_test,
device,
temporary_store=temporary_store,
)
def cell_count(self) -> int:
return self.cell_end - self.cell_begin
@wp.struct
class CellArg:
cell_begin: int
cell_end: int
def cell_arg_value(self, device):
arg = LinearGeometryPartition.CellArg()
arg.cell_begin = self.cell_begin
arg.cell_end = self.cell_end
return arg
@wp.func
def cell_index(args: CellArg, partition_cell_index: int):
"""Partition cell to cell index"""
return args.cell_begin + partition_cell_index
@wp.func
def partition_cell_index(args: CellArg, cell_index: int):
"""Partition cell to cell index"""
if cell_index > args.cell_end:
return NULL_ELEMENT_INDEX
partition_cell_index = cell_index - args.cell_begin
if partition_cell_index < 0:
return NULL_ELEMENT_INDEX
return partition_cell_index
@wp.func
def _cell_inclusion_test(arg: CellArg, cell_index: int):
return cell_index >= arg.cell_begin and cell_index < arg.cell_end
class ExplicitGeometryPartition(CellBasedGeometryPartition):
def __init__(self, geometry: Geometry, cell_mask: "wp.array(dtype=int)", temporary_store: TemporaryStore = None):
"""Creates a geometry partition by uniformly partionning cell indices
Args:
geometry: the geometry to partition
cell_mask: warp array of length ``geometry.cell_count()`` indicating which cells are selected. Array values must be either ``1`` (selected) or ``0`` (not selected).
"""
super().__init__(geometry)
self._cell_mask = cell_mask
self._cells, self._partition_cells = masked_indices(self._cell_mask, temporary_store=temporary_store)
super().compute_side_indices_from_cells(
self._cell_mask,
ExplicitGeometryPartition._cell_inclusion_test,
self._cell_mask.device,
temporary_store=temporary_store,
)
def cell_count(self) -> int:
return self._cells.array.shape[0]
@wp.struct
class CellArg:
cell_index: wp.array(dtype=int)
partition_cell_index: wp.array(dtype=int)
@cached_arg_value
def cell_arg_value(self, device):
arg = ExplicitGeometryPartition.CellArg()
arg.cell_index = self._cells.array.to(device)
arg.partition_cell_index = self._partition_cells.array.to(device)
return arg
@wp.func
def cell_index(args: CellArg, partition_cell_index: int):
return args.cell_index[partition_cell_index]
@wp.func
def partition_cell_index(args: CellArg, cell_index: int):
return args.partition_cell_index[cell_index]
@wp.func
def _cell_inclusion_test(mask: wp.array(dtype=int), cell_index: int):
return mask[cell_index] > 0
| 12,705 | Python | 32.882667 | 176 | 0.632271 |
NVIDIA/warp/warp/fem/geometry/grid_3d.py | from typing import Any, Optional
import warp as wp
from warp.fem.cache import cached_arg_value
from warp.fem.types import OUTSIDE, Coords, ElementIndex, Sample, make_free_sample
from .element import Cube, Square
from .geometry import Geometry
@wp.struct
class Grid3DCellArg:
res: wp.vec3i
cell_size: wp.vec3
origin: wp.vec3
_mat32 = wp.mat(shape=(3, 2), dtype=float)
class Grid3D(Geometry):
"""Three-dimensional regular grid geometry"""
dimension = 3
Permutation = wp.types.matrix(shape=(3, 3), dtype=int)
LOC_TO_WORLD = wp.constant(Permutation(0, 1, 2, 1, 2, 0, 2, 0, 1))
WORLD_TO_LOC = wp.constant(Permutation(0, 1, 2, 2, 0, 1, 1, 2, 0))
def __init__(self, res: wp.vec3i, bounds_lo: Optional[wp.vec3] = None, bounds_hi: Optional[wp.vec3] = None):
"""Constructs a dense 3D grid
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
"""
if bounds_lo is None:
bounds_lo = wp.vec3(0.0)
if bounds_hi is None:
bounds_hi = wp.vec3(1.0)
self.bounds_lo = bounds_lo
self.bounds_hi = bounds_hi
self._res = res
@property
def extents(self) -> wp.vec3:
# Avoid using native sub due to higher over of calling builtins from Python
return wp.vec3(
self.bounds_hi[0] - self.bounds_lo[0],
self.bounds_hi[1] - self.bounds_lo[1],
self.bounds_hi[2] - self.bounds_lo[2],
)
@property
def cell_size(self) -> wp.vec3:
ex = self.extents
return wp.vec3(
ex[0] / self.res[0],
ex[1] / self.res[1],
ex[2] / self.res[2],
)
def cell_count(self):
return self.res[0] * self.res[1] * self.res[2]
def vertex_count(self):
return (self.res[0] + 1) * (self.res[1] + 1) * (self.res[2] + 1)
def side_count(self):
return (
(self.res[0] + 1) * (self.res[1]) * (self.res[2])
+ (self.res[0]) * (self.res[1] + 1) * (self.res[2])
+ (self.res[0]) * (self.res[1]) * (self.res[2] + 1)
)
def edge_count(self):
return (
(self.res[0] + 1) * (self.res[1] + 1) * (self.res[2])
+ (self.res[0]) * (self.res[1] + 1) * (self.res[2] + 1)
+ (self.res[0] + 1) * (self.res[1]) * (self.res[2] + 1)
)
def boundary_side_count(self):
return 2 * (self.res[1]) * (self.res[2]) + (self.res[0]) * 2 * (self.res[2]) + (self.res[0]) * (self.res[1]) * 2
def reference_cell(self) -> Cube:
return Cube()
def reference_side(self) -> Square:
return Square()
@property
def res(self):
return self._res
@property
def origin(self):
return self.bounds_lo
@property
def strides(self):
return wp.vec3i(self.res[1] * self.res[2], self.res[2], 1)
# Utility device functions
CellArg = Grid3DCellArg
Cell = wp.vec3i
@wp.func
def _to_3d_index(strides: wp.vec2i, index: int):
x = index // strides[0]
y = (index - strides[0] * x) // strides[1]
z = index - strides[0] * x - strides[1] * y
return wp.vec3i(x, y, z)
@wp.func
def _from_3d_index(strides: wp.vec2i, index: wp.vec3i):
return strides[0] * index[0] + strides[1] * index[1] + index[2]
@wp.func
def cell_index(res: wp.vec3i, cell: Cell):
strides = wp.vec2i(res[1] * res[2], res[2])
return Grid3D._from_3d_index(strides, cell)
@wp.func
def get_cell(res: wp.vec3i, cell_index: ElementIndex):
strides = wp.vec2i(res[1] * res[2], res[2])
return Grid3D._to_3d_index(strides, cell_index)
@wp.struct
class Side:
axis: int # normal
origin: wp.vec3i # index of vertex at corner (0,0,0)
@wp.struct
class SideArg:
cell_count: int
axis_offsets: wp.vec3i
cell_arg: Grid3DCellArg
SideIndexArg = SideArg
@wp.func
def _world_to_local(axis: int, vec: Any):
return type(vec)(
vec[Grid3D.LOC_TO_WORLD[axis, 0]],
vec[Grid3D.LOC_TO_WORLD[axis, 1]],
vec[Grid3D.LOC_TO_WORLD[axis, 2]],
)
@wp.func
def _local_to_world(axis: int, vec: Any):
return type(vec)(
vec[Grid3D.WORLD_TO_LOC[axis, 0]],
vec[Grid3D.WORLD_TO_LOC[axis, 1]],
vec[Grid3D.WORLD_TO_LOC[axis, 2]],
)
@wp.func
def side_index(arg: SideArg, side: Side):
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
if side.origin[0] == arg.cell_arg.res[alt_axis]:
# Upper-boundary side
longitude = side.origin[1]
latitude = side.origin[2]
latitude_res = arg.cell_arg.res[Grid3D.LOC_TO_WORLD[side.axis, 2]]
lat_long = latitude_res * longitude + latitude
return 3 * arg.cell_count + arg.axis_offsets[side.axis] + lat_long
cell_index = Grid3D.cell_index(arg.cell_arg.res, Grid3D._local_to_world(side.axis, side.origin))
return side.axis * arg.cell_count + cell_index
@wp.func
def get_side(arg: SideArg, side_index: ElementIndex):
if side_index < 3 * arg.cell_count:
axis = side_index // arg.cell_count
cell_index = side_index - axis * arg.cell_count
origin = Grid3D._world_to_local(axis, Grid3D.get_cell(arg.cell_arg.res, cell_index))
return Grid3D.Side(axis, origin)
axis_side_index = side_index - 3 * arg.cell_count
if axis_side_index < arg.axis_offsets[1]:
axis = 0
elif axis_side_index < arg.axis_offsets[2]:
axis = 1
else:
axis = 2
altitude = arg.cell_arg.res[Grid3D.LOC_TO_WORLD[axis, 0]]
lat_long = axis_side_index - arg.axis_offsets[axis]
latitude_res = arg.cell_arg.res[Grid3D.LOC_TO_WORLD[axis, 2]]
longitude = lat_long // latitude_res
latitude = lat_long - longitude * latitude_res
origin_loc = wp.vec3i(altitude, longitude, latitude)
return Grid3D.Side(axis, origin_loc)
# Geometry device interface
@cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.res = self.res
args.origin = self.bounds_lo
args.cell_size = self.cell_size
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
cell = Grid3D.get_cell(args.res, s.element_index)
return (
wp.vec3(
(float(cell[0]) + s.element_coords[0]) * args.cell_size[0],
(float(cell[1]) + s.element_coords[1]) * args.cell_size[1],
(float(cell[2]) + s.element_coords[2]) * args.cell_size[2],
)
+ args.origin
)
@wp.func
def cell_deformation_gradient(args: CellArg, s: Sample):
return wp.diag(args.cell_size)
@wp.func
def cell_inverse_deformation_gradient(args: CellArg, s: Sample):
return wp.diag(wp.cw_div(wp.vec3(1.0), args.cell_size))
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3):
loc_pos = wp.cw_div(pos - args.origin, args.cell_size)
x = wp.clamp(loc_pos[0], 0.0, float(args.res[0]))
y = wp.clamp(loc_pos[1], 0.0, float(args.res[1]))
z = wp.clamp(loc_pos[2], 0.0, float(args.res[2]))
x_cell = wp.min(wp.floor(x), float(args.res[0]) - 1.0)
y_cell = wp.min(wp.floor(y), float(args.res[1]) - 1.0)
z_cell = wp.min(wp.floor(z), float(args.res[2]) - 1.0)
coords = Coords(x - x_cell, y - y_cell, z - z_cell)
cell_index = Grid3D.cell_index(args.res, Grid3D.Cell(int(x_cell), int(y_cell), int(z_cell)))
return make_free_sample(cell_index, coords)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3, guess: Sample):
return Grid3D.cell_lookup(args, pos)
@wp.func
def cell_measure(args: CellArg, s: Sample):
return args.cell_size[0] * args.cell_size[1] * args.cell_size[2]
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec3(0.0)
@cached_arg_value
def side_arg_value(self, device) -> SideArg:
args = self.SideArg()
axis_dims = wp.vec3i(
self.res[1] * self.res[2],
self.res[2] * self.res[0],
self.res[0] * self.res[1],
)
args.axis_offsets = wp.vec3i(
0,
axis_dims[0],
axis_dims[0] + axis_dims[1],
)
args.cell_count = self.cell_count()
args.cell_arg = self.cell_arg_value(device)
return args
def side_index_arg_value(self, device) -> SideIndexArg:
return self.side_arg_value(device)
@wp.func
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
axis_side_index = boundary_side_index // 2
border = boundary_side_index - 2 * axis_side_index
if axis_side_index < args.axis_offsets[1]:
axis = 0
elif axis_side_index < args.axis_offsets[2]:
axis = 1
else:
axis = 2
lat_long = axis_side_index - args.axis_offsets[axis]
latitude_res = args.cell_arg.res[Grid3D.LOC_TO_WORLD[axis, 2]]
longitude = lat_long // latitude_res
latitude = lat_long - longitude * latitude_res
altitude = border * args.cell_arg.res[axis]
side = Grid3D.Side(axis, wp.vec3i(altitude, longitude, latitude))
return Grid3D.side_index(args, side)
@wp.func
def side_position(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
coord0 = wp.select(side.origin[0] == 0, s.element_coords[0], 1.0 - s.element_coords[0])
local_pos = wp.vec3(
float(side.origin[0]),
float(side.origin[1]) + coord0,
float(side.origin[2]) + s.element_coords[1],
)
pos = args.cell_arg.origin + wp.cw_mul(Grid3D._local_to_world(side.axis, local_pos), args.cell_arg.cell_size)
return pos
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
sign = wp.select(side.origin[0] == 0, 1.0, -1.0)
return _mat32(
wp.cw_mul(Grid3D._local_to_world(side.axis, wp.vec3(0.0, sign, 0.0)), args.cell_arg.cell_size),
wp.cw_mul(Grid3D._local_to_world(side.axis, wp.vec3(0.0, 0.0, 1.0)), args.cell_arg.cell_size),
)
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
return Grid3D.cell_inverse_deformation_gradient(args.cell_arg, s)
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
return Grid3D.cell_inverse_deformation_gradient(args.cell_arg, s)
@wp.func
def side_measure(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
long_axis = Grid3D.LOC_TO_WORLD[side.axis, 1]
lat_axis = Grid3D.LOC_TO_WORLD[side.axis, 2]
return args.cell_arg.cell_size[long_axis] * args.cell_arg.cell_size[lat_axis]
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
return 1.0 / args.cell_arg.cell_size[alt_axis]
@wp.func
def side_normal(args: SideArg, s: Sample):
side = Grid3D.get_side(args, s.element_index)
sign = wp.select(side.origin[0] == 0, 1.0, -1.0)
local_n = wp.vec3(sign, 0.0, 0.0)
return Grid3D._local_to_world(side.axis, local_n)
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid3D.get_side(arg, side_index)
inner_alt = wp.select(side.origin[0] == 0, side.origin[0] - 1, 0)
inner_origin = wp.vec3i(inner_alt, side.origin[1], side.origin[2])
cell = Grid3D._local_to_world(side.axis, inner_origin)
return Grid3D.cell_index(arg.cell_arg.res, cell)
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid3D.get_side(arg, side_index)
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
outer_alt = wp.select(
side.origin[0] == arg.cell_arg.res[alt_axis], side.origin[0], arg.cell_arg.res[alt_axis] - 1
)
outer_origin = wp.vec3i(outer_alt, side.origin[1], side.origin[2])
cell = Grid3D._local_to_world(side.axis, outer_origin)
return Grid3D.cell_index(arg.cell_arg.res, cell)
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
side = Grid3D.get_side(args, side_index)
inner_alt = wp.select(side.origin[0] == 0, 1.0, 0.0)
side_coord0 = wp.select(side.origin[0] == 0, side_coords[0], 1.0 - side_coords[0])
return Grid3D._local_to_world(side.axis, wp.vec3(inner_alt, side_coord0, side_coords[1]))
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
side = Grid3D.get_side(args, side_index)
alt_axis = Grid3D.LOC_TO_WORLD[side.axis, 0]
outer_alt = wp.select(side.origin[0] == args.cell_arg.res[alt_axis], 0.0, 1.0)
side_coord0 = wp.select(side.origin[0] == 0, side_coords[0], 1.0 - side_coords[0])
return Grid3D._local_to_world(side.axis, wp.vec3(outer_alt, side_coord0, side_coords[1]))
@wp.func
def side_from_cell_coords(
args: SideArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
side = Grid3D.get_side(args, side_index)
cell = Grid3D.get_cell(args.cell_arg.res, element_index)
if float(side.origin[0] - cell[side.axis]) == element_coords[side.axis]:
long_axis = Grid3D.LOC_TO_WORLD[side.axis, 1]
lat_axis = Grid3D.LOC_TO_WORLD[side.axis, 2]
long_coord = element_coords[long_axis]
long_coord = wp.select(side.origin[0] == 0, long_coord, 1.0 - long_coord)
return Coords(long_coord, element_coords[lat_axis], 0.0)
return Coords(OUTSIDE)
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
| 14,466 | Python | 32.02968 | 120 | 0.579358 |
NVIDIA/warp/warp/fem/geometry/tetmesh.py | from typing import Optional
import warp as wp
from warp.fem.cache import (
TemporaryStore,
borrow_temporary,
borrow_temporary_like,
cached_arg_value,
)
from warp.fem.types import (
NULL_ELEMENT_INDEX,
OUTSIDE,
Coords,
ElementIndex,
Sample,
make_free_sample,
)
from .closest_point import project_on_tet_at_origin
from .element import Tetrahedron, Triangle
from .geometry import Geometry
@wp.struct
class TetmeshCellArg:
tet_vertex_indices: wp.array2d(dtype=int)
positions: wp.array(dtype=wp.vec3)
# for neighbor cell lookup
vertex_tet_offsets: wp.array(dtype=int)
vertex_tet_indices: wp.array(dtype=int)
# for transforming reference gradient
deformation_gradients: wp.array(dtype=wp.mat33f)
@wp.struct
class TetmeshSideArg:
cell_arg: TetmeshCellArg
face_vertex_indices: wp.array(dtype=wp.vec3i)
face_tet_indices: wp.array(dtype=wp.vec2i)
_mat32 = wp.mat(shape=(3, 2), dtype=float)
class Tetmesh(Geometry):
"""Tetrahedral mesh geometry"""
dimension = 3
def __init__(
self, tet_vertex_indices: wp.array, positions: wp.array, temporary_store: Optional[TemporaryStore] = None
):
"""
Constructs a tetrahedral mesh.
Args:
tet_vertex_indices: warp array of shape (num_tets, 4) containing vertex indices for each tet
positions: warp array of shape (num_vertices, 3) containing 3d position for each vertex
temporary_store: shared pool from which to allocate temporary arrays
"""
self.tet_vertex_indices = tet_vertex_indices
self.positions = positions
self._face_vertex_indices: wp.array = None
self._face_tet_indices: wp.array = None
self._vertex_tet_offsets: wp.array = None
self._vertex_tet_indices: wp.array = None
self._tet_edge_indices: wp.array = None
self._edge_count = 0
self._build_topology(temporary_store)
self._deformation_gradients: wp.array = None
self._compute_deformation_gradients()
def cell_count(self):
return self.tet_vertex_indices.shape[0]
def vertex_count(self):
return self.positions.shape[0]
def side_count(self):
return self._face_vertex_indices.shape[0]
def edge_count(self):
if self._tet_edge_indices is None:
self._compute_tet_edges()
return self._edge_count
def boundary_side_count(self):
return self._boundary_face_indices.shape[0]
def reference_cell(self) -> Tetrahedron:
return Tetrahedron()
def reference_side(self) -> Triangle:
return Triangle()
@property
def tet_edge_indices(self) -> wp.array:
if self._tet_edge_indices is None:
self._compute_tet_edges()
return self._tet_edge_indices
@property
def face_tet_indices(self) -> wp.array:
return self._face_tet_indices
@property
def face_vertex_indices(self) -> wp.array:
return self._face_vertex_indices
CellArg = TetmeshCellArg
SideArg = TetmeshSideArg
@wp.struct
class SideIndexArg:
boundary_face_indices: wp.array(dtype=int)
# Geometry device interface
@cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.tet_vertex_indices = self.tet_vertex_indices.to(device)
args.positions = self.positions.to(device)
args.vertex_tet_offsets = self._vertex_tet_offsets.to(device)
args.vertex_tet_indices = self._vertex_tet_indices.to(device)
args.deformation_gradients = self._deformation_gradients.to(device)
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
tet_idx = args.tet_vertex_indices[s.element_index]
w0 = 1.0 - s.element_coords[0] - s.element_coords[1] - s.element_coords[2]
return (
w0 * args.positions[tet_idx[0]]
+ s.element_coords[0] * args.positions[tet_idx[1]]
+ s.element_coords[1] * args.positions[tet_idx[2]]
+ s.element_coords[2] * args.positions[tet_idx[3]]
)
@wp.func
def cell_deformation_gradient(args: CellArg, s: Sample):
return args.deformation_gradients[s.element_index]
@wp.func
def cell_inverse_deformation_gradient(args: CellArg, s: Sample):
return wp.inverse(args.deformation_gradients[s.element_index])
@wp.func
def _project_on_tet(args: CellArg, pos: wp.vec3, tet_index: int):
p0 = args.positions[args.tet_vertex_indices[tet_index, 0]]
q = pos - p0
e1 = args.positions[args.tet_vertex_indices[tet_index, 1]] - p0
e2 = args.positions[args.tet_vertex_indices[tet_index, 2]] - p0
e3 = args.positions[args.tet_vertex_indices[tet_index, 3]] - p0
dist, coords = project_on_tet_at_origin(q, e1, e2, e3)
return dist, coords
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3, guess: Sample):
closest_tet = int(NULL_ELEMENT_INDEX)
closest_coords = Coords(OUTSIDE)
closest_dist = float(1.0e8)
for v in range(4):
vtx = args.tet_vertex_indices[guess.element_index, v]
tet_beg = args.vertex_tet_offsets[vtx]
tet_end = args.vertex_tet_offsets[vtx + 1]
for t in range(tet_beg, tet_end):
tet = args.vertex_tet_indices[t]
dist, coords = Tetmesh._project_on_tet(args, pos, tet)
if dist <= closest_dist:
closest_dist = dist
closest_tet = tet
closest_coords = coords
return make_free_sample(closest_tet, closest_coords)
@wp.func
def cell_measure(args: CellArg, s: Sample):
return wp.abs(wp.determinant(args.deformation_gradients[s.element_index])) / 6.0
@wp.func
def cell_measure_ratio(args: CellArg, s: Sample):
return 1.0
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec3(0.0)
@cached_arg_value
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_face_indices = self._boundary_face_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_face_indices[boundary_side_index]
@cached_arg_value
def side_arg_value(self, device) -> CellArg:
args = self.SideArg()
args.cell_arg = self.cell_arg_value(device)
args.face_vertex_indices = self._face_vertex_indices.to(device)
args.face_tet_indices = self._face_tet_indices.to(device)
return args
@wp.func
def side_position(args: SideArg, s: Sample):
face_idx = args.face_vertex_indices[s.element_index]
return (
s.element_coords[0] * args.cell_arg.positions[face_idx[0]]
+ s.element_coords[1] * args.cell_arg.positions[face_idx[1]]
+ s.element_coords[2] * args.cell_arg.positions[face_idx[2]]
)
@wp.func
def _side_vecs(args: SideArg, side_index: ElementIndex):
face_idx = args.face_vertex_indices[side_index]
v0 = args.cell_arg.positions[face_idx[0]]
v1 = args.cell_arg.positions[face_idx[1]]
v2 = args.cell_arg.positions[face_idx[2]]
return v1 - v0, v2 - v0
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
e1, e2 = Tetmesh._side_vecs(args, s.element_index)
return _mat32(e1, e2)
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Tetmesh.side_inner_cell_index(args, s.element_index)
return wp.inverse(args.cell_arg.deformation_gradients[cell_index])
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Tetmesh.side_outer_cell_index(args, s.element_index)
return wp.inverse(args.cell_arg.deformation_gradients[cell_index])
@wp.func
def side_measure(args: SideArg, s: Sample):
e1, e2 = Tetmesh._side_vecs(args, s.element_index)
return 0.5 * wp.length(wp.cross(e1, e2))
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
inner = Tetmesh.side_inner_cell_index(args, s.element_index)
outer = Tetmesh.side_outer_cell_index(args, s.element_index)
return Tetmesh.side_measure(args, s) / wp.min(
Tetmesh.cell_measure(args.cell_arg, make_free_sample(inner, Coords())),
Tetmesh.cell_measure(args.cell_arg, make_free_sample(outer, Coords())),
)
@wp.func
def side_normal(args: SideArg, s: Sample):
e1, e2 = Tetmesh._side_vecs(args, s.element_index)
return wp.normalize(wp.cross(e1, e2))
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.face_tet_indices[side_index][0]
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.face_tet_indices[side_index][1]
@wp.func
def face_to_tet_coords(args: SideArg, side_index: ElementIndex, tet_index: ElementIndex, side_coords: Coords):
fvi = args.face_vertex_indices[side_index]
tv1 = args.cell_arg.tet_vertex_indices[tet_index, 1]
tv2 = args.cell_arg.tet_vertex_indices[tet_index, 2]
tv3 = args.cell_arg.tet_vertex_indices[tet_index, 3]
c1 = float(0.0)
c2 = float(0.0)
c3 = float(0.0)
for k in range(3):
if tv1 == fvi[k]:
c1 = side_coords[k]
elif tv2 == fvi[k]:
c2 = side_coords[k]
elif tv3 == fvi[k]:
c3 = side_coords[k]
return Coords(c1, c2, c3)
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
inner_cell_index = Tetmesh.side_inner_cell_index(args, side_index)
return Tetmesh.face_to_tet_coords(args, side_index, inner_cell_index, side_coords)
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
outer_cell_index = Tetmesh.side_outer_cell_index(args, side_index)
return Tetmesh.face_to_tet_coords(args, side_index, outer_cell_index, side_coords)
@wp.func
def side_from_cell_coords(args: SideArg, side_index: ElementIndex, tet_index: ElementIndex, tet_coords: Coords):
fvi = args.face_vertex_indices[side_index]
tv1 = args.cell_arg.tet_vertex_indices[tet_index, 1]
tv2 = args.cell_arg.tet_vertex_indices[tet_index, 2]
tv3 = args.cell_arg.tet_vertex_indices[tet_index, 3]
if tv1 == fvi[0]:
c0 = tet_coords[0]
elif tv2 == fvi[0]:
c0 = tet_coords[1]
elif tv3 == fvi[0]:
c0 = tet_coords[2]
else:
c0 = 1.0 - tet_coords[0] - tet_coords[1] - tet_coords[2]
if tv1 == fvi[1]:
c1 = tet_coords[0]
elif tv2 == fvi[1]:
c1 = tet_coords[1]
elif tv3 == fvi[1]:
c1 = tet_coords[2]
else:
c1 = 1.0 - tet_coords[0] - tet_coords[1] - tet_coords[2]
if tv1 == fvi[2]:
c2 = tet_coords[0]
elif tv2 == fvi[2]:
c2 = tet_coords[1]
elif tv3 == fvi[2]:
c2 = tet_coords[2]
else:
c2 = 1.0 - tet_coords[0] - tet_coords[1] - tet_coords[2]
return wp.select(c0 + c1 + c2 > 0.999, Coords(OUTSIDE), Coords(c0, c1, c2))
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
def _build_topology(self, temporary_store: TemporaryStore):
from warp.fem.utils import compress_node_indices, masked_indices
from warp.utils import array_scan
device = self.tet_vertex_indices.device
vertex_tet_offsets, vertex_tet_indices, _, __ = compress_node_indices(
self.vertex_count(), self.tet_vertex_indices, temporary_store=temporary_store
)
self._vertex_tet_offsets = vertex_tet_offsets.detach()
self._vertex_tet_indices = vertex_tet_indices.detach()
vertex_start_face_count = borrow_temporary(temporary_store, dtype=int, device=device, shape=self.vertex_count())
vertex_start_face_count.array.zero_()
vertex_start_face_offsets = borrow_temporary_like(vertex_start_face_count, temporary_store=temporary_store)
vertex_face_other_vs = borrow_temporary(
temporary_store, dtype=wp.vec2i, device=device, shape=(4 * self.cell_count())
)
vertex_face_tets = borrow_temporary(temporary_store, dtype=int, device=device, shape=(4 * self.cell_count(), 2))
# Count face edges starting at each vertex
wp.launch(
kernel=Tetmesh._count_starting_faces_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.tet_vertex_indices, vertex_start_face_count.array],
)
array_scan(in_array=vertex_start_face_count.array, out_array=vertex_start_face_offsets.array, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_face_count = vertex_start_face_count
wp.launch(
kernel=Tetmesh._count_unique_starting_faces_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_tet_offsets,
self._vertex_tet_indices,
self.tet_vertex_indices,
vertex_start_face_offsets.array,
vertex_unique_face_count.array,
vertex_face_other_vs.array,
vertex_face_tets.array,
],
)
vertex_unique_face_offsets = borrow_temporary_like(vertex_start_face_offsets, temporary_store=temporary_store)
array_scan(in_array=vertex_start_face_count.array, out_array=vertex_unique_face_offsets.array, inclusive=False)
# Get back edge count to host
if device.is_cuda:
face_count = borrow_temporary(temporary_store, shape=(1,), dtype=int, device="cpu", pinned=True)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(
dest=face_count.array, src=vertex_unique_face_offsets.array, src_offset=self.vertex_count() - 1, count=1
)
wp.synchronize_stream(wp.get_stream(device))
face_count = int(face_count.array.numpy()[0])
else:
face_count = int(vertex_unique_face_offsets.array.numpy()[self.vertex_count() - 1])
self._face_vertex_indices = wp.empty(shape=(face_count,), dtype=wp.vec3i, device=device)
self._face_tet_indices = wp.empty(shape=(face_count,), dtype=wp.vec2i, device=device)
boundary_mask = borrow_temporary(temporary_store, shape=(face_count,), dtype=int, device=device)
# Compress edge data
wp.launch(
kernel=Tetmesh._compress_faces_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
vertex_start_face_offsets.array,
vertex_unique_face_offsets.array,
vertex_unique_face_count.array,
vertex_face_other_vs.array,
vertex_face_tets.array,
self._face_vertex_indices,
self._face_tet_indices,
boundary_mask.array,
],
)
vertex_start_face_offsets.release()
vertex_unique_face_offsets.release()
vertex_unique_face_count.release()
vertex_face_other_vs.release()
vertex_face_tets.release()
# Flip normals if necessary
wp.launch(
kernel=Tetmesh._flip_face_normals,
device=device,
dim=self.side_count(),
inputs=[self._face_vertex_indices, self._face_tet_indices, self.tet_vertex_indices, self.positions],
)
boundary_face_indices, _ = masked_indices(boundary_mask.array)
self._boundary_face_indices = boundary_face_indices.detach()
def _compute_tet_edges(self, temporary_store: Optional[TemporaryStore] = None):
from warp.utils import array_scan
device = self.tet_vertex_indices.device
vertex_start_edge_count = borrow_temporary(temporary_store, dtype=int, device=device, shape=self.vertex_count())
vertex_start_edge_count.array.zero_()
vertex_start_edge_offsets = borrow_temporary_like(vertex_start_edge_count, temporary_store=temporary_store)
vertex_edge_ends = borrow_temporary(temporary_store, dtype=int, device=device, shape=(6 * self.cell_count()))
# Count face edges starting at each vertex
wp.launch(
kernel=Tetmesh._count_starting_edges_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.tet_vertex_indices, vertex_start_edge_count.array],
)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_start_edge_offsets.array, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_edge_count = vertex_start_edge_count
wp.launch(
kernel=Tetmesh._count_unique_starting_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_tet_offsets,
self._vertex_tet_indices,
self.tet_vertex_indices,
vertex_start_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
],
)
vertex_unique_edge_offsets = borrow_temporary_like(
vertex_start_edge_offsets.array, temporary_store=temporary_store
)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_unique_edge_offsets.array, inclusive=False)
# Get back edge count to host
if device.is_cuda:
edge_count = borrow_temporary(temporary_store, shape=(1,), dtype=int, device="cpu", pinned=True)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(
dest=edge_count.array,
src=vertex_unique_edge_offsets.array,
src_offset=self.vertex_count() - 1,
count=1,
)
wp.synchronize_stream(wp.get_stream(device))
self._edge_count = int(edge_count.array.numpy()[0])
else:
self._edge_count = int(vertex_unique_edge_offsets.array.numpy()[self.vertex_count() - 1])
self._tet_edge_indices = wp.empty(
dtype=int, device=self.tet_vertex_indices.device, shape=(self.cell_count(), 6)
)
# Compress edge data
wp.launch(
kernel=Tetmesh._compress_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_tet_offsets,
self._vertex_tet_indices,
self.tet_vertex_indices,
vertex_start_edge_offsets.array,
vertex_unique_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
self._tet_edge_indices,
],
)
vertex_start_edge_offsets.release()
vertex_unique_edge_offsets.release()
vertex_unique_edge_count.release()
vertex_edge_ends.release()
def _compute_deformation_gradients(self):
self._deformation_gradients = wp.empty(dtype=wp.mat33f, device=self.positions.device, shape=(self.cell_count()))
wp.launch(
kernel=Tetmesh._compute_deformation_gradients_kernel,
dim=self._deformation_gradients.shape,
device=self._deformation_gradients.device,
inputs=[self.tet_vertex_indices, self.positions, self._deformation_gradients],
)
@wp.kernel
def _count_starting_faces_kernel(
tet_vertex_indices: wp.array2d(dtype=int), vertex_start_face_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(4):
vi = wp.vec3i(
tet_vertex_indices[t, k], tet_vertex_indices[t, (k + 1) % 4], tet_vertex_indices[t, (k + 2) % 4]
)
vm = wp.min(vi)
for i in range(3):
if vm == vi[i]:
wp.atomic_add(vertex_start_face_count, vm, 1)
@wp.func
def _find_face(
needle: wp.vec2i,
values: wp.array(dtype=wp.vec2i),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_faces_kernel(
vertex_tet_offsets: wp.array(dtype=int),
vertex_tet_indices: wp.array(dtype=int),
tet_vertex_indices: wp.array2d(dtype=int),
vertex_start_face_offsets: wp.array(dtype=int),
vertex_start_face_count: wp.array(dtype=int),
face_other_vs: wp.array(dtype=wp.vec2i),
face_tets: wp.array2d(dtype=int),
):
v = wp.tid()
face_beg = vertex_start_face_offsets[v]
tet_beg = vertex_tet_offsets[v]
tet_end = vertex_tet_offsets[v + 1]
face_cur = face_beg
for tet in range(tet_beg, tet_end):
t = vertex_tet_indices[tet]
for k in range(4):
vi = wp.vec3i(
tet_vertex_indices[t, k], tet_vertex_indices[t, (k + 1) % 4], tet_vertex_indices[t, (k + 2) % 4]
)
min_v = wp.min(vi)
if v == min_v:
max_v = wp.max(vi)
mid_v = vi[0] + vi[1] + vi[2] - min_v - max_v
other_v = wp.vec2i(mid_v, max_v)
# Check if other_v has been seen
seen_idx = Tetmesh._find_face(other_v, face_other_vs, face_beg, face_cur)
if seen_idx == -1:
face_other_vs[face_cur] = other_v
face_tets[face_cur, 0] = t
face_tets[face_cur, 1] = t
face_cur += 1
else:
face_tets[seen_idx, 1] = t
vertex_start_face_count[v] = face_cur - face_beg
@wp.kernel
def _compress_faces_kernel(
vertex_start_face_offsets: wp.array(dtype=int),
vertex_unique_face_offsets: wp.array(dtype=int),
vertex_unique_face_count: wp.array(dtype=int),
uncompressed_face_other_vs: wp.array(dtype=wp.vec2i),
uncompressed_face_tets: wp.array2d(dtype=int),
face_vertex_indices: wp.array(dtype=wp.vec3i),
face_tet_indices: wp.array(dtype=wp.vec2i),
boundary_mask: wp.array(dtype=int),
):
v = wp.tid()
start_beg = vertex_start_face_offsets[v]
unique_beg = vertex_unique_face_offsets[v]
unique_count = vertex_unique_face_count[v]
for f in range(unique_count):
src_index = start_beg + f
face_index = unique_beg + f
face_vertex_indices[face_index] = wp.vec3i(
v,
uncompressed_face_other_vs[src_index][0],
uncompressed_face_other_vs[src_index][1],
)
t0 = uncompressed_face_tets[src_index, 0]
t1 = uncompressed_face_tets[src_index, 1]
face_tet_indices[face_index] = wp.vec2i(t0, t1)
if t0 == t1:
boundary_mask[face_index] = 1
else:
boundary_mask[face_index] = 0
@wp.kernel
def _flip_face_normals(
face_vertex_indices: wp.array(dtype=wp.vec3i),
face_tet_indices: wp.array(dtype=wp.vec2i),
tet_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec3),
):
e = wp.tid()
tet = face_tet_indices[e][0]
tet_vidx = tet_vertex_indices[tet]
face_vidx = face_vertex_indices[e]
tet_centroid = (
positions[tet_vidx[0]] + positions[tet_vidx[1]] + positions[tet_vidx[2]] + positions[tet_vidx[3]]
) / 4.0
v0 = positions[face_vidx[0]]
v1 = positions[face_vidx[1]]
v2 = positions[face_vidx[2]]
face_center = (v1 + v0 + v2) / 3.0
face_normal = wp.cross(v1 - v0, v2 - v0)
# if face normal points toward first tet centroid, flip indices
if wp.dot(tet_centroid - face_center, face_normal) > 0.0:
face_vertex_indices[e] = wp.vec3i(face_vidx[0], face_vidx[2], face_vidx[1])
@wp.kernel
def _count_starting_edges_kernel(
tri_vertex_indices: wp.array2d(dtype=int), vertex_start_edge_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, (k + 1) % 3]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, 3]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
@wp.func
def _find_edge(
needle: int,
values: wp.array(dtype=int),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_edges_kernel(
vertex_tet_offsets: wp.array(dtype=int),
vertex_tet_indices: wp.array(dtype=int),
tet_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_start_edge_count: wp.array(dtype=int),
edge_ends: wp.array(dtype=int),
):
v = wp.tid()
edge_beg = vertex_start_edge_offsets[v]
tet_beg = vertex_tet_offsets[v]
tet_end = vertex_tet_offsets[v + 1]
edge_cur = edge_beg
for tet in range(tet_beg, tet_end):
t = vertex_tet_indices[tet]
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, (k + 1) % 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
if Tetmesh._find_edge(other_v, edge_ends, edge_beg, edge_cur) == -1:
edge_ends[edge_cur] = other_v
edge_cur += 1
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
if Tetmesh._find_edge(other_v, edge_ends, edge_beg, edge_cur) == -1:
edge_ends[edge_cur] = other_v
edge_cur += 1
vertex_start_edge_count[v] = edge_cur - edge_beg
@wp.kernel
def _compress_edges_kernel(
vertex_tet_offsets: wp.array(dtype=int),
vertex_tet_indices: wp.array(dtype=int),
tet_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_count: wp.array(dtype=int),
uncompressed_edge_ends: wp.array(dtype=int),
tet_edge_indices: wp.array2d(dtype=int),
):
v = wp.tid()
uncompressed_beg = vertex_start_edge_offsets[v]
unique_beg = vertex_unique_edge_offsets[v]
unique_count = vertex_unique_edge_count[v]
tet_beg = vertex_tet_offsets[v]
tet_end = vertex_tet_offsets[v + 1]
for tet in range(tet_beg, tet_end):
t = vertex_tet_indices[tet]
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, (k + 1) % 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
edge_id = (
Tetmesh._find_edge(
other_v, uncompressed_edge_ends, uncompressed_beg, uncompressed_beg + unique_count
)
- uncompressed_beg
+ unique_beg
)
tet_edge_indices[t][k] = edge_id
for k in range(3):
v0 = tet_vertex_indices[t, k]
v1 = tet_vertex_indices[t, 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
edge_id = (
Tetmesh._find_edge(
other_v, uncompressed_edge_ends, uncompressed_beg, uncompressed_beg + unique_count
)
- uncompressed_beg
+ unique_beg
)
tet_edge_indices[t][k + 3] = edge_id
@wp.kernel
def _compute_deformation_gradients_kernel(
tet_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec3f),
transforms: wp.array(dtype=wp.mat33f),
):
t = wp.tid()
p0 = positions[tet_vertex_indices[t, 0]]
p1 = positions[tet_vertex_indices[t, 1]]
p2 = positions[tet_vertex_indices[t, 2]]
p3 = positions[tet_vertex_indices[t, 3]]
e1 = p1 - p0
e2 = p2 - p0
e3 = p3 - p0
transforms[t] = wp.mat33(e1, e2, e3)
| 29,806 | Python | 34.442331 | 120 | 0.575018 |
NVIDIA/warp/warp/fem/geometry/hexmesh.py | from typing import Optional
import warp as wp
from warp.fem.cache import (
TemporaryStore,
borrow_temporary,
borrow_temporary_like,
cached_arg_value,
)
from warp.fem.types import OUTSIDE, Coords, ElementIndex, Sample, make_free_sample
from .element import Cube, Square
from .geometry import Geometry
@wp.struct
class HexmeshCellArg:
hex_vertex_indices: wp.array2d(dtype=int)
positions: wp.array(dtype=wp.vec3)
# for neighbor cell lookup
vertex_hex_offsets: wp.array(dtype=int)
vertex_hex_indices: wp.array(dtype=int)
@wp.struct
class HexmeshSideArg:
cell_arg: HexmeshCellArg
face_vertex_indices: wp.array(dtype=wp.vec4i)
face_hex_indices: wp.array(dtype=wp.vec2i)
face_hex_face_orientation: wp.array(dtype=wp.vec4i)
_mat32 = wp.mat(shape=(3, 2), dtype=float)
FACE_VERTEX_INDICES = wp.constant(
wp.mat(shape=(6, 4), dtype=int)(
[
[0, 4, 7, 3], # x = 0
[1, 2, 6, 5], # x = 1
[0, 1, 5, 4], # y = 0
[3, 7, 6, 2], # y = 1
[0, 3, 2, 1], # z = 0
[4, 5, 6, 7], # z = 1
]
)
)
EDGE_VERTEX_INDICES = wp.constant(
wp.mat(shape=(12, 2), dtype=int)(
[
[0, 1],
[1, 2],
[3, 2],
[0, 3],
[4, 5],
[5, 6],
[7, 6],
[4, 7],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
]
)
)
# orthogal transform for face coordinates given first vertex + winding
# (two rows per entry)
FACE_ORIENTATION = [
[1, 0], # FV: 0, det: +
[0, 1],
[0, 1], # FV: 0, det: -
[1, 0],
[0, -1], # FV: 1, det: +
[1, 0],
[-1, 0], # FV: 1, det: -
[0, 1],
[-1, 0], # FV: 2, det: +
[0, -1],
[0, -1], # FV: 2, det: -
[-1, 0],
[0, 1], # FV: 3, det: +
[-1, 0],
[1, 0], # FV: 3, det: -
[0, -1],
]
FACE_TRANSLATION = [
[0, 0],
[1, 0],
[1, 1],
[0, 1],
]
# local face coordinate system
_FACE_COORD_INDICES = wp.constant(
wp.mat(shape=(6, 4), dtype=int)(
[
[2, 1, 0, 0], # 0: z y -x
[1, 2, 0, 1], # 1: y z x-1
[0, 2, 1, 0], # 2: x z -y
[2, 0, 1, 1], # 3: z x y-1
[1, 0, 2, 0], # 4: y x -z
[0, 1, 2, 1], # 5: x y z-1
]
)
)
_FACE_ORIENTATION_F = wp.constant(wp.mat(shape=(16, 2), dtype=float)(FACE_ORIENTATION))
_FACE_TRANSLATION_F = wp.constant(wp.mat(shape=(4, 2), dtype=float)(FACE_TRANSLATION))
class Hexmesh(Geometry):
"""Hexahedral mesh geometry"""
dimension = 3
def __init__(
self, hex_vertex_indices: wp.array, positions: wp.array, temporary_store: Optional[TemporaryStore] = None
):
"""
Constructs a tetrahedral mesh.
Args:
hex_vertex_indices: warp array of shape (num_hexes, 8) containing vertex indices for each hex
following standard ordering (bottom face vertices in counter-clockwise order, then similarly for upper face)
positions: warp array of shape (num_vertices, 3) containing 3d position for each vertex
temporary_store: shared pool from which to allocate temporary arrays
"""
self.hex_vertex_indices = hex_vertex_indices
self.positions = positions
self._face_vertex_indices: wp.array = None
self._face_hex_indices: wp.array = None
self._face_hex_face_orientation: wp.array = None
self._vertex_hex_offsets: wp.array = None
self._vertex_hex_indices: wp.array = None
self._hex_edge_indices: wp.array = None
self._edge_count = 0
self._build_topology(temporary_store)
def cell_count(self):
return self.hex_vertex_indices.shape[0]
def vertex_count(self):
return self.positions.shape[0]
def side_count(self):
return self._face_vertex_indices.shape[0]
def edge_count(self):
if self._hex_edge_indices is None:
self._compute_hex_edges()
return self._edge_count
def boundary_side_count(self):
return self._boundary_face_indices.shape[0]
def reference_cell(self) -> Cube:
return Cube()
def reference_side(self) -> Square:
return Square()
@property
def hex_edge_indices(self) -> wp.array:
if self._hex_edge_indices is None:
self._compute_hex_edges()
return self._hex_edge_indices
@property
def face_hex_indices(self) -> wp.array:
return self._face_hex_indices
@property
def face_vertex_indices(self) -> wp.array:
return self._face_vertex_indices
CellArg = HexmeshCellArg
SideArg = HexmeshSideArg
@wp.struct
class SideIndexArg:
boundary_face_indices: wp.array(dtype=int)
# Geometry device interface
@cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.hex_vertex_indices = self.hex_vertex_indices.to(device)
args.positions = self.positions.to(device)
args.vertex_hex_offsets = self._vertex_hex_offsets.to(device)
args.vertex_hex_indices = self._vertex_hex_indices.to(device)
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
hex_idx = args.hex_vertex_indices[s.element_index]
w_p = s.element_coords
w_m = Coords(1.0) - s.element_coords
# 0 : m m m
# 1 : p m m
# 2 : p p m
# 3 : m p m
# 4 : m m p
# 5 : p m p
# 6 : p p p
# 7 : m p p
return (
w_m[0] * w_m[1] * w_m[2] * args.positions[hex_idx[0]]
+ w_p[0] * w_m[1] * w_m[2] * args.positions[hex_idx[1]]
+ w_p[0] * w_p[1] * w_m[2] * args.positions[hex_idx[2]]
+ w_m[0] * w_p[1] * w_m[2] * args.positions[hex_idx[3]]
+ w_m[0] * w_m[1] * w_p[2] * args.positions[hex_idx[4]]
+ w_p[0] * w_m[1] * w_p[2] * args.positions[hex_idx[5]]
+ w_p[0] * w_p[1] * w_p[2] * args.positions[hex_idx[6]]
+ w_m[0] * w_p[1] * w_p[2] * args.positions[hex_idx[7]]
)
@wp.func
def cell_deformation_gradient(cell_arg: CellArg, s: Sample):
"""Deformation gradient at `coords`"""
"""Transposed deformation gradient at `coords`"""
hex_idx = cell_arg.hex_vertex_indices[s.element_index]
w_p = s.element_coords
w_m = Coords(1.0) - s.element_coords
return (
wp.outer(cell_arg.positions[hex_idx[0]], wp.vec3(-w_m[1] * w_m[2], -w_m[0] * w_m[2], -w_m[0] * w_m[1]))
+ wp.outer(cell_arg.positions[hex_idx[1]], wp.vec3(w_m[1] * w_m[2], -w_p[0] * w_m[2], -w_p[0] * w_m[1]))
+ wp.outer(cell_arg.positions[hex_idx[2]], wp.vec3(w_p[1] * w_m[2], w_p[0] * w_m[2], -w_p[0] * w_p[1]))
+ wp.outer(cell_arg.positions[hex_idx[3]], wp.vec3(-w_p[1] * w_m[2], w_m[0] * w_m[2], -w_m[0] * w_p[1]))
+ wp.outer(cell_arg.positions[hex_idx[4]], wp.vec3(-w_m[1] * w_p[2], -w_m[0] * w_p[2], w_m[0] * w_m[1]))
+ wp.outer(cell_arg.positions[hex_idx[5]], wp.vec3(w_m[1] * w_p[2], -w_p[0] * w_p[2], w_p[0] * w_m[1]))
+ wp.outer(cell_arg.positions[hex_idx[6]], wp.vec3(w_p[1] * w_p[2], w_p[0] * w_p[2], w_p[0] * w_p[1]))
+ wp.outer(cell_arg.positions[hex_idx[7]], wp.vec3(-w_p[1] * w_p[2], w_m[0] * w_p[2], w_m[0] * w_p[1]))
)
@wp.func
def cell_inverse_deformation_gradient(cell_arg: CellArg, s: Sample):
return wp.inverse(Hexmesh.cell_deformation_gradient(cell_arg, s))
@wp.func
def cell_measure(args: CellArg, s: Sample):
return wp.abs(wp.determinant(Hexmesh.cell_deformation_gradient(args, s)))
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec3(0.0)
@cached_arg_value
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_face_indices = self._boundary_face_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_face_indices[boundary_side_index]
@cached_arg_value
def side_arg_value(self, device) -> CellArg:
args = self.SideArg()
args.cell_arg = self.cell_arg_value(device)
args.face_vertex_indices = self._face_vertex_indices.to(device)
args.face_hex_indices = self._face_hex_indices.to(device)
args.face_hex_face_orientation = self._face_hex_face_orientation.to(device)
return args
@wp.func
def side_position(args: SideArg, s: Sample):
face_idx = args.face_vertex_indices[s.element_index]
w_p = s.element_coords
w_m = Coords(1.0) - s.element_coords
return (
w_m[0] * w_m[1] * args.cell_arg.positions[face_idx[0]]
+ w_p[0] * w_m[1] * args.cell_arg.positions[face_idx[1]]
+ w_p[0] * w_p[1] * args.cell_arg.positions[face_idx[2]]
+ w_m[0] * w_p[1] * args.cell_arg.positions[face_idx[3]]
)
@wp.func
def _side_deformation_vecs(args: SideArg, side_index: ElementIndex, coords: Coords):
face_idx = args.face_vertex_indices[side_index]
p0 = args.cell_arg.positions[face_idx[0]]
p1 = args.cell_arg.positions[face_idx[1]]
p2 = args.cell_arg.positions[face_idx[2]]
p3 = args.cell_arg.positions[face_idx[3]]
w_p = coords
w_m = Coords(1.0) - coords
v1 = w_m[1] * (p1 - p0) + w_p[1] * (p2 - p3)
v2 = w_p[0] * (p2 - p1) + w_m[0] * (p3 - p0)
return v1, v2
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
"""Transposed side deformation gradient at `coords`"""
v1, v2 = Hexmesh._side_deformation_vecs(args, s.element_index, s.element_coords)
return _mat32(v1, v2)
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Hexmesh.side_inner_cell_index(args, s.element_index)
cell_coords = Hexmesh.side_inner_cell_coords(args, s.element_index, s.element_coords)
return Hexmesh.cell_inverse_deformation_gradient(args.cell_arg, make_free_sample(cell_index, cell_coords))
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Hexmesh.side_outer_cell_index(args, s.element_index)
cell_coords = Hexmesh.side_outer_cell_coords(args, s.element_index, s.element_coords)
return Hexmesh.cell_inverse_deformation_gradient(args.cell_arg, make_free_sample(cell_index, cell_coords))
@wp.func
def side_measure(args: SideArg, s: Sample):
v1, v2 = Hexmesh._side_deformation_vecs(args, s.element_index, s.element_coords)
return wp.length(wp.cross(v1, v2))
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
inner = Hexmesh.side_inner_cell_index(args, s.element_index)
outer = Hexmesh.side_outer_cell_index(args, s.element_index)
inner_coords = Hexmesh.side_inner_cell_coords(args, s.element_index, s.element_coords)
outer_coords = Hexmesh.side_outer_cell_coords(args, s.element_index, s.element_coords)
return Hexmesh.side_measure(args, s) / wp.min(
Hexmesh.cell_measure(args.cell_arg, make_free_sample(inner, inner_coords)),
Hexmesh.cell_measure(args.cell_arg, make_free_sample(outer, outer_coords)),
)
@wp.func
def side_normal(args: SideArg, s: Sample):
v1, v2 = Hexmesh._side_deformation_vecs(args, s.element_index, s.element_coords)
return wp.normalize(wp.cross(v1, v2))
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.face_hex_indices[side_index][0]
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.face_hex_indices[side_index][1]
@wp.func
def _hex_local_face_coords(hex_coords: Coords, face_index: int):
# Coordinatex in local face coordinates system
# Sign of last coordinate (out of face)
face_coords = wp.vec2(
hex_coords[_FACE_COORD_INDICES[face_index, 0]], hex_coords[_FACE_COORD_INDICES[face_index, 1]]
)
normal_coord = hex_coords[_FACE_COORD_INDICES[face_index, 2]]
normal_coord = wp.select(_FACE_COORD_INDICES[face_index, 3] == 0, normal_coord - 1.0, -normal_coord)
return face_coords, normal_coord
@wp.func
def _local_face_hex_coords(face_coords: wp.vec2, face_index: int):
# Coordinates in hex from local face coordinates system
hex_coords = Coords()
hex_coords[_FACE_COORD_INDICES[face_index, 0]] = face_coords[0]
hex_coords[_FACE_COORD_INDICES[face_index, 1]] = face_coords[1]
hex_coords[_FACE_COORD_INDICES[face_index, 2]] = wp.select(_FACE_COORD_INDICES[face_index, 3] == 0, 1.0, 0.0)
return hex_coords
@wp.func
def _local_from_oriented_face_coords(ori: int, oriented_coords: Coords):
fv = ori // 2
return (oriented_coords[0] - _FACE_TRANSLATION_F[fv, 0]) * _FACE_ORIENTATION_F[2 * ori] + (
oriented_coords[1] - _FACE_TRANSLATION_F[fv, 1]
) * _FACE_ORIENTATION_F[2 * ori + 1]
@wp.func
def _local_to_oriented_face_coords(ori: int, coords: wp.vec2):
fv = ori // 2
return Coords(
wp.dot(_FACE_ORIENTATION_F[2 * ori], coords) + _FACE_TRANSLATION_F[fv, 0],
wp.dot(_FACE_ORIENTATION_F[2 * ori + 1], coords) + _FACE_TRANSLATION_F[fv, 1],
0.0,
)
@wp.func
def face_to_hex_coords(local_face_index: int, face_orientation: int, side_coords: Coords):
local_coords = Hexmesh._local_from_oriented_face_coords(face_orientation, side_coords)
return Hexmesh._local_face_hex_coords(local_coords, local_face_index)
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
local_face_index = args.face_hex_face_orientation[side_index][0]
face_orientation = args.face_hex_face_orientation[side_index][1]
return Hexmesh.face_to_hex_coords(local_face_index, face_orientation, side_coords)
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
local_face_index = args.face_hex_face_orientation[side_index][2]
face_orientation = args.face_hex_face_orientation[side_index][3]
return Hexmesh.face_to_hex_coords(local_face_index, face_orientation, side_coords)
@wp.func
def side_from_cell_coords(args: SideArg, side_index: ElementIndex, hex_index: ElementIndex, hex_coords: Coords):
if Hexmesh.side_inner_cell_index(args, side_index) == hex_index:
local_face_index = args.face_hex_face_orientation[side_index][0]
face_orientation = args.face_hex_face_orientation[side_index][1]
else:
local_face_index = args.face_hex_face_orientation[side_index][2]
face_orientation = args.face_hex_face_orientation[side_index][3]
face_coords, normal_coord = Hexmesh._hex_local_face_coords(hex_coords, local_face_index)
return wp.select(
normal_coord == 0.0, Coords(OUTSIDE), Hexmesh._local_to_oriented_face_coords(face_orientation, face_coords)
)
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
def _build_topology(self, temporary_store: TemporaryStore):
from warp.fem.utils import compress_node_indices, masked_indices
from warp.utils import array_scan
device = self.hex_vertex_indices.device
vertex_hex_offsets, vertex_hex_indices, _, __ = compress_node_indices(
self.vertex_count(), self.hex_vertex_indices, temporary_store=temporary_store
)
self._vertex_hex_offsets = vertex_hex_offsets.detach()
self._vertex_hex_indices = vertex_hex_indices.detach()
vertex_start_face_count = borrow_temporary(temporary_store, dtype=int, device=device, shape=self.vertex_count())
vertex_start_face_count.array.zero_()
vertex_start_face_offsets = borrow_temporary_like(vertex_start_face_count, temporary_store=temporary_store)
vertex_face_other_vs = borrow_temporary(
temporary_store, dtype=wp.vec3i, device=device, shape=(8 * self.cell_count())
)
vertex_face_hexes = borrow_temporary(
temporary_store, dtype=int, device=device, shape=(8 * self.cell_count(), 2)
)
# Count face edges starting at each vertex
wp.launch(
kernel=Hexmesh._count_starting_faces_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.hex_vertex_indices, vertex_start_face_count.array],
)
array_scan(in_array=vertex_start_face_count.array, out_array=vertex_start_face_offsets.array, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_face_count = vertex_start_face_count
wp.launch(
kernel=Hexmesh._count_unique_starting_faces_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_hex_offsets,
self._vertex_hex_indices,
self.hex_vertex_indices,
vertex_start_face_offsets.array,
vertex_unique_face_count.array,
vertex_face_other_vs.array,
vertex_face_hexes.array,
],
)
vertex_unique_face_offsets = borrow_temporary_like(vertex_start_face_offsets, temporary_store=temporary_store)
array_scan(in_array=vertex_start_face_count.array, out_array=vertex_unique_face_offsets.array, inclusive=False)
# Get back edge count to host
if device.is_cuda:
face_count = borrow_temporary(temporary_store, shape=(1,), dtype=int, device="cpu", pinned=True)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(
dest=face_count.array, src=vertex_unique_face_offsets.array, src_offset=self.vertex_count() - 1, count=1
)
wp.synchronize_stream(wp.get_stream(device))
face_count = int(face_count.array.numpy()[0])
else:
face_count = int(vertex_unique_face_offsets.array.numpy()[self.vertex_count() - 1])
self._face_vertex_indices = wp.empty(shape=(face_count,), dtype=wp.vec4i, device=device)
self._face_hex_indices = wp.empty(shape=(face_count,), dtype=wp.vec2i, device=device)
self._face_hex_face_orientation = wp.empty(shape=(face_count,), dtype=wp.vec4i, device=device)
boundary_mask = borrow_temporary(temporary_store, shape=(face_count,), dtype=int, device=device)
# Compress edge data
wp.launch(
kernel=Hexmesh._compress_faces_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
vertex_start_face_offsets.array,
vertex_unique_face_offsets.array,
vertex_unique_face_count.array,
vertex_face_other_vs.array,
vertex_face_hexes.array,
self._face_vertex_indices,
self._face_hex_indices,
boundary_mask.array,
],
)
vertex_start_face_offsets.release()
vertex_unique_face_offsets.release()
vertex_unique_face_count.release()
vertex_face_other_vs.release()
vertex_face_hexes.release()
# Flip normals if necessary
wp.launch(
kernel=Hexmesh._flip_face_normals,
device=device,
dim=self.side_count(),
inputs=[self._face_vertex_indices, self._face_hex_indices, self.hex_vertex_indices, self.positions],
)
# Compute and store face orientation
wp.launch(
kernel=Hexmesh._compute_face_orientation,
device=device,
dim=self.side_count(),
inputs=[
self._face_vertex_indices,
self._face_hex_indices,
self.hex_vertex_indices,
self._face_hex_face_orientation,
],
)
boundary_face_indices, _ = masked_indices(boundary_mask.array)
self._boundary_face_indices = boundary_face_indices.detach()
def _compute_hex_edges(self, temporary_store: Optional[TemporaryStore] = None):
from warp.utils import array_scan
device = self.hex_vertex_indices.device
vertex_start_edge_count = borrow_temporary(temporary_store, dtype=int, device=device, shape=self.vertex_count())
vertex_start_edge_count.array.zero_()
vertex_start_edge_offsets = borrow_temporary_like(vertex_start_edge_count, temporary_store=temporary_store)
vertex_edge_ends = borrow_temporary(temporary_store, dtype=int, device=device, shape=(12 * self.cell_count()))
# Count face edges starting at each vertex
wp.launch(
kernel=Hexmesh._count_starting_edges_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.hex_vertex_indices, vertex_start_edge_count.array],
)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_start_edge_offsets.array, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_edge_count = vertex_start_edge_count
wp.launch(
kernel=Hexmesh._count_unique_starting_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_hex_offsets,
self._vertex_hex_indices,
self.hex_vertex_indices,
vertex_start_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
],
)
vertex_unique_edge_offsets = borrow_temporary_like(
vertex_start_edge_offsets.array, temporary_store=temporary_store
)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_unique_edge_offsets.array, inclusive=False)
# Get back edge count to host
if device.is_cuda:
edge_count = borrow_temporary(temporary_store, shape=(1,), dtype=int, device="cpu", pinned=True)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(
dest=edge_count.array,
src=vertex_unique_edge_offsets.array,
src_offset=self.vertex_count() - 1,
count=1,
)
wp.synchronize_stream(wp.get_stream(device))
self._edge_count = int(edge_count.array.numpy()[0])
else:
self._edge_count = int(vertex_unique_edge_offsets.array.numpy()[self.vertex_count() - 1])
self._hex_edge_indices = wp.empty(
dtype=int, device=self.hex_vertex_indices.device, shape=(self.cell_count(), 12)
)
# Compress edge data
wp.launch(
kernel=Hexmesh._compress_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_hex_offsets,
self._vertex_hex_indices,
self.hex_vertex_indices,
vertex_start_edge_offsets.array,
vertex_unique_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
self._hex_edge_indices,
],
)
vertex_start_edge_offsets.release()
vertex_unique_edge_offsets.release()
vertex_unique_edge_count.release()
vertex_edge_ends.release()
@wp.kernel
def _count_starting_faces_kernel(
hex_vertex_indices: wp.array2d(dtype=int), vertex_start_face_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(6):
vi = wp.vec4i(
hex_vertex_indices[t, FACE_VERTEX_INDICES[k, 0]],
hex_vertex_indices[t, FACE_VERTEX_INDICES[k, 1]],
hex_vertex_indices[t, FACE_VERTEX_INDICES[k, 2]],
hex_vertex_indices[t, FACE_VERTEX_INDICES[k, 3]],
)
vm = wp.min(vi)
for i in range(4):
if vm == vi[i]:
wp.atomic_add(vertex_start_face_count, vm, 1)
@wp.func
def _face_sort(vidx: wp.vec4i, min_k: int):
v1 = vidx[(min_k + 1) % 4]
v2 = vidx[(min_k + 2) % 4]
v3 = vidx[(min_k + 3) % 4]
if v1 < v3:
return wp.vec3i(v1, v2, v3)
return wp.vec3i(v3, v2, v1)
@wp.func
def _find_face(
needle: wp.vec3i,
values: wp.array(dtype=wp.vec3i),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_faces_kernel(
vertex_hex_offsets: wp.array(dtype=int),
vertex_hex_indices: wp.array(dtype=int),
hex_vertex_indices: wp.array2d(dtype=int),
vertex_start_face_offsets: wp.array(dtype=int),
vertex_start_face_count: wp.array(dtype=int),
face_other_vs: wp.array(dtype=wp.vec3i),
face_hexes: wp.array2d(dtype=int),
):
v = wp.tid()
face_beg = vertex_start_face_offsets[v]
hex_beg = vertex_hex_offsets[v]
hex_end = vertex_hex_offsets[v + 1]
face_cur = face_beg
for hexa in range(hex_beg, hex_end):
hx = vertex_hex_indices[hexa]
for k in range(6):
vi = wp.vec4i(
hex_vertex_indices[hx, FACE_VERTEX_INDICES[k, 0]],
hex_vertex_indices[hx, FACE_VERTEX_INDICES[k, 1]],
hex_vertex_indices[hx, FACE_VERTEX_INDICES[k, 2]],
hex_vertex_indices[hx, FACE_VERTEX_INDICES[k, 3]],
)
min_i = int(wp.argmin(vi))
if v == vi[min_i]:
other_v = Hexmesh._face_sort(vi, min_i)
# Check if other_v has been seen
seen_idx = Hexmesh._find_face(other_v, face_other_vs, face_beg, face_cur)
if seen_idx == -1:
face_other_vs[face_cur] = other_v
face_hexes[face_cur, 0] = hx
face_hexes[face_cur, 1] = hx
face_cur += 1
else:
face_hexes[seen_idx, 1] = hx
vertex_start_face_count[v] = face_cur - face_beg
@wp.kernel
def _compress_faces_kernel(
vertex_start_face_offsets: wp.array(dtype=int),
vertex_unique_face_offsets: wp.array(dtype=int),
vertex_unique_face_count: wp.array(dtype=int),
uncompressed_face_other_vs: wp.array(dtype=wp.vec3i),
uncompressed_face_hexes: wp.array2d(dtype=int),
face_vertex_indices: wp.array(dtype=wp.vec4i),
face_hex_indices: wp.array(dtype=wp.vec2i),
boundary_mask: wp.array(dtype=int),
):
v = wp.tid()
start_beg = vertex_start_face_offsets[v]
unique_beg = vertex_unique_face_offsets[v]
unique_count = vertex_unique_face_count[v]
for f in range(unique_count):
src_index = start_beg + f
face_index = unique_beg + f
face_vertex_indices[face_index] = wp.vec4i(
v,
uncompressed_face_other_vs[src_index][0],
uncompressed_face_other_vs[src_index][1],
uncompressed_face_other_vs[src_index][2],
)
hx0 = uncompressed_face_hexes[src_index, 0]
hx1 = uncompressed_face_hexes[src_index, 1]
face_hex_indices[face_index] = wp.vec2i(hx0, hx1)
if hx0 == hx1:
boundary_mask[face_index] = 1
else:
boundary_mask[face_index] = 0
@wp.kernel
def _flip_face_normals(
face_vertex_indices: wp.array(dtype=wp.vec4i),
face_hex_indices: wp.array(dtype=wp.vec2i),
hex_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec3),
):
f = wp.tid()
hexa = face_hex_indices[f][0]
hex_vidx = hex_vertex_indices[hexa]
face_vidx = face_vertex_indices[f]
hex_centroid = (
positions[hex_vidx[0]]
+ positions[hex_vidx[1]]
+ positions[hex_vidx[2]]
+ positions[hex_vidx[3]]
+ positions[hex_vidx[4]]
+ positions[hex_vidx[5]]
+ positions[hex_vidx[6]]
+ positions[hex_vidx[7]]
) / 8.0
v0 = positions[face_vidx[0]]
v1 = positions[face_vidx[1]]
v2 = positions[face_vidx[2]]
v3 = positions[face_vidx[3]]
face_center = (v1 + v0 + v2 + v3) / 4.0
face_normal = wp.cross(v2 - v0, v3 - v1)
# if face normal points toward first tet centroid, flip indices
if wp.dot(hex_centroid - face_center, face_normal) > 0.0:
face_vertex_indices[f] = wp.vec4i(face_vidx[0], face_vidx[3], face_vidx[2], face_vidx[1])
@wp.func
def _find_face_orientation(face_vidx: wp.vec4i, hex_index: int, hex_vertex_indices: wp.array2d(dtype=int)):
hex_vidx = hex_vertex_indices[hex_index]
# Find local index in hex corresponding to face
face_min_i = int(wp.argmin(face_vidx))
face_other_v = Hexmesh._face_sort(face_vidx, face_min_i)
for k in range(6):
hex_face_vi = wp.vec4i(
hex_vidx[FACE_VERTEX_INDICES[k, 0]],
hex_vidx[FACE_VERTEX_INDICES[k, 1]],
hex_vidx[FACE_VERTEX_INDICES[k, 2]],
hex_vidx[FACE_VERTEX_INDICES[k, 3]],
)
hex_min_i = int(wp.argmin(hex_face_vi))
hex_other_v = Hexmesh._face_sort(hex_face_vi, hex_min_i)
if hex_other_v == face_other_v:
local_face_index = k
break
# Find starting vertex index
for k in range(4):
if face_vidx[k] == hex_face_vi[0]:
face_orientation = 2 * k
if face_vidx[(k + 1) % 4] != hex_face_vi[1]:
face_orientation += 1
return local_face_index, face_orientation
@wp.kernel
def _compute_face_orientation(
face_vertex_indices: wp.array(dtype=wp.vec4i),
face_hex_indices: wp.array(dtype=wp.vec2i),
hex_vertex_indices: wp.array2d(dtype=int),
face_hex_face_ori: wp.array(dtype=wp.vec4i),
):
f = wp.tid()
face_vidx = face_vertex_indices[f]
hx0 = face_hex_indices[f][0]
local_face_0, ori_0 = Hexmesh._find_face_orientation(face_vidx, hx0, hex_vertex_indices)
hx1 = face_hex_indices[f][1]
if hx0 == hx1:
face_hex_face_ori[f] = wp.vec4i(local_face_0, ori_0, local_face_0, ori_0)
else:
local_face_1, ori_1 = Hexmesh._find_face_orientation(face_vidx, hx1, hex_vertex_indices)
face_hex_face_ori[f] = wp.vec4i(local_face_0, ori_0, local_face_1, ori_1)
@wp.kernel
def _count_starting_edges_kernel(
hex_vertex_indices: wp.array2d(dtype=int), vertex_start_edge_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(12):
v0 = hex_vertex_indices[t, EDGE_VERTEX_INDICES[k, 0]]
v1 = hex_vertex_indices[t, EDGE_VERTEX_INDICES[k, 1]]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
@wp.func
def _find_edge(
needle: int,
values: wp.array(dtype=int),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_edges_kernel(
vertex_hex_offsets: wp.array(dtype=int),
vertex_hex_indices: wp.array(dtype=int),
hex_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_start_edge_count: wp.array(dtype=int),
edge_ends: wp.array(dtype=int),
):
v = wp.tid()
edge_beg = vertex_start_edge_offsets[v]
hex_beg = vertex_hex_offsets[v]
hex_end = vertex_hex_offsets[v + 1]
edge_cur = edge_beg
for tet in range(hex_beg, hex_end):
t = vertex_hex_indices[tet]
for k in range(12):
v0 = hex_vertex_indices[t, EDGE_VERTEX_INDICES[k, 0]]
v1 = hex_vertex_indices[t, EDGE_VERTEX_INDICES[k, 1]]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
if Hexmesh._find_edge(other_v, edge_ends, edge_beg, edge_cur) == -1:
edge_ends[edge_cur] = other_v
edge_cur += 1
vertex_start_edge_count[v] = edge_cur - edge_beg
@wp.kernel
def _compress_edges_kernel(
vertex_hex_offsets: wp.array(dtype=int),
vertex_hex_indices: wp.array(dtype=int),
hex_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_count: wp.array(dtype=int),
uncompressed_edge_ends: wp.array(dtype=int),
hex_edge_indices: wp.array2d(dtype=int),
):
v = wp.tid()
uncompressed_beg = vertex_start_edge_offsets[v]
unique_beg = vertex_unique_edge_offsets[v]
unique_count = vertex_unique_edge_count[v]
hex_beg = vertex_hex_offsets[v]
hex_end = vertex_hex_offsets[v + 1]
for tet in range(hex_beg, hex_end):
t = vertex_hex_indices[tet]
for k in range(12):
v0 = hex_vertex_indices[t, EDGE_VERTEX_INDICES[k, 0]]
v1 = hex_vertex_indices[t, EDGE_VERTEX_INDICES[k, 1]]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
edge_id = (
Hexmesh._find_edge(
other_v, uncompressed_edge_ends, uncompressed_beg, uncompressed_beg + unique_count
)
- uncompressed_beg
+ unique_beg
)
hex_edge_indices[t][k] = edge_id
| 34,831 | Python | 35.51153 | 124 | 0.569234 |
NVIDIA/warp/warp/fem/geometry/trimesh_2d.py | from typing import Optional
import warp as wp
from warp.fem.cache import (
TemporaryStore,
borrow_temporary,
borrow_temporary_like,
cached_arg_value,
)
from warp.fem.types import (
NULL_ELEMENT_INDEX,
OUTSIDE,
Coords,
ElementIndex,
Sample,
make_free_sample,
)
from .closest_point import project_on_tri_at_origin
from .element import LinearEdge, Triangle
from .geometry import Geometry
@wp.struct
class Trimesh2DCellArg:
tri_vertex_indices: wp.array2d(dtype=int)
positions: wp.array(dtype=wp.vec2)
# for neighbor cell lookup
vertex_tri_offsets: wp.array(dtype=int)
vertex_tri_indices: wp.array(dtype=int)
deformation_gradients: wp.array(dtype=wp.mat22f)
@wp.struct
class Trimesh2DSideArg:
cell_arg: Trimesh2DCellArg
edge_vertex_indices: wp.array(dtype=wp.vec2i)
edge_tri_indices: wp.array(dtype=wp.vec2i)
class Trimesh2D(Geometry):
"""Two-dimensional triangular mesh geometry"""
dimension = 2
def __init__(
self, tri_vertex_indices: wp.array, positions: wp.array, temporary_store: Optional[TemporaryStore] = None
):
"""
Constructs a two-dimensional triangular mesh.
Args:
tri_vertex_indices: warp array of shape (num_tris, 3) containing vertex indices for each tri
positions: warp array of shape (num_vertices, 2) containing 2d position for each vertex
temporary_store: shared pool from which to allocate temporary arrays
"""
self.tri_vertex_indices = tri_vertex_indices
self.positions = positions
self._edge_vertex_indices: wp.array = None
self._edge_tri_indices: wp.array = None
self._vertex_tri_offsets: wp.array = None
self._vertex_tri_indices: wp.array = None
self._build_topology(temporary_store)
self._deformation_gradients: wp.array = None
self._compute_deformation_gradients()
def cell_count(self):
return self.tri_vertex_indices.shape[0]
def vertex_count(self):
return self.positions.shape[0]
def side_count(self):
return self._edge_vertex_indices.shape[0]
def boundary_side_count(self):
return self._boundary_edge_indices.shape[0]
def reference_cell(self) -> Triangle:
return Triangle()
def reference_side(self) -> LinearEdge:
return LinearEdge()
@property
def edge_tri_indices(self) -> wp.array:
return self._edge_tri_indices
@property
def edge_vertex_indices(self) -> wp.array:
return self._edge_vertex_indices
CellArg = Trimesh2DCellArg
SideArg = Trimesh2DSideArg
@wp.struct
class SideIndexArg:
boundary_edge_indices: wp.array(dtype=int)
# Geometry device interface
@cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.tri_vertex_indices = self.tri_vertex_indices.to(device)
args.positions = self.positions.to(device)
args.vertex_tri_offsets = self._vertex_tri_offsets.to(device)
args.vertex_tri_indices = self._vertex_tri_indices.to(device)
args.deformation_gradients = self._deformation_gradients.to(device)
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
tri_idx = args.tri_vertex_indices[s.element_index]
return (
s.element_coords[0] * args.positions[tri_idx[0]]
+ s.element_coords[1] * args.positions[tri_idx[1]]
+ s.element_coords[2] * args.positions[tri_idx[2]]
)
@wp.func
def cell_deformation_gradient(args: CellArg, s: Sample):
return args.deformation_gradients[s.element_index]
@wp.func
def cell_inverse_deformation_gradient(args: CellArg, s: Sample):
return wp.inverse(args.deformation_gradients[s.element_index])
@wp.func
def _project_on_tri(args: CellArg, pos: wp.vec2, tri_index: int):
p0 = args.positions[args.tri_vertex_indices[tri_index, 0]]
q = pos - p0
e1 = args.positions[args.tri_vertex_indices[tri_index, 1]] - p0
e2 = args.positions[args.tri_vertex_indices[tri_index, 2]] - p0
dist, coords = project_on_tri_at_origin(q, e1, e2)
return dist, coords
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec2, guess: Sample):
closest_tri = int(NULL_ELEMENT_INDEX)
closest_coords = Coords(OUTSIDE)
closest_dist = float(1.0e8)
for v in range(3):
vtx = args.tri_vertex_indices[guess.element_index, v]
tri_beg = args.vertex_tri_offsets[vtx]
tri_end = args.vertex_tri_offsets[vtx + 1]
for t in range(tri_beg, tri_end):
tri = args.vertex_tri_indices[t]
dist, coords = Trimesh2D._project_on_tri(args, pos, tri)
if dist <= closest_dist:
closest_dist = dist
closest_tri = tri
closest_coords = coords
return make_free_sample(closest_tri, closest_coords)
@wp.func
def cell_measure(args: CellArg, s: Sample):
return 0.5 * wp.abs(wp.determinant(args.deformation_gradients[s.element_index]))
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec2(0.0)
@cached_arg_value
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_edge_indices = self._boundary_edge_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
"""Boundary side to side index"""
return args.boundary_edge_indices[boundary_side_index]
@cached_arg_value
def side_arg_value(self, device) -> CellArg:
args = self.SideArg()
args.cell_arg = self.cell_arg_value(device)
args.edge_vertex_indices = self._edge_vertex_indices.to(device)
args.edge_tri_indices = self._edge_tri_indices.to(device)
return args
@wp.func
def side_position(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
return (1.0 - s.element_coords[0]) * args.cell_arg.positions[edge_idx[0]] + s.element_coords[
0
] * args.cell_arg.positions[edge_idx[1]]
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.cell_arg.positions[edge_idx[0]]
v1 = args.cell_arg.positions[edge_idx[1]]
return v1 - v0
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Trimesh2D.side_inner_cell_index(args, s.element_index)
return wp.inverse(args.cell_arg.deformation_gradients[cell_index])
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
cell_index = Trimesh2D.side_outer_cell_index(args, s.element_index)
return wp.inverse(args.cell_arg.deformation_gradients[cell_index])
@wp.func
def side_measure(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.cell_arg.positions[edge_idx[0]]
v1 = args.cell_arg.positions[edge_idx[1]]
return wp.length(v1 - v0)
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
inner = Trimesh2D.side_inner_cell_index(args, s.element_index)
outer = Trimesh2D.side_outer_cell_index(args, s.element_index)
return Trimesh2D.side_measure(args, s) / wp.min(
Trimesh2D.cell_measure(args.cell_arg, make_free_sample(inner, Coords())),
Trimesh2D.cell_measure(args.cell_arg, make_free_sample(outer, Coords())),
)
@wp.func
def side_normal(args: SideArg, s: Sample):
edge_idx = args.edge_vertex_indices[s.element_index]
v0 = args.cell_arg.positions[edge_idx[0]]
v1 = args.cell_arg.positions[edge_idx[1]]
e = v1 - v0
return wp.normalize(wp.vec2(-e[1], e[0]))
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.edge_tri_indices[side_index][0]
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
return arg.edge_tri_indices[side_index][1]
@wp.func
def edge_to_tri_coords(args: SideArg, side_index: ElementIndex, tri_index: ElementIndex, side_coords: Coords):
edge_vidx = args.edge_vertex_indices[side_index]
tri_vidx = args.cell_arg.tri_vertex_indices[tri_index]
v0 = tri_vidx[0]
v1 = tri_vidx[1]
cx = float(0.0)
cy = float(0.0)
cz = float(0.0)
if edge_vidx[0] == v0:
cx = 1.0 - side_coords[0]
elif edge_vidx[0] == v1:
cy = 1.0 - side_coords[0]
else:
cz = 1.0 - side_coords[0]
if edge_vidx[1] == v0:
cx = side_coords[0]
elif edge_vidx[1] == v1:
cy = side_coords[0]
else:
cz = side_coords[0]
return Coords(cx, cy, cz)
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
inner_cell_index = Trimesh2D.side_inner_cell_index(args, side_index)
return Trimesh2D.edge_to_tri_coords(args, side_index, inner_cell_index, side_coords)
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
outer_cell_index = Trimesh2D.side_outer_cell_index(args, side_index)
return Trimesh2D.edge_to_tri_coords(args, side_index, outer_cell_index, side_coords)
@wp.func
def side_from_cell_coords(
args: SideArg,
side_index: ElementIndex,
tri_index: ElementIndex,
tri_coords: Coords,
):
edge_vidx = args.edge_vertex_indices[side_index]
tri_vidx = args.cell_arg.tri_vertex_indices[tri_index]
start = int(2)
end = int(2)
for k in range(2):
v = tri_vidx[k]
if edge_vidx[1] == v:
end = k
elif edge_vidx[0] == v:
start = k
return wp.select(
tri_coords[start] + tri_coords[end] > 0.999, Coords(OUTSIDE), Coords(tri_coords[end], 0.0, 0.0)
)
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
def _build_topology(self, temporary_store: TemporaryStore):
from warp.fem.utils import compress_node_indices, masked_indices
from warp.utils import array_scan
device = self.tri_vertex_indices.device
vertex_tri_offsets, vertex_tri_indices, _, __ = compress_node_indices(
self.vertex_count(), self.tri_vertex_indices, temporary_store=temporary_store
)
self._vertex_tri_offsets = vertex_tri_offsets.detach()
self._vertex_tri_indices = vertex_tri_indices.detach()
vertex_start_edge_count = borrow_temporary(temporary_store, dtype=int, device=device, shape=self.vertex_count())
vertex_start_edge_count.array.zero_()
vertex_start_edge_offsets = borrow_temporary_like(vertex_start_edge_count, temporary_store=temporary_store)
vertex_edge_ends = borrow_temporary(temporary_store, dtype=int, device=device, shape=(3 * self.cell_count()))
vertex_edge_tris = borrow_temporary(temporary_store, dtype=int, device=device, shape=(3 * self.cell_count(), 2))
# Count face edges starting at each vertex
wp.launch(
kernel=Trimesh2D._count_starting_edges_kernel,
device=device,
dim=self.cell_count(),
inputs=[self.tri_vertex_indices, vertex_start_edge_count.array],
)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_start_edge_offsets.array, inclusive=False)
# Count number of unique edges (deduplicate across faces)
vertex_unique_edge_count = vertex_start_edge_count
wp.launch(
kernel=Trimesh2D._count_unique_starting_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
self._vertex_tri_offsets,
self._vertex_tri_indices,
self.tri_vertex_indices,
vertex_start_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
vertex_edge_tris.array,
],
)
vertex_unique_edge_offsets = borrow_temporary_like(vertex_start_edge_offsets, temporary_store=temporary_store)
array_scan(in_array=vertex_start_edge_count.array, out_array=vertex_unique_edge_offsets.array, inclusive=False)
# Get back edge count to host
if device.is_cuda:
edge_count = borrow_temporary(temporary_store, shape=(1,), dtype=int, device="cpu", pinned=True)
# Last vertex will not own any edge, so its count will be zero; just fetching last prefix count is ok
wp.copy(
dest=edge_count.array, src=vertex_unique_edge_offsets.array, src_offset=self.vertex_count() - 1, count=1
)
wp.synchronize_stream(wp.get_stream(device))
edge_count = int(edge_count.array.numpy()[0])
else:
edge_count = int(vertex_unique_edge_offsets.array.numpy()[self.vertex_count() - 1])
self._edge_vertex_indices = wp.empty(shape=(edge_count,), dtype=wp.vec2i, device=device)
self._edge_tri_indices = wp.empty(shape=(edge_count,), dtype=wp.vec2i, device=device)
boundary_mask = borrow_temporary(temporary_store=temporary_store, shape=(edge_count,), dtype=int, device=device)
# Compress edge data
wp.launch(
kernel=Trimesh2D._compress_edges_kernel,
device=device,
dim=self.vertex_count(),
inputs=[
vertex_start_edge_offsets.array,
vertex_unique_edge_offsets.array,
vertex_unique_edge_count.array,
vertex_edge_ends.array,
vertex_edge_tris.array,
self._edge_vertex_indices,
self._edge_tri_indices,
boundary_mask.array,
],
)
vertex_start_edge_offsets.release()
vertex_unique_edge_offsets.release()
vertex_unique_edge_count.release()
vertex_edge_ends.release()
vertex_edge_tris.release()
# Flip normals if necessary
wp.launch(
kernel=Trimesh2D._flip_edge_normals,
device=device,
dim=self.side_count(),
inputs=[self._edge_vertex_indices, self._edge_tri_indices, self.tri_vertex_indices, self.positions],
)
boundary_edge_indices, _ = masked_indices(boundary_mask.array, temporary_store=temporary_store)
self._boundary_edge_indices = boundary_edge_indices.detach()
boundary_mask.release()
def _compute_deformation_gradients(self):
self._deformation_gradients = wp.empty(dtype=wp.mat22f, device=self.positions.device, shape=(self.cell_count()))
wp.launch(
kernel=Trimesh2D._compute_deformation_gradients_kernel,
dim=self._deformation_gradients.shape,
device=self._deformation_gradients.device,
inputs=[self.tri_vertex_indices, self.positions, self._deformation_gradients],
)
@wp.kernel
def _count_starting_edges_kernel(
tri_vertex_indices: wp.array2d(dtype=int), vertex_start_edge_count: wp.array(dtype=int)
):
t = wp.tid()
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, (k + 1) % 3]
if v0 < v1:
wp.atomic_add(vertex_start_edge_count, v0, 1)
else:
wp.atomic_add(vertex_start_edge_count, v1, 1)
@wp.func
def _find(
needle: int,
values: wp.array(dtype=int),
beg: int,
end: int,
):
for i in range(beg, end):
if values[i] == needle:
return i
return -1
@wp.kernel
def _count_unique_starting_edges_kernel(
vertex_tri_offsets: wp.array(dtype=int),
vertex_tri_indices: wp.array(dtype=int),
tri_vertex_indices: wp.array2d(dtype=int),
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_start_edge_count: wp.array(dtype=int),
edge_ends: wp.array(dtype=int),
edge_tris: wp.array2d(dtype=int),
):
v = wp.tid()
edge_beg = vertex_start_edge_offsets[v]
tri_beg = vertex_tri_offsets[v]
tri_end = vertex_tri_offsets[v + 1]
edge_cur = edge_beg
for tri in range(tri_beg, tri_end):
t = vertex_tri_indices[tri]
for k in range(3):
v0 = tri_vertex_indices[t, k]
v1 = tri_vertex_indices[t, (k + 1) % 3]
if v == wp.min(v0, v1):
other_v = wp.max(v0, v1)
# Check if other_v has been seen
seen_idx = Trimesh2D._find(other_v, edge_ends, edge_beg, edge_cur)
if seen_idx == -1:
edge_ends[edge_cur] = other_v
edge_tris[edge_cur, 0] = t
edge_tris[edge_cur, 1] = t
edge_cur += 1
else:
edge_tris[seen_idx, 1] = t
vertex_start_edge_count[v] = edge_cur - edge_beg
@wp.kernel
def _compress_edges_kernel(
vertex_start_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_offsets: wp.array(dtype=int),
vertex_unique_edge_count: wp.array(dtype=int),
uncompressed_edge_ends: wp.array(dtype=int),
uncompressed_edge_tris: wp.array2d(dtype=int),
edge_vertex_indices: wp.array(dtype=wp.vec2i),
edge_tri_indices: wp.array(dtype=wp.vec2i),
boundary_mask: wp.array(dtype=int),
):
v = wp.tid()
start_beg = vertex_start_edge_offsets[v]
unique_beg = vertex_unique_edge_offsets[v]
unique_count = vertex_unique_edge_count[v]
for e in range(unique_count):
src_index = start_beg + e
edge_index = unique_beg + e
edge_vertex_indices[edge_index] = wp.vec2i(v, uncompressed_edge_ends[src_index])
t0 = uncompressed_edge_tris[src_index, 0]
t1 = uncompressed_edge_tris[src_index, 1]
edge_tri_indices[edge_index] = wp.vec2i(t0, t1)
if t0 == t1:
boundary_mask[edge_index] = 1
else:
boundary_mask[edge_index] = 0
@wp.kernel
def _flip_edge_normals(
edge_vertex_indices: wp.array(dtype=wp.vec2i),
edge_tri_indices: wp.array(dtype=wp.vec2i),
tri_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec2),
):
e = wp.tid()
tri = edge_tri_indices[e][0]
tri_vidx = tri_vertex_indices[tri]
edge_vidx = edge_vertex_indices[e]
tri_centroid = (positions[tri_vidx[0]] + positions[tri_vidx[1]] + positions[tri_vidx[2]]) / 3.0
v0 = positions[edge_vidx[0]]
v1 = positions[edge_vidx[1]]
edge_center = 0.5 * (v1 + v0)
edge_vec = v1 - v0
edge_normal = wp.vec2(-edge_vec[1], edge_vec[0])
# if edge normal points toward first triangle centroid, flip indices
if wp.dot(tri_centroid - edge_center, edge_normal) > 0.0:
edge_vertex_indices[e] = wp.vec2i(edge_vidx[1], edge_vidx[0])
@wp.kernel
def _compute_deformation_gradients_kernel(
tri_vertex_indices: wp.array2d(dtype=int),
positions: wp.array(dtype=wp.vec2f),
transforms: wp.array(dtype=wp.mat22f),
):
t = wp.tid()
p0 = positions[tri_vertex_indices[t, 0]]
p1 = positions[tri_vertex_indices[t, 1]]
p2 = positions[tri_vertex_indices[t, 2]]
e1 = p1 - p0
e2 = p2 - p0
transforms[t] = wp.mat22(e1, e2)
| 20,109 | Python | 33.792387 | 120 | 0.602715 |
NVIDIA/warp/warp/fem/geometry/__init__.py | from .deformed_geometry import DeformedGeometry
from .element import Element
from .geometry import Geometry
from .grid_2d import Grid2D
from .grid_3d import Grid3D
from .hexmesh import Hexmesh
from .nanogrid import Nanogrid
from .partition import (
ExplicitGeometryPartition,
GeometryPartition,
LinearGeometryPartition,
WholeGeometryPartition,
)
from .quadmesh_2d import Quadmesh2D
from .tetmesh import Tetmesh
from .trimesh_2d import Trimesh2D
| 461 | Python | 26.176469 | 47 | 0.81128 |
NVIDIA/warp/warp/fem/geometry/nanogrid.py | from typing import Optional
import numpy as np
import warp as wp
from warp.fem import cache, utils
from warp.fem.types import NULL_ELEMENT_INDEX, OUTSIDE, Coords, ElementIndex, Sample, make_free_sample
from .element import Cube, Square
from .geometry import Geometry
# Flag used for building edge/face grids to disambiguiate axis within the grid
GRID_AXIS_FLAG = wp.constant(wp.int32(1 << 20))
FACE_AXIS_MASK = wp.constant(wp.uint8((1 << 3) - 1))
FACE_INNER_OFFSET_BIT = wp.constant(wp.uint8(3))
FACE_OUTER_OFFSET_BIT = wp.constant(wp.uint8(4))
_mat32 = wp.mat(shape=(3, 2), dtype=float)
@wp.func
def _add_axis_flag(ijk: wp.vec3i, axis: int):
coord = ijk[axis]
ijk[axis] = wp.select(coord < 0, coord | GRID_AXIS_FLAG, coord & (~GRID_AXIS_FLAG))
return ijk
@wp.func
def _extract_axis_flag(ijk: wp.vec3i):
for ax in range(3):
coord = ijk[ax]
if coord < 0:
if (ijk[ax] & GRID_AXIS_FLAG) == 0:
ijk[ax] = ijk[ax] | GRID_AXIS_FLAG
return ax, ijk
else:
if (ijk[ax] & GRID_AXIS_FLAG) != 0:
ijk[ax] = ijk[ax] & (~GRID_AXIS_FLAG)
return ax, ijk
return -1, ijk
@wp.struct
class NanogridCellArg:
# Utility device functions
cell_grid: wp.uint64
cell_ijk: wp.array(dtype=wp.vec3i)
inverse_transform: wp.mat33
cell_volume: float
@wp.struct
class NanogridSideArg:
# Utility device functions
cell_arg: NanogridCellArg
face_ijk: wp.array(dtype=wp.vec3i)
face_flags: wp.array(dtype=wp.uint8)
face_areas: wp.vec3
class Nanogrid(Geometry):
dimension = 3
def __init__(self, grid: wp.Volume, temporary_store: Optional[cache.TemporaryStore] = None):
self._cell_grid = grid
self._cell_grid_info = grid.get_grid_info()
device = grid.device
cell_count = grid.get_voxel_count()
self._cell_ijk = wp.array(shape=(cell_count,), dtype=wp.vec3i, device=device)
grid.get_voxels(out=self._cell_ijk)
self._node_grid = _build_node_grid(self._cell_ijk, grid, temporary_store)
node_count = self._node_grid.get_voxel_count()
self._node_ijk = wp.array(shape=(node_count,), dtype=wp.vec3i, device=device)
self._node_grid.get_voxels(out=self._node_ijk)
self._face_grid = _build_face_grid(self._cell_ijk, grid, temporary_store)
face_count = self._face_grid.get_voxel_count()
self._face_ijk = wp.array(shape=(face_count,), dtype=wp.vec3i, device=device)
self._face_grid.get_voxels(out=self._face_ijk)
self._face_flags = wp.array(shape=(face_count,), dtype=wp.uint8, device=device)
boundary_face_mask = cache.borrow_temporary(temporary_store, shape=(face_count,), dtype=wp.int32, device=device)
wp.launch(
_build_face_flags,
dim=face_count,
device=device,
inputs=[grid.id, self._face_ijk, self._face_flags, boundary_face_mask.array],
)
boundary_face_indices, _ = utils.masked_indices(boundary_face_mask.array)
self._boundary_face_indices = boundary_face_indices.detach()
self._edge_grid = None
self._edge_ijk = None
def _build_edge_grid(self, temporary_store: Optional[cache.TemporaryStore] = None):
self._edge_grid = _build_edge_grid(self._cell_ijk, self._cell_grid, temporary_store)
edge_count = self._edge_grid.get_voxel_count()
self._edge_ijk = wp.array(shape=(edge_count,), dtype=wp.vec3i, device=self._edge_grid.device)
self._edge_grid.get_voxels(out=self._edge_ijk)
def cell_count(self):
return self._cell_ijk.shape[0]
def vertex_count(self):
return self._node_ijk.shape[0]
def side_count(self):
return self._face_ijk.shape[0]
def edge_count(self):
if self._edge_ijk is None:
self._build_edge_grid()
return self._edge_ijk.shape[0]
def boundary_side_count(self):
return self._boundary_face_indices.shape[0]
def reference_cell(self) -> Cube:
return Cube()
def reference_side(self) -> Square:
return Square()
CellArg = NanogridCellArg
@cache.cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.cell_grid = self._cell_grid.id
args.cell_ijk = self._cell_ijk
transform = np.array(self._cell_grid_info.transform_matrix).reshape(3, 3)
args.inverse_transform = wp.mat33f(np.linalg.inv(transform))
args.cell_volume = abs(np.linalg.det(transform))
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
uvw = wp.vec3(args.cell_ijk[s.element_index]) + s.element_coords
return wp.volume_index_to_world(args.cell_grid, uvw)
@wp.func
def cell_deformation_gradient(args: CellArg, s: Sample):
return wp.inverse(args.inverse_transform)
@wp.func
def cell_inverse_deformation_gradient(args: CellArg, s: Sample):
return args.inverse_transform
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3):
uvw = wp.volume_world_to_index(args.cell_grid, pos)
ijk = wp.vec3i(int(wp.floor(uvw[0])), int(wp.floor(uvw[1])), int(wp.floor(uvw[2])))
element_index = wp.volume_lookup_index(args.cell_grid, ijk[0], ijk[1], ijk[2])
return wp.select(
element_index == -1,
make_free_sample(element_index, uvw - wp.vec3(ijk)),
make_free_sample(NULL_ELEMENT_INDEX, Coords(OUTSIDE)),
)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec3, guess: Sample):
return Nanogrid.cell_lookup(args, pos)
@wp.func
def cell_measure(args: CellArg, s: Sample):
return args.cell_volume
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec3(0.0)
SideArg = NanogridSideArg
@cache.cached_arg_value
def side_arg_value(self, device) -> SideArg:
args = self.SideArg()
args.cell_arg = self.cell_arg_value(device)
args.face_ijk = self._face_ijk.to(device)
args.face_flags = self._face_flags.to(device)
transform = np.array(self._cell_grid_info.transform_matrix).reshape(3, 3)
args.face_areas = wp.vec3(
tuple(np.linalg.norm(np.cross(transform[:, k - 2], transform[:, k - 1])) for k in range(3))
)
return args
@wp.struct
class SideIndexArg:
boundary_face_indices: wp.array(dtype=int)
@cache.cached_arg_value
def side_index_arg_value(self, device) -> SideIndexArg:
args = self.SideIndexArg()
args.boundary_face_indices = self._boundary_face_indices.to(device)
return args
@wp.func
def boundary_side_index(args: SideIndexArg, boundary_side_index: int):
return args.boundary_face_indices[boundary_side_index]
@wp.func
def _side_to_cell_coords(axis: int, inner: float, side_coords: Coords):
uvw = wp.vec3()
uvw[axis] = inner
uvw[(axis + 1) % 3] = side_coords[0]
uvw[(axis + 2) % 3] = side_coords[1]
return uvw
@wp.func
def _get_face_axis(flags: wp.uint8):
return wp.int32(flags & FACE_AXIS_MASK)
@wp.func
def _get_face_inner_offset(flags: wp.uint8):
return wp.int32(flags >> FACE_INNER_OFFSET_BIT) & 1
@wp.func
def _get_face_outer_offset(flags: wp.uint8):
return wp.int32(flags >> FACE_OUTER_OFFSET_BIT) & 1
@wp.func
def side_position(args: SideArg, s: Sample):
ijk = args.face_ijk[s.element_index]
axis = Nanogrid._get_face_axis(args.face_flags[s.element_index])
uvw = wp.vec3(ijk) + Nanogrid._side_to_cell_coords(axis, 0.0, s.element_coords)
cell_grid = args.cell_arg.cell_grid
return wp.volume_index_to_world(cell_grid, uvw)
@wp.func
def _face_tangent_vecs(args: SideArg, axis: int, flip: int):
u_axis = utils.unit_element(wp.vec3(), (axis + 1 + flip) % 3)
v_axis = utils.unit_element(wp.vec3(), (axis + 2 - flip) % 3)
cell_grid = args.cell_arg.cell_grid
return wp.volume_index_to_world_dir(cell_grid, u_axis), wp.volume_index_to_world_dir(cell_grid, v_axis)
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
flags = args.face_flags[s.element_index]
axis = Nanogrid._get_face_axis(flags)
flip = Nanogrid._get_face_inner_offset(flags)
v1, v2 = Nanogrid._face_tangent_vecs(args, axis, flip)
return _mat32(v1, v2)
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
return Nanogrid.cell_inverse_deformation_gradient(args.cell_arg, s)
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
return Nanogrid.cell_inverse_deformation_gradient(args.cell_arg, s)
@wp.func
def side_measure(args: SideArg, s: Sample):
axis = Nanogrid._get_face_axis(args.face_flags[s.element_index])
return args.face_areas[axis]
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
axis = Nanogrid._get_face_axis(args.face_flags[s.element_index])
return args.face_areas[axis] / args.cell_arg.cell_volume
@wp.func
def side_normal(args: SideArg, s: Sample):
flags = args.face_flags[s.element_index]
axis = Nanogrid._get_face_axis(flags)
flip = Nanogrid._get_face_inner_offset(flags)
v1, v2 = Nanogrid._face_tangent_vecs(args, axis, flip)
return wp.cross(v1, v2) / args.face_areas[axis]
@wp.func
def side_inner_cell_index(args: SideArg, side_index: ElementIndex):
ijk = args.face_ijk[side_index]
flags = args.face_flags[side_index]
axis = Nanogrid._get_face_axis(flags)
offset = Nanogrid._get_face_inner_offset(flags)
ijk[axis] += offset - 1
cell_grid = args.cell_arg.cell_grid
return wp.volume_lookup_index(cell_grid, ijk[0], ijk[1], ijk[2])
@wp.func
def side_outer_cell_index(args: SideArg, side_index: ElementIndex):
ijk = args.face_ijk[side_index]
flags = args.face_flags[side_index]
axis = Nanogrid._get_face_axis(flags)
offset = Nanogrid._get_face_outer_offset(flags)
ijk[axis] -= offset
cell_grid = args.cell_arg.cell_grid
return wp.volume_lookup_index(cell_grid, ijk[0], ijk[1], ijk[2])
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
flags = args.face_flags[side_index]
axis = Nanogrid._get_face_axis(flags)
offset = float(Nanogrid._get_face_inner_offset(flags))
return Nanogrid._side_to_cell_coords(axis, 1.0 - offset, side_coords)
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
flags = args.face_flags[side_index]
axis = Nanogrid._get_face_axis(flags)
offset = float(Nanogrid._get_face_outer_offset(flags))
return Nanogrid._side_to_cell_coords(axis, offset, side_coords)
@wp.func
def side_from_cell_coords(
args: SideArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
flags = args.face_flags[side_index]
axis = Nanogrid._get_face_axis(flags)
cell_ijk = args.cell_arg.cell_ijk[element_index]
side_ijk = args.face_ijk[side_index]
on_side = float(side_ijk[axis] - cell_ijk[axis]) == element_coords[axis]
return wp.select(
on_side, Coords(OUTSIDE), Coords(element_coords[(axis + 1) % 3], element_coords[(axis + 2) % 3], 0.0)
)
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
@wp.kernel
def _cell_node_indices(
cell_ijk: wp.array(dtype=wp.vec3i),
node_ijk: wp.array2d(dtype=wp.vec3i),
):
cell, n = wp.tid()
node_ijk[cell, n] = cell_ijk[cell] + wp.vec3i((n & 4) >> 2, (n & 2) >> 1, n & 1)
@wp.kernel
def _cell_face_indices(
cell_ijk: wp.array(dtype=wp.vec3i),
node_ijk: wp.array2d(dtype=wp.vec3i),
):
cell = wp.tid()
ijk = cell_ijk[cell]
node_ijk[cell, 0] = _add_axis_flag(ijk, 0)
node_ijk[cell, 1] = _add_axis_flag(ijk, 1)
node_ijk[cell, 2] = _add_axis_flag(ijk, 2)
node_ijk[cell, 3] = _add_axis_flag(ijk + wp.vec3i(1, 0, 0), 0)
node_ijk[cell, 4] = _add_axis_flag(ijk + wp.vec3i(0, 1, 0), 1)
node_ijk[cell, 5] = _add_axis_flag(ijk + wp.vec3i(0, 0, 1), 2)
@wp.kernel
def _cell_edge_indices(
cell_ijk: wp.array(dtype=wp.vec3i),
edge_ijk: wp.array2d(dtype=wp.vec3i),
):
cell = wp.tid()
ijk = cell_ijk[cell]
edge_ijk[cell, 0] = _add_axis_flag(ijk, 0)
edge_ijk[cell, 1] = _add_axis_flag(ijk, 1)
edge_ijk[cell, 2] = _add_axis_flag(ijk, 2)
edge_ijk[cell, 3] = _add_axis_flag(ijk + wp.vec3i(0, 1, 0), 0)
edge_ijk[cell, 4] = _add_axis_flag(ijk + wp.vec3i(0, 0, 1), 1)
edge_ijk[cell, 5] = _add_axis_flag(ijk + wp.vec3i(1, 0, 0), 2)
edge_ijk[cell, 6] = _add_axis_flag(ijk + wp.vec3i(0, 1, 1), 0)
edge_ijk[cell, 7] = _add_axis_flag(ijk + wp.vec3i(1, 0, 1), 1)
edge_ijk[cell, 8] = _add_axis_flag(ijk + wp.vec3i(1, 1, 0), 2)
edge_ijk[cell, 9] = _add_axis_flag(ijk + wp.vec3i(0, 0, 1), 0)
edge_ijk[cell, 10] = _add_axis_flag(ijk + wp.vec3i(1, 0, 0), 1)
edge_ijk[cell, 11] = _add_axis_flag(ijk + wp.vec3i(0, 1, 0), 2)
def _build_node_grid(cell_ijk, grid: wp.Volume, temporary_store: cache.TemporaryStore):
cell_count = cell_ijk.shape[0]
cell_nodes = cache.borrow_temporary(temporary_store, shape=(cell_count, 8), dtype=wp.vec3i, device=cell_ijk.device)
wp.launch(
_cell_node_indices, dim=cell_nodes.array.shape, inputs=[cell_ijk, cell_nodes.array], device=cell_ijk.device
)
node_grid = wp.Volume.allocate_by_voxels(
cell_nodes.array.flatten(), voxel_size=grid.get_voxel_size()[0], device=cell_ijk.device
)
return node_grid
def _build_face_grid(cell_ijk, grid: wp.Volume, temporary_store: cache.TemporaryStore):
cell_count = cell_ijk.shape[0]
cell_faces = cache.borrow_temporary(temporary_store, shape=(cell_count, 6), dtype=wp.vec3i, device=cell_ijk.device)
wp.launch(_cell_face_indices, dim=cell_count, inputs=[cell_ijk, cell_faces.array], device=cell_ijk.device)
face_grid = wp.Volume.allocate_by_voxels(
cell_faces.array.flatten(), voxel_size=grid.get_voxel_size()[0], device=cell_ijk.device
)
return face_grid
def _build_edge_grid(cell_ijk, grid: wp.Volume, temporary_store: cache.TemporaryStore):
cell_count = cell_ijk.shape[0]
cell_edges = cache.borrow_temporary(temporary_store, shape=(cell_count, 12), dtype=wp.vec3i, device=cell_ijk.device)
wp.launch(_cell_edge_indices, dim=cell_count, inputs=[cell_ijk, cell_edges.array], device=cell_ijk.device)
edge_grid = wp.Volume.allocate_by_voxels(
cell_edges.array.flatten(), voxel_size=grid.get_voxel_size()[0], device=cell_ijk.device
)
return edge_grid
@wp.kernel
def _build_face_flags(
cell_grid: wp.uint64,
face_ijk: wp.array(dtype=wp.vec3i),
face_flags: wp.array(dtype=wp.uint8),
boundary_face_mask: wp.array(dtype=int),
):
face = wp.tid()
axis, ijk = _extract_axis_flag(face_ijk[face])
ijk_minus = ijk
ijk_minus[axis] -= 1
plus_cell_index = wp.volume_lookup_index(cell_grid, ijk[0], ijk[1], ijk[2])
minus_cell_index = wp.volume_lookup_index(cell_grid, ijk_minus[0], ijk_minus[1], ijk_minus[2])
plus_boundary = wp.uint8(wp.select(plus_cell_index == -1, 0, 1)) << FACE_OUTER_OFFSET_BIT
minus_boundary = wp.uint8(wp.select(minus_cell_index == -1, 0, 1)) << FACE_INNER_OFFSET_BIT
face_ijk[face] = ijk
face_flags[face] = wp.uint8(axis) | plus_boundary | minus_boundary
boundary_face_mask[face] = wp.select((plus_boundary | minus_boundary) == 0, 1, 0)
| 15,902 | Python | 33.875 | 120 | 0.629229 |
NVIDIA/warp/warp/fem/geometry/deformed_geometry.py | from typing import Any
import warp as wp
from warp.fem import cache
from warp.fem.types import Coords, ElementIndex, Sample, make_free_sample
from .geometry import Geometry
_mat32 = wp.mat(shape=(3, 2), dtype=float)
class DeformedGeometry(Geometry):
def __init__(self, field):
"""Constructs a Deformed Geometry from a displacement field defined over a base geometry"""
from warp.fem.field import DiscreteField
self.field: DiscreteField = field
self.base = self.field.space.geometry
self.dimension = self.base.dimension
if not wp.types.type_is_vector(field.dtype) or wp.types.type_length(field.dtype) != self.dimension:
raise ValueError("Invalid value type for position field")
self.CellArg = self.field.ElementEvalArg
self.field_trace = field.trace()
self.SideArg = self._make_side_arg()
self.SideIndexArg = self.base.SideIndexArg
self.cell_count = self.base.cell_count
self.vertex_count = self.base.vertex_count
self.side_count = self.base.side_count
self.boundary_side_count = self.base.boundary_side_count
self.reference_cell = self.base.reference_cell
self.reference_side = self.base.reference_side
self.side_index_arg_value = self.base.side_index_arg_value
self.cell_position = self._make_cell_position()
self.cell_deformation_gradient = self._make_cell_deformation_gradient()
self.cell_inverse_deformation_gradient = self._make_cell_inverse_deformation_gradient()
self.cell_measure = self._make_cell_measure()
self.boundary_side_index = self.base.boundary_side_index
self.side_to_cell_arg = self._make_side_to_cell_arg()
self.side_position = self._make_side_position()
self.side_deformation_gradient = self._make_side_deformation_gradient()
self.side_inner_cell_index = self._make_side_inner_cell_index()
self.side_outer_cell_index = self._make_side_outer_cell_index()
self.side_inner_cell_coords = self._make_side_inner_cell_coords()
self.side_outer_cell_coords = self._make_side_outer_cell_coords()
self.side_from_cell_coords = self._make_side_from_cell_coords()
self.side_inner_inverse_deformation_gradient = self._make_side_inner_inverse_deformation_gradient()
self.side_outer_inverse_deformation_gradient = self._make_side_outer_inverse_deformation_gradient()
self.side_measure = self._make_side_measure()
self.side_measure_ratio = self._make_side_measure_ratio()
self.side_normal = self._make_side_normal()
@property
def name(self):
return f"DefGeo_{self.field.name}"
# Geometry device interface
@cache.cached_arg_value
def cell_arg_value(self, device) -> "DeformedGeometry.CellArg":
args = self.CellArg()
args.elt_arg = self.base.cell_arg_value(device)
args.eval_arg = self.field.eval_arg_value(device)
return args
def _make_cell_position(self):
@cache.dynamic_func(suffix=self.name)
def cell_position(cell_arg: self.CellArg, s: Sample):
return self.field.eval_inner(cell_arg, s) + self.base.cell_position(cell_arg.elt_arg, s)
return cell_position
def _make_cell_deformation_gradient(self):
@cache.dynamic_func(suffix=self.name)
def cell_deformation_gradient(cell_arg: self.CellArg, s: Sample):
return self.field.eval_reference_grad_inner(cell_arg, s) + self.base.cell_deformation_gradient(
cell_arg.elt_arg, s
)
return cell_deformation_gradient
def _make_cell_inverse_deformation_gradient(self):
@cache.dynamic_func(suffix=self.name)
def cell_inverse_deformation_gradient(cell_arg: self.CellArg, s: Sample):
return wp.inverse(self.cell_deformation_gradient(cell_arg, s))
return cell_inverse_deformation_gradient
def _make_cell_measure(self):
REF_MEASURE = wp.constant(self.reference_cell().measure())
@cache.dynamic_func(suffix=self.name)
def cell_measure(args: self.CellArg, s: Sample):
return wp.abs(wp.determinant(self.cell_deformation_gradient(args, s))) * REF_MEASURE
return cell_measure
@wp.func
def cell_normal(args: Any, s: Sample):
return wp.vec2(0.0)
def _make_side_arg(self):
@cache.dynamic_struct(suffix=self.name)
class SideArg:
base_arg: self.base.SideArg
trace_arg: self.field_trace.EvalArg
field_arg: self.field.EvalArg
return SideArg
@cache.cached_arg_value
def side_arg_value(self, device) -> "DeformedGeometry.SideArg":
args = self.SideArg()
args.base_arg = self.base.side_arg_value(device)
args.field_arg = self.field.eval_arg_value(device)
args.trace_arg = self.field_trace.eval_arg_value(device)
return args
def _make_side_position(self):
@cache.dynamic_func(suffix=self.name)
def side_position(args: self.SideArg, s: Sample):
trace_arg = self.field_trace.ElementEvalArg(args.base_arg, args.trace_arg)
return self.field_trace.eval_inner(trace_arg, s) + self.base.side_position(args.base_arg, s)
return side_position
def _make_side_deformation_gradient(self):
@cache.dynamic_func(suffix=self.name)
def side_deformation_gradient(args: self.SideArg, s: Sample):
base_def_grad = self.base.side_deformation_gradient(args.base_arg, s)
trace_arg = self.field_trace.ElementEvalArg(args.base_arg, args.trace_arg)
Du = self.field_trace.eval_grad_inner(trace_arg, s)
return base_def_grad + Du * base_def_grad
return side_deformation_gradient
def _make_side_inner_inverse_deformation_gradient(self):
@cache.dynamic_func(suffix=self.name)
def side_inner_inverse_deformation_gradient(args: self.SideArg, s: Sample):
cell_index = self.side_inner_cell_index(args, s.element_index)
cell_coords = self.side_inner_cell_coords(args, s.element_index, s.element_coords)
cell_arg = self.side_to_cell_arg(args)
return self.cell_inverse_deformation_gradient(cell_arg, make_free_sample(cell_index, cell_coords))
def _make_side_outer_inverse_deformation_gradient(self):
@cache.dynamic_func(suffix=self.name)
def side_outer_inverse_deformation_gradient(args: self.SideArg, s: Sample):
cell_index = self.side_outer_cell_index(args, s.element_index)
cell_coords = self.side_outer_cell_coords(args, s.element_index, s.element_coords)
cell_arg = self.side_to_cell_arg(args)
return self.cell_inverse_deformation_gradient(cell_arg, make_free_sample(cell_index, cell_coords))
@wp.func
def _side_measure(F: wp.vec2):
return wp.length(F)
@wp.func
def _side_measure(F: _mat32):
Fcross = wp.vec3(
F[1, 0] * F[2, 1] - F[2, 0] * F[1, 1],
F[2, 0] * F[0, 1] - F[0, 0] * F[2, 1],
F[0, 0] * F[1, 1] - F[1, 0] * F[0, 1],
)
return wp.length(Fcross)
@wp.func
def _side_normal(F: wp.vec2):
return wp.normalize(wp.vec2(-F[1], F[0]))
@wp.func
def _side_normal(F: _mat32):
Fcross = wp.vec3(
F[1, 0] * F[2, 1] - F[2, 0] * F[1, 1],
F[2, 0] * F[0, 1] - F[0, 0] * F[2, 1],
F[0, 0] * F[1, 1] - F[1, 0] * F[0, 1],
)
return wp.normalize(Fcross)
def _make_side_measure(self):
REF_MEASURE = wp.constant(self.reference_side().measure())
@cache.dynamic_func(suffix=self.name)
def side_measure(args: self.SideArg, s: Sample):
F = self.side_deformation_gradient(args, s)
return DeformedGeometry._side_measure(F) * REF_MEASURE
return side_measure
def _make_side_measure_ratio(self):
@cache.dynamic_func(suffix=self.name)
def side_measure_ratio(args: self.SideArg, s: Sample):
inner = self.side_inner_cell_index(args, s.element_index)
outer = self.side_outer_cell_index(args, s.element_index)
inner_coords = self.side_inner_cell_coords(args, s.element_index, s.element_coords)
outer_coords = self.side_outer_cell_coords(args, s.element_index, s.element_coords)
cell_arg = self.side_to_cell_arg(args)
return self.side_measure(args, s) / wp.min(
self.cell_measure(cell_arg, make_free_sample(inner, inner_coords)),
self.cell_measure(cell_arg, make_free_sample(outer, outer_coords)),
)
return side_measure_ratio
def _make_side_normal(self):
@cache.dynamic_func(suffix=self.name)
def side_normal(args: self.SideArg, s: Sample):
F = self.side_deformation_gradient(args, s)
return DeformedGeometry._side_normal(F)
return side_normal
def _make_side_inner_cell_index(self):
@cache.dynamic_func(suffix=self.name)
def side_inner_cell_index(args: self.SideArg, side_index: ElementIndex):
return self.base.side_inner_cell_index(args.base_arg, side_index)
return side_inner_cell_index
def _make_side_outer_cell_index(self):
@cache.dynamic_func(suffix=self.name)
def side_outer_cell_index(args: self.SideArg, side_index: ElementIndex):
return self.base.side_outer_cell_index(args.base_arg, side_index)
return side_outer_cell_index
def _make_side_inner_cell_coords(self):
@cache.dynamic_func(suffix=self.name)
def side_inner_cell_coords(args: self.SideArg, side_index: ElementIndex, side_coords: Coords):
return self.base.side_inner_cell_coords(args.base_arg, side_index, side_coords)
return side_inner_cell_coords
def _make_side_outer_cell_coords(self):
@cache.dynamic_func(suffix=self.name)
def side_outer_cell_coords(args: self.SideArg, side_index: ElementIndex, side_coords: Coords):
return self.base.side_outer_cell_coords(args.base_arg, side_index, side_coords)
return side_outer_cell_coords
def _make_side_from_cell_coords(self):
@cache.dynamic_func(suffix=self.name)
def side_from_cell_coords(
args: self.SideArg,
side_index: ElementIndex,
cell_index: ElementIndex,
cell_coords: Coords,
):
return self.base.side_from_cell_coords(args.base_arg, side_index, cell_index, cell_coords)
return side_from_cell_coords
def _make_side_to_cell_arg(self):
@cache.dynamic_func(suffix=self.name)
def side_to_cell_arg(side_arg: self.SideArg):
return self.CellArg(self.base.side_to_cell_arg(side_arg.base_arg), side_arg.field_arg)
return side_to_cell_arg
| 10,929 | Python | 39.332103 | 110 | 0.639949 |
NVIDIA/warp/warp/fem/geometry/grid_2d.py | from typing import Optional
import warp as wp
from warp.fem.cache import cached_arg_value
from warp.fem.types import OUTSIDE, Coords, ElementIndex, Sample, make_free_sample
from .element import LinearEdge, Square
from .geometry import Geometry
@wp.struct
class Grid2DCellArg:
res: wp.vec2i
cell_size: wp.vec2
origin: wp.vec2
class Grid2D(Geometry):
"""Two-dimensional regular grid geometry"""
dimension = 2
Permutation = wp.types.matrix(shape=(2, 2), dtype=int)
ROTATION = wp.constant(Permutation(0, 1, 1, 0))
def __init__(self, res: wp.vec2i, bounds_lo: Optional[wp.vec2] = None, bounds_hi: Optional[wp.vec2] = None):
"""Constructs a dense 2D grid
Args:
res: Resolution of the grid along each dimension
bounds_lo: Position of the lower bound of the axis-aligned grid
bounds_up: Position of the upper bound of the axis-aligned grid
"""
if bounds_lo is None:
bounds_lo = wp.vec2(0.0)
if bounds_hi is None:
bounds_hi = wp.vec2(1.0)
self.bounds_lo = bounds_lo
self.bounds_hi = bounds_hi
self._res = res
@property
def extents(self) -> wp.vec3:
# Avoid using native sub due to higher over of calling builtins from Python
return wp.vec2(
self.bounds_hi[0] - self.bounds_lo[0],
self.bounds_hi[1] - self.bounds_lo[1],
)
@property
def cell_size(self) -> wp.vec2:
ex = self.extents
return wp.vec2(
ex[0] / self.res[0],
ex[1] / self.res[1],
)
def cell_count(self):
return self.res[0] * self.res[1]
def vertex_count(self):
return (self.res[0] + 1) * (self.res[1] + 1)
def side_count(self):
return 2 * self.cell_count() + self.res[0] + self.res[1]
def boundary_side_count(self):
return 2 * (self.res[0] + self.res[1])
def reference_cell(self) -> Square:
return Square()
def reference_side(self) -> LinearEdge:
return LinearEdge()
@property
def res(self):
return self._res
@property
def origin(self):
return self.bounds_lo
@property
def strides(self):
return wp.vec2i(self.res[1], 1)
# Utility device functions
CellArg = Grid2DCellArg
Cell = wp.vec2i
@wp.func
def _to_2d_index(x_stride: int, index: int):
x = index // x_stride
y = index - x_stride * x
return wp.vec2i(x, y)
@wp.func
def _from_2d_index(x_stride: int, index: wp.vec2i):
return x_stride * index[0] + index[1]
@wp.func
def cell_index(res: wp.vec2i, cell: Cell):
return Grid2D._from_2d_index(res[1], cell)
@wp.func
def get_cell(res: wp.vec2i, cell_index: ElementIndex):
return Grid2D._to_2d_index(res[1], cell_index)
@wp.struct
class Side:
axis: int # normal; 0: horizontal, 1: vertical
origin: wp.vec2i # index of vertex at corner (0,0)
@wp.struct
class SideArg:
cell_count: int
axis_offsets: wp.vec2i
cell_arg: Grid2DCellArg
SideIndexArg = SideArg
@wp.func
def _rotate(axis: int, vec: wp.vec2i):
return wp.vec2i(
vec[Grid2D.ROTATION[axis, 0]],
vec[Grid2D.ROTATION[axis, 1]],
)
@wp.func
def _rotate(axis: int, vec: wp.vec2):
return wp.vec2(
vec[Grid2D.ROTATION[axis, 0]],
vec[Grid2D.ROTATION[axis, 1]],
)
@wp.func
def side_index(arg: SideArg, side: Side):
alt_axis = Grid2D.ROTATION[side.axis, 0]
if side.origin[0] == arg.cell_arg.res[alt_axis]:
# Upper-boundary side
longitude = side.origin[1]
return 2 * arg.cell_count + arg.axis_offsets[side.axis] + longitude
cell_index = Grid2D.cell_index(arg.cell_arg.res, Grid2D._rotate(side.axis, side.origin))
return side.axis * arg.cell_count + cell_index
@wp.func
def get_side(arg: SideArg, side_index: ElementIndex):
if side_index < 2 * arg.cell_count:
axis = side_index // arg.cell_count
cell_index = side_index - axis * arg.cell_count
origin = Grid2D._rotate(axis, Grid2D.get_cell(arg.cell_arg.res, cell_index))
return Grid2D.Side(axis, origin)
axis_side_index = side_index - 2 * arg.cell_count
if axis_side_index < arg.axis_offsets[1]:
axis = 0
else:
axis = 1
altitude = arg.cell_arg.res[Grid2D.ROTATION[axis, 0]]
longitude = axis_side_index - arg.axis_offsets[axis]
origin_loc = wp.vec2i(altitude, longitude)
return Grid2D.Side(axis, origin_loc)
# Geometry device interface
@cached_arg_value
def cell_arg_value(self, device) -> CellArg:
args = self.CellArg()
args.res = self.res
args.cell_size = self.cell_size
args.origin = self.bounds_lo
return args
@wp.func
def cell_position(args: CellArg, s: Sample):
cell = Grid2D.get_cell(args.res, s.element_index)
return (
wp.vec2(
(float(cell[0]) + s.element_coords[0]) * args.cell_size[0],
(float(cell[1]) + s.element_coords[1]) * args.cell_size[1],
)
+ args.origin
)
@wp.func
def cell_deformation_gradient(args: CellArg, s: Sample):
return wp.diag(args.cell_size)
@wp.func
def cell_inverse_deformation_gradient(args: CellArg, s: Sample):
return wp.diag(wp.cw_div(wp.vec2(1.0), args.cell_size))
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec2):
loc_pos = wp.cw_div(pos - args.origin, args.cell_size)
x = wp.clamp(loc_pos[0], 0.0, float(args.res[0]))
y = wp.clamp(loc_pos[1], 0.0, float(args.res[1]))
x_cell = wp.min(wp.floor(x), float(args.res[0]) - 1.0)
y_cell = wp.min(wp.floor(y), float(args.res[1]) - 1.0)
coords = Coords(x - x_cell, y - y_cell, 0.0)
cell_index = Grid2D.cell_index(args.res, Grid2D.Cell(int(x_cell), int(y_cell)))
return make_free_sample(cell_index, coords)
@wp.func
def cell_lookup(args: CellArg, pos: wp.vec2, guess: Sample):
return Grid2D.cell_lookup(args, pos)
@wp.func
def cell_measure(args: CellArg, s: Sample):
return args.cell_size[0] * args.cell_size[1]
@wp.func
def cell_normal(args: CellArg, s: Sample):
return wp.vec2(0.0)
@cached_arg_value
def side_arg_value(self, device) -> SideArg:
args = self.SideArg()
args.axis_offsets = wp.vec2i(
0,
self.res[0],
)
args.cell_count = self.cell_count()
args.cell_arg = self.cell_arg_value(device)
return args
def side_index_arg_value(self, device) -> SideIndexArg:
return self.side_arg_value(device)
@wp.func
def boundary_side_index(args: SideArg, boundary_side_index: int):
"""Boundary side to side index"""
axis_side_index = boundary_side_index // 2
border = boundary_side_index - 2 * axis_side_index
if axis_side_index < args.axis_offsets[1]:
axis = 0
else:
axis = 1
longitude = axis_side_index - args.axis_offsets[axis]
altitude = border * args.cell_arg.res[axis]
side = Grid2D.Side(axis, wp.vec2i(altitude, longitude))
return Grid2D.side_index(args, side)
@wp.func
def side_position(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
coord = wp.select((side.origin[0] == 0) == (side.axis == 0), 1.0 - s.element_coords[0], s.element_coords[0])
local_pos = wp.vec2(
float(side.origin[0]),
float(side.origin[1]) + coord,
)
pos = args.cell_arg.origin + wp.cw_mul(Grid2D._rotate(side.axis, local_pos), args.cell_arg.cell_size)
return pos
@wp.func
def side_deformation_gradient(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
sign = wp.select((side.origin[0] == 0) == (side.axis == 0), -1.0, 1.0)
return wp.cw_mul(Grid2D._rotate(side.axis, wp.vec2(0.0, sign)), args.cell_arg.cell_size)
@wp.func
def side_inner_inverse_deformation_gradient(args: SideArg, s: Sample):
return Grid2D.cell_inverse_deformation_gradient(args.cell_arg, s)
@wp.func
def side_outer_inverse_deformation_gradient(args: SideArg, s: Sample):
return Grid2D.cell_inverse_deformation_gradient(args.cell_arg, s)
@wp.func
def side_measure(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
long_axis = Grid2D.ROTATION[side.axis, 1]
return args.cell_arg.cell_size[long_axis]
@wp.func
def side_measure_ratio(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
alt_axis = Grid2D.ROTATION[side.axis, 0]
return 1.0 / args.cell_arg.cell_size[alt_axis]
@wp.func
def side_normal(args: SideArg, s: Sample):
side = Grid2D.get_side(args, s.element_index)
sign = wp.select(side.origin[0] == 0, 1.0, -1.0)
local_n = wp.vec2(sign, 0.0)
return Grid2D._rotate(side.axis, local_n)
@wp.func
def side_inner_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid2D.get_side(arg, side_index)
inner_alt = wp.select(side.origin[0] == 0, side.origin[0] - 1, 0)
inner_origin = wp.vec2i(inner_alt, side.origin[1])
cell = Grid2D._rotate(side.axis, inner_origin)
return Grid2D.cell_index(arg.cell_arg.res, cell)
@wp.func
def side_outer_cell_index(arg: SideArg, side_index: ElementIndex):
side = Grid2D.get_side(arg, side_index)
alt_axis = Grid2D.ROTATION[side.axis, 0]
outer_alt = wp.select(
side.origin[0] == arg.cell_arg.res[alt_axis], side.origin[0], arg.cell_arg.res[alt_axis] - 1
)
outer_origin = wp.vec2i(outer_alt, side.origin[1])
cell = Grid2D._rotate(side.axis, outer_origin)
return Grid2D.cell_index(arg.cell_arg.res, cell)
@wp.func
def side_inner_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
side = Grid2D.get_side(args, side_index)
inner_alt = wp.select(side.origin[0] == 0, 1.0, 0.0)
side_coord = wp.select((side.origin[0] == 0) == (side.axis == 0), 1.0 - side_coords[0], side_coords[0])
coords = Grid2D._rotate(side.axis, wp.vec2(inner_alt, side_coord))
return Coords(coords[0], coords[1], 0.0)
@wp.func
def side_outer_cell_coords(args: SideArg, side_index: ElementIndex, side_coords: Coords):
side = Grid2D.get_side(args, side_index)
alt_axis = Grid2D.ROTATION[side.axis, 0]
outer_alt = wp.select(side.origin[0] == args.cell_arg.res[alt_axis], 0.0, 1.0)
side_coord = wp.select((side.origin[0] == 0) == (side.axis == 0), 1.0 - side_coords[0], side_coords[0])
coords = Grid2D._rotate(side.axis, wp.vec2(outer_alt, side_coord))
return Coords(coords[0], coords[1], 0.0)
@wp.func
def side_from_cell_coords(
args: SideArg,
side_index: ElementIndex,
element_index: ElementIndex,
element_coords: Coords,
):
side = Grid2D.get_side(args, side_index)
cell = Grid2D.get_cell(args.cell_arg.res, element_index)
if float(side.origin[0] - cell[side.axis]) == element_coords[side.axis]:
long_axis = Grid2D.ROTATION[side.axis, 1]
axis_coord = element_coords[long_axis]
side_coord = wp.select((side.origin[0] == 0) == (side.axis == 0), 1.0 - axis_coord, axis_coord)
return Coords(side_coord, 0.0, 0.0)
return Coords(OUTSIDE)
@wp.func
def side_to_cell_arg(side_arg: SideArg):
return side_arg.cell_arg
| 11,950 | Python | 30.367454 | 116 | 0.591799 |
NVIDIA/warp/warp/fem/geometry/element.py | from typing import List, Tuple
from warp.fem.polynomial import Polynomial, quadrature_1d
from warp.fem.types import Coords
class Element:
def measure() -> float:
"""Measure (area, volume, ...) of the reference element"""
raise NotImplementedError
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial) -> Tuple[List[Coords], List[float]]:
"""Returns a quadrature of a given order for a prototypical element"""
raise NotImplementedError
def center(self) -> Tuple[float]:
coords, _ = self.instantiate_quadrature(order=0, family=None)
return coords[0]
def _point_count_from_order(order: int, family: Polynomial):
if family == Polynomial.GAUSS_LEGENDRE:
point_count = max(1, order // 2 + 1)
elif family == Polynomial.LOBATTO_GAUSS_LEGENDRE:
point_count = max(2, order // 2 + 2)
elif family == Polynomial.EQUISPACED_CLOSED:
point_count = max(2, 2 * (order // 2) + 1)
elif family == Polynomial.EQUISPACED_OPEN:
point_count = max(1, 2 * (order // 2) + 1)
return point_count
class Cube(Element):
@staticmethod
def measure() -> float:
return 1.0
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is None:
family = Polynomial.GAUSS_LEGENDRE
point_count = _point_count_from_order(order=order, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(x, y, z) for x in gauss_1d for y in gauss_1d for z in gauss_1d]
weights = [wx * wy * wz for wx in weights_1d for wy in weights_1d for wz in weights_1d]
return coords, weights
class Square(Element):
@staticmethod
def measure() -> float:
return 1.0
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is None:
family = Polynomial.GAUSS_LEGENDRE
point_count = _point_count_from_order(order=order, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(x, y, 0.0) for x in gauss_1d for y in gauss_1d]
weights = [wx * wy for wx in weights_1d for wy in weights_1d]
return coords, weights
class LinearEdge(Element):
@staticmethod
def measure() -> float:
return 1.0
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is None:
family = Polynomial.GAUSS_LEGENDRE
point_count = _point_count_from_order(order=order, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(x, 0.0, 0.0) for x in gauss_1d]
return coords, weights_1d
class Triangle(Element):
@staticmethod
def measure() -> float:
return 0.5
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is not None:
# Duffy transformation from square to triangle
point_count = _point_count_from_order(order=order + 1, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [Coords(1.0 - x - y + x * y, x, y * (1.0 - x)) for x in gauss_1d for y in gauss_1d]
# Scale weight by 2.0 so that they sum up to 1
weights = [2.0 * wx * (1.0 - x) * wy for x, wx in zip(gauss_1d, weights_1d) for wy in weights_1d]
return coords, weights
if order <= 1:
weights = [1.0]
coords = [Coords(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0)]
elif order <= 2:
weights = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0]
coords = [
Coords(2.0 / 3.0, 1.0 / 6.0, 1.0 / 6.0),
Coords(1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0),
Coords(1.0 / 6.0, 1.0 / 6.0, 2.0 / 3.0),
]
elif order <= 3:
# Hillion 1977,
# "Numerical Integration on a Triangle"
weights = [
3.18041381743977225049491153185954e-01,
3.18041381743977225049491153185954e-01,
1.81958618256022719439357615556219e-01,
1.81958618256022719439357615556219e-01,
]
coords = [
Coords(
6.66390246014701426169324349757517e-01,
1.78558728263616461884311092944699e-01,
1.55051025721682111946364557297784e-01,
),
Coords(
1.78558728263616461884311092944699e-01,
6.66390246014701426169324349757517e-01,
1.55051025721682056435213326039957e-01,
),
Coords(
2.80019915499074012465996474929852e-01,
7.50311102226081383381739442484104e-02,
6.44948974278317876951405196450651e-01,
),
Coords(
7.50311102226081383381739442484104e-02,
2.80019915499074012465996474929852e-01,
6.44948974278317876951405196450651e-01,
),
]
elif order <= 4:
# Witherden and Vincent 2015,
# "On the identification of symmetric quadrature rules for finite element methods"
# https://doi.org/10.1016/j.camwa.2015.03.017
weights = [
2.23381589678011471811203136894619e-01,
2.23381589678011471811203136894619e-01,
2.23381589678011471811203136894619e-01,
1.09951743655321870773988734981685e-01,
1.09951743655321870773988734981685e-01,
1.09951743655321870773988734981685e-01,
]
coords = [
Coords(
4.45948490915964890213274429697776e-01,
4.45948490915964890213274429697776e-01,
1.08103018168070219573451140604448e-01,
),
Coords(
4.45948490915964890213274429697776e-01,
1.08103018168070219573451140604448e-01,
4.45948490915964890213274429697776e-01,
),
Coords(
1.08103018168070219573451140604448e-01,
4.45948490915964890213274429697776e-01,
4.45948490915964890213274429697776e-01,
),
Coords(
9.15762135097707430375635340169538e-02,
9.15762135097707430375635340169538e-02,
8.16847572980458513924872931966092e-01,
),
Coords(
9.15762135097707430375635340169538e-02,
8.16847572980458513924872931966092e-01,
9.15762135097707430375635340169538e-02,
),
Coords(
8.16847572980458513924872931966092e-01,
9.15762135097707430375635340169538e-02,
9.15762135097707430375635340169538e-02,
),
]
elif order <= 5:
weights = [
2.25000000000000005551115123125783e-01,
1.25939180544827139529573400977824e-01,
1.25939180544827139529573400977824e-01,
1.25939180544827139529573400977824e-01,
1.32394152788506191953388224646915e-01,
1.32394152788506191953388224646915e-01,
1.32394152788506191953388224646915e-01,
]
coords = [
Coords(
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
),
Coords(
1.01286507323456342888334802410100e-01,
1.01286507323456342888334802410100e-01,
7.97426985353087314223330395179801e-01,
),
Coords(
1.01286507323456342888334802410100e-01,
7.97426985353087314223330395179801e-01,
1.01286507323456342888334802410100e-01,
),
Coords(
7.97426985353087314223330395179801e-01,
1.01286507323456342888334802410100e-01,
1.01286507323456342888334802410100e-01,
),
Coords(
4.70142064105115109473587153843255e-01,
4.70142064105115109473587153843255e-01,
5.97158717897697810528256923134904e-02,
),
Coords(
4.70142064105115109473587153843255e-01,
5.97158717897697810528256923134904e-02,
4.70142064105115109473587153843255e-01,
),
Coords(
5.97158717897697810528256923134904e-02,
4.70142064105115109473587153843255e-01,
4.70142064105115109473587153843255e-01,
),
]
elif order <= 6:
weights = [
5.08449063702068326797700592578622e-02,
5.08449063702068326797700592578622e-02,
5.08449063702068326797700592578622e-02,
1.16786275726379396022736045779311e-01,
1.16786275726379396022736045779311e-01,
1.16786275726379396022736045779311e-01,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
8.28510756183735846969184990484791e-02,
]
coords = [
Coords(
6.30890144915022266225435032538371e-02,
6.30890144915022266225435032538371e-02,
8.73821971016995546754912993492326e-01,
),
Coords(
6.30890144915022266225435032538371e-02,
8.73821971016995546754912993492326e-01,
6.30890144915022266225435032538371e-02,
),
Coords(
8.73821971016995546754912993492326e-01,
6.30890144915022266225435032538371e-02,
6.30890144915022266225435032538371e-02,
),
Coords(
2.49286745170910428726074314909056e-01,
2.49286745170910428726074314909056e-01,
5.01426509658179142547851370181888e-01,
),
Coords(
2.49286745170910428726074314909056e-01,
5.01426509658179142547851370181888e-01,
2.49286745170910428726074314909056e-01,
),
Coords(
5.01426509658179142547851370181888e-01,
2.49286745170910428726074314909056e-01,
2.49286745170910428726074314909056e-01,
),
Coords(
5.31450498448169383891581674106419e-02,
3.10352451033784393352732422499685e-01,
6.36502499121398668258109410089673e-01,
),
Coords(
5.31450498448169383891581674106419e-02,
6.36502499121398668258109410089673e-01,
3.10352451033784393352732422499685e-01,
),
Coords(
3.10352451033784393352732422499685e-01,
5.31450498448169383891581674106419e-02,
6.36502499121398668258109410089673e-01,
),
Coords(
3.10352451033784393352732422499685e-01,
6.36502499121398668258109410089673e-01,
5.31450498448169383891581674106419e-02,
),
Coords(
6.36502499121398668258109410089673e-01,
5.31450498448169383891581674106419e-02,
3.10352451033784393352732422499685e-01,
),
Coords(
6.36502499121398668258109410089673e-01,
3.10352451033784393352732422499685e-01,
5.31450498448169383891581674106419e-02,
),
]
else:
# Order 8
weights = [
1.44315607677787172136163462710101e-01,
9.50916342672846193195823616406415e-02,
9.50916342672846193195823616406415e-02,
9.50916342672846193195823616406415e-02,
1.03217370534718244634575512463925e-01,
1.03217370534718244634575512463925e-01,
1.03217370534718244634575512463925e-01,
3.24584976231980792960030157701112e-02,
3.24584976231980792960030157701112e-02,
3.24584976231980792960030157701112e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
2.72303141744349927466650740370824e-02,
]
coords = [
Coords(
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
3.33333333333333314829616256247391e-01,
),
Coords(
4.59292588292723125142913431773195e-01,
4.59292588292723125142913431773195e-01,
8.14148234145537497141731364536099e-02,
),
Coords(
4.59292588292723125142913431773195e-01,
8.14148234145537497141731364536099e-02,
4.59292588292723125142913431773195e-01,
),
Coords(
8.14148234145537497141731364536099e-02,
4.59292588292723125142913431773195e-01,
4.59292588292723125142913431773195e-01,
),
Coords(
1.70569307751760212976677166807349e-01,
1.70569307751760212976677166807349e-01,
6.58861384496479574046645666385302e-01,
),
Coords(
1.70569307751760212976677166807349e-01,
6.58861384496479574046645666385302e-01,
1.70569307751760212976677166807349e-01,
),
Coords(
6.58861384496479574046645666385302e-01,
1.70569307751760212976677166807349e-01,
1.70569307751760212976677166807349e-01,
),
Coords(
5.05472283170309566457945038564503e-02,
5.05472283170309566457945038564503e-02,
8.98905543365938086708410992287099e-01,
),
Coords(
5.05472283170309566457945038564503e-02,
8.98905543365938086708410992287099e-01,
5.05472283170309566457945038564503e-02,
),
Coords(
8.98905543365938086708410992287099e-01,
5.05472283170309566457945038564503e-02,
5.05472283170309566457945038564503e-02,
),
Coords(
8.39477740995758781039626228448469e-03,
2.63112829634638112352718053443823e-01,
7.28492392955404355348036915529519e-01,
),
Coords(
8.39477740995758781039626228448469e-03,
7.28492392955404355348036915529519e-01,
2.63112829634638112352718053443823e-01,
),
Coords(
2.63112829634638112352718053443823e-01,
8.39477740995758781039626228448469e-03,
7.28492392955404355348036915529519e-01,
),
Coords(
2.63112829634638112352718053443823e-01,
7.28492392955404355348036915529519e-01,
8.39477740995758781039626228448469e-03,
),
Coords(
7.28492392955404355348036915529519e-01,
8.39477740995758781039626228448469e-03,
2.63112829634638112352718053443823e-01,
),
Coords(
7.28492392955404355348036915529519e-01,
2.63112829634638112352718053443823e-01,
8.39477740995758781039626228448469e-03,
),
]
return coords, weights
class Tetrahedron(Element):
@staticmethod
def measure() -> float:
return 1.0 / 6.0
@staticmethod
def instantiate_quadrature(order: int, family: Polynomial):
if family is not None:
# Duffy transformation from square to triangle
point_count = _point_count_from_order(order=order + 1, family=family)
gauss_1d, weights_1d = quadrature_1d(point_count=point_count, family=family)
coords = [
Coords(x, y * (1.0 - x), z * (1.0 - x) * (1.0 - y))
for x in gauss_1d
for y in gauss_1d
for z in gauss_1d
]
# Scale weight by 6.0 so that they sum up to 1
weights = [
6.0 * wx * wy * wz * (1.0 - x) * (1.0 - x) * (1.0 - y)
for x, wx in zip(gauss_1d, weights_1d)
for y, wy in zip(gauss_1d, weights_1d)
for wz in weights_1d
]
return coords, weights
# Shunn and Ham 2012
# "Symmetric quadrature rules for tetrahedra based on a cubic close-packed lattice arrangement"
# https://doi.org/10.1016/j.cam.2012.03.032
# TODO: add Witherden and Vincent 2015,
if order <= 1:
weights = [1.0]
coords = [Coords(1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0)]
elif order <= 2:
weights = [1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0, 1.0 / 4.0]
coords = [
Coords(0.1381966011250110, 0.1381966011250110, 0.1381966011250110),
Coords(0.5854101966249680, 0.1381966011250110, 0.1381966011250110),
Coords(0.1381966011250110, 0.5854101966249680, 0.1381966011250110),
Coords(0.1381966011250110, 0.1381966011250110, 0.5854101966249680),
]
elif order <= 3:
weights = [
0.0476331348432089,
0.0476331348432089,
0.0476331348432089,
0.0476331348432089,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
0.1349112434378610,
]
coords = [
Coords(0.0738349017262234, 0.0738349017262234, 0.0738349017262234),
Coords(0.7784952948213300, 0.0738349017262234, 0.0738349017262234),
Coords(0.0738349017262234, 0.7784952948213300, 0.0738349017262234),
Coords(0.0738349017262234, 0.0738349017262234, 0.7784952948213300),
Coords(0.4062443438840510, 0.0937556561159491, 0.0937556561159491),
Coords(0.0937556561159491, 0.4062443438840510, 0.0937556561159491),
Coords(0.0937556561159491, 0.0937556561159491, 0.4062443438840510),
Coords(0.4062443438840510, 0.4062443438840510, 0.0937556561159491),
Coords(0.4062443438840510, 0.0937556561159491, 0.4062443438840510),
Coords(0.0937556561159491, 0.4062443438840510, 0.4062443438840510),
]
elif order <= 4:
weights = [
0.0070670747944695,
0.0070670747944695,
0.0070670747944695,
0.0070670747944695,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.0469986689718877,
0.1019369182898680,
0.1019369182898680,
0.1019369182898680,
0.1019369182898680,
]
coords = [
Coords(0.0323525947272439, 0.0323525947272439, 0.0323525947272439),
Coords(0.9029422158182680, 0.0323525947272439, 0.0323525947272439),
Coords(0.0323525947272439, 0.9029422158182680, 0.0323525947272439),
Coords(0.0323525947272439, 0.0323525947272439, 0.9029422158182680),
Coords(0.6165965330619370, 0.0603604415251421, 0.0603604415251421),
Coords(0.2626825838877790, 0.0603604415251421, 0.0603604415251421),
Coords(0.0603604415251421, 0.6165965330619370, 0.0603604415251421),
Coords(0.0603604415251421, 0.2626825838877790, 0.0603604415251421),
Coords(0.0603604415251421, 0.0603604415251421, 0.6165965330619370),
Coords(0.0603604415251421, 0.0603604415251421, 0.2626825838877790),
Coords(0.2626825838877790, 0.6165965330619370, 0.0603604415251421),
Coords(0.6165965330619370, 0.2626825838877790, 0.0603604415251421),
Coords(0.2626825838877790, 0.0603604415251421, 0.6165965330619370),
Coords(0.6165965330619370, 0.0603604415251421, 0.2626825838877790),
Coords(0.0603604415251421, 0.2626825838877790, 0.6165965330619370),
Coords(0.0603604415251421, 0.6165965330619370, 0.2626825838877790),
Coords(0.3097693042728620, 0.3097693042728620, 0.0706920871814129),
Coords(0.3097693042728620, 0.0706920871814129, 0.3097693042728620),
Coords(0.0706920871814129, 0.3097693042728620, 0.3097693042728620),
Coords(0.3097693042728620, 0.3097693042728620, 0.3097693042728620),
]
elif order <= 5:
weights = [
0.0021900463965388,
0.0021900463965388,
0.0021900463965388,
0.0021900463965388,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0143395670177665,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0250305395686746,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0479839333057554,
0.0931745731195340,
]
coords = [
Coords(0.0267367755543735, 0.0267367755543735, 0.0267367755543735),
Coords(0.9197896733368800, 0.0267367755543735, 0.0267367755543735),
Coords(0.0267367755543735, 0.9197896733368800, 0.0267367755543735),
Coords(0.0267367755543735, 0.0267367755543735, 0.9197896733368800),
Coords(0.7477598884818090, 0.0391022406356488, 0.0391022406356488),
Coords(0.1740356302468940, 0.0391022406356488, 0.0391022406356488),
Coords(0.0391022406356488, 0.7477598884818090, 0.0391022406356488),
Coords(0.0391022406356488, 0.1740356302468940, 0.0391022406356488),
Coords(0.0391022406356488, 0.0391022406356488, 0.7477598884818090),
Coords(0.0391022406356488, 0.0391022406356488, 0.1740356302468940),
Coords(0.1740356302468940, 0.7477598884818090, 0.0391022406356488),
Coords(0.7477598884818090, 0.1740356302468940, 0.0391022406356488),
Coords(0.1740356302468940, 0.0391022406356488, 0.7477598884818090),
Coords(0.7477598884818090, 0.0391022406356488, 0.1740356302468940),
Coords(0.0391022406356488, 0.1740356302468940, 0.7477598884818090),
Coords(0.0391022406356488, 0.7477598884818090, 0.1740356302468940),
Coords(0.4547545999844830, 0.0452454000155172, 0.0452454000155172),
Coords(0.0452454000155172, 0.4547545999844830, 0.0452454000155172),
Coords(0.0452454000155172, 0.0452454000155172, 0.4547545999844830),
Coords(0.4547545999844830, 0.4547545999844830, 0.0452454000155172),
Coords(0.4547545999844830, 0.0452454000155172, 0.4547545999844830),
Coords(0.0452454000155172, 0.4547545999844830, 0.4547545999844830),
Coords(0.2232010379623150, 0.2232010379623150, 0.0504792790607720),
Coords(0.5031186450145980, 0.2232010379623150, 0.0504792790607720),
Coords(0.2232010379623150, 0.5031186450145980, 0.0504792790607720),
Coords(0.2232010379623150, 0.0504792790607720, 0.2232010379623150),
Coords(0.5031186450145980, 0.0504792790607720, 0.2232010379623150),
Coords(0.2232010379623150, 0.0504792790607720, 0.5031186450145980),
Coords(0.0504792790607720, 0.2232010379623150, 0.2232010379623150),
Coords(0.0504792790607720, 0.5031186450145980, 0.2232010379623150),
Coords(0.0504792790607720, 0.2232010379623150, 0.5031186450145980),
Coords(0.5031186450145980, 0.2232010379623150, 0.2232010379623150),
Coords(0.2232010379623150, 0.5031186450145980, 0.2232010379623150),
Coords(0.2232010379623150, 0.2232010379623150, 0.5031186450145980),
Coords(0.2500000000000000, 0.2500000000000000, 0.2500000000000000),
]
elif order <= 6:
weights = [
0.0010373112336140,
0.0010373112336140,
0.0010373112336140,
0.0010373112336140,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0096016645399480,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0164493976798232,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0153747766513310,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0293520118375230,
0.0366291366405108,
0.0366291366405108,
0.0366291366405108,
0.0366291366405108,
]
coords = [
Coords(0.0149520651530592, 0.0149520651530592, 0.0149520651530592),
Coords(0.9551438045408220, 0.0149520651530592, 0.0149520651530592),
Coords(0.0149520651530592, 0.9551438045408220, 0.0149520651530592),
Coords(0.0149520651530592, 0.0149520651530592, 0.9551438045408220),
Coords(0.1518319491659370, 0.0340960211962615, 0.0340960211962615),
Coords(0.7799760084415400, 0.0340960211962615, 0.0340960211962615),
Coords(0.0340960211962615, 0.1518319491659370, 0.0340960211962615),
Coords(0.0340960211962615, 0.7799760084415400, 0.0340960211962615),
Coords(0.0340960211962615, 0.0340960211962615, 0.1518319491659370),
Coords(0.0340960211962615, 0.0340960211962615, 0.7799760084415400),
Coords(0.7799760084415400, 0.1518319491659370, 0.0340960211962615),
Coords(0.1518319491659370, 0.7799760084415400, 0.0340960211962615),
Coords(0.7799760084415400, 0.0340960211962615, 0.1518319491659370),
Coords(0.1518319491659370, 0.0340960211962615, 0.7799760084415400),
Coords(0.0340960211962615, 0.7799760084415400, 0.1518319491659370),
Coords(0.0340960211962615, 0.1518319491659370, 0.7799760084415400),
Coords(0.5526556431060170, 0.0462051504150017, 0.0462051504150017),
Coords(0.3549340560639790, 0.0462051504150017, 0.0462051504150017),
Coords(0.0462051504150017, 0.5526556431060170, 0.0462051504150017),
Coords(0.0462051504150017, 0.3549340560639790, 0.0462051504150017),
Coords(0.0462051504150017, 0.0462051504150017, 0.5526556431060170),
Coords(0.0462051504150017, 0.0462051504150017, 0.3549340560639790),
Coords(0.3549340560639790, 0.5526556431060170, 0.0462051504150017),
Coords(0.5526556431060170, 0.3549340560639790, 0.0462051504150017),
Coords(0.3549340560639790, 0.0462051504150017, 0.5526556431060170),
Coords(0.5526556431060170, 0.0462051504150017, 0.3549340560639790),
Coords(0.0462051504150017, 0.3549340560639790, 0.5526556431060170),
Coords(0.0462051504150017, 0.5526556431060170, 0.3549340560639790),
Coords(0.2281904610687610, 0.2281904610687610, 0.0055147549744775),
Coords(0.5381043228880020, 0.2281904610687610, 0.0055147549744775),
Coords(0.2281904610687610, 0.5381043228880020, 0.0055147549744775),
Coords(0.2281904610687610, 0.0055147549744775, 0.2281904610687610),
Coords(0.5381043228880020, 0.0055147549744775, 0.2281904610687610),
Coords(0.2281904610687610, 0.0055147549744775, 0.5381043228880020),
Coords(0.0055147549744775, 0.2281904610687610, 0.2281904610687610),
Coords(0.0055147549744775, 0.5381043228880020, 0.2281904610687610),
Coords(0.0055147549744775, 0.2281904610687610, 0.5381043228880020),
Coords(0.5381043228880020, 0.2281904610687610, 0.2281904610687610),
Coords(0.2281904610687610, 0.5381043228880020, 0.2281904610687610),
Coords(0.2281904610687610, 0.2281904610687610, 0.5381043228880020),
Coords(0.3523052600879940, 0.3523052600879940, 0.0992057202494530),
Coords(0.1961837595745600, 0.3523052600879940, 0.0992057202494530),
Coords(0.3523052600879940, 0.1961837595745600, 0.0992057202494530),
Coords(0.3523052600879940, 0.0992057202494530, 0.3523052600879940),
Coords(0.1961837595745600, 0.0992057202494530, 0.3523052600879940),
Coords(0.3523052600879940, 0.0992057202494530, 0.1961837595745600),
Coords(0.0992057202494530, 0.3523052600879940, 0.3523052600879940),
Coords(0.0992057202494530, 0.1961837595745600, 0.3523052600879940),
Coords(0.0992057202494530, 0.3523052600879940, 0.1961837595745600),
Coords(0.1961837595745600, 0.3523052600879940, 0.3523052600879940),
Coords(0.3523052600879940, 0.1961837595745600, 0.3523052600879940),
Coords(0.3523052600879940, 0.3523052600879940, 0.1961837595745600),
Coords(0.1344783347929940, 0.1344783347929940, 0.1344783347929940),
Coords(0.5965649956210170, 0.1344783347929940, 0.1344783347929940),
Coords(0.1344783347929940, 0.5965649956210170, 0.1344783347929940),
Coords(0.1344783347929940, 0.1344783347929940, 0.5965649956210170),
]
else:
raise NotImplementedError
return coords, weights
| 34,180 | Python | 44.635514 | 109 | 0.570246 |
NVIDIA/warp/warp/fem/quadrature/quadrature.py | from typing import Any
import warp as wp
from warp.fem import cache, domain
from warp.fem.space import FunctionSpace
from warp.fem.types import Coords, ElementIndex
from ..polynomial import Polynomial
class Quadrature:
"""Interface class for quadrature rules"""
@wp.struct
class Arg:
"""Structure containing arguments to be passed to device functions"""
pass
def __init__(self, domain: domain.GeometryDomain):
self._domain = domain
@property
def domain(self):
"""Domain over which this quadrature is defined"""
return self._domain
def arg_value(self, device) -> "Arg":
"""
Value of the argument to be passed to device
"""
arg = RegularQuadrature.Arg()
return arg
def total_point_count(self):
"""Total number of quadrature points over the domain"""
raise NotImplementedError()
def points_per_element(self):
"""Number of points per element if constant, or ``None`` if varying"""
return None
@staticmethod
def point_count(elt_arg: "domain.GeometryDomain.ElementArg", qp_arg: Arg, element_index: ElementIndex):
"""Number of quadrature points for a given element"""
raise NotImplementedError()
@staticmethod
def point_coords(
elt_arg: "domain.GeometryDomain.ElementArg", qp_arg: Arg, element_index: ElementIndex, qp_index: int
):
"""Coordinates in element of the element's qp_index'th quadrature point"""
raise NotImplementedError()
@staticmethod
def point_weight(
elt_arg: "domain.GeometryDomain.ElementArg", qp_arg: Arg, element_index: ElementIndex, qp_index: int
):
"""Weight of the element's qp_index'th quadrature point"""
raise NotImplementedError()
@staticmethod
def point_index(
elt_arg: "domain.GeometryDomain.ElementArg", qp_arg: Arg, element_index: ElementIndex, qp_index: int
):
"""Global index of the element's qp_index'th quadrature point"""
raise NotImplementedError()
def __str__(self) -> str:
return self.name
class RegularQuadrature(Quadrature):
"""Regular quadrature formula, using a constant set of quadrature points per element"""
def __init__(
self,
domain: domain.GeometryDomain,
order: int,
family: Polynomial = None,
):
super().__init__(domain)
self.family = family
self.order = order
self._element_quadrature = domain.reference_element().instantiate_quadrature(order, family)
self._N = wp.constant(len(self.points))
WeightVec = wp.vec(length=self._N, dtype=wp.float32)
CoordMat = wp.mat(shape=(self._N, 3), dtype=wp.float32)
self._POINTS = wp.constant(CoordMat(self.points))
self._WEIGHTS = wp.constant(WeightVec(self.weights))
self.point_count = self._make_point_count()
self.point_index = self._make_point_index()
self.point_coords = self._make_point_coords()
self.point_weight = self._make_point_weight()
@property
def name(self):
return f"{self.__class__.__name__}_{self.domain.name}_{self.family}_{self.order}"
def total_point_count(self):
return len(self.points) * self.domain.geometry_element_count()
def points_per_element(self):
return self._N
@property
def points(self):
return self._element_quadrature[0]
@property
def weights(self):
return self._element_quadrature[1]
def _make_point_count(self):
N = self._N
@cache.dynamic_func(suffix=self.name)
def point_count(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex):
return N
return point_count
def _make_point_coords(self):
POINTS = self._POINTS
@cache.dynamic_func(suffix=self.name)
def point_coords(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex, qp_index: int):
return Coords(POINTS[qp_index, 0], POINTS[qp_index, 1], POINTS[qp_index, 2])
return point_coords
def _make_point_weight(self):
WEIGHTS = self._WEIGHTS
@cache.dynamic_func(suffix=self.name)
def point_weight(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex, qp_index: int):
return WEIGHTS[qp_index]
return point_weight
def _make_point_index(self):
N = self._N
@cache.dynamic_func(suffix=self.name)
def point_index(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex, qp_index: int):
return N * element_index + qp_index
return point_index
class NodalQuadrature(Quadrature):
"""Quadrature using space node points as quadrature points
Note that in contrast to the `nodal=True` flag for :func:`integrate`, this quadrature odes not make any assumption
about orthogonality of shape functions, and is thus safe to use for arbitrary integrands.
"""
def __init__(self, domain: domain.GeometryDomain, space: FunctionSpace):
super().__init__(domain)
self._space = space
self.Arg = self._make_arg()
self.point_count = self._make_point_count()
self.point_index = self._make_point_index()
self.point_coords = self._make_point_coords()
self.point_weight = self._make_point_weight()
@property
def name(self):
return f"{self.__class__.__name__}_{self._space.name}"
def total_point_count(self):
return self._space.node_count()
def points_per_element(self):
return self._space.topology.NODES_PER_ELEMENT
def _make_arg(self):
@cache.dynamic_struct(suffix=self.name)
class Arg:
space_arg: self._space.SpaceArg
topo_arg: self._space.topology.TopologyArg
return Arg
@cache.cached_arg_value
def arg_value(self, device):
arg = self.Arg()
arg.space_arg = self._space.space_arg_value(device)
arg.topo_arg = self._space.topology.topo_arg_value(device)
return arg
def _make_point_count(self):
N = self._space.topology.NODES_PER_ELEMENT
@cache.dynamic_func(suffix=self.name)
def point_count(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex):
return N
return point_count
def _make_point_coords(self):
@cache.dynamic_func(suffix=self.name)
def point_coords(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex, qp_index: int):
return self._space.node_coords_in_element(elt_arg, qp_arg.space_arg, element_index, qp_index)
return point_coords
def _make_point_weight(self):
@cache.dynamic_func(suffix=self.name)
def point_weight(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex, qp_index: int):
return self._space.node_quadrature_weight(elt_arg, qp_arg.space_arg, element_index, qp_index)
return point_weight
def _make_point_index(self):
@cache.dynamic_func(suffix=self.name)
def point_index(elt_arg: self.domain.ElementArg, qp_arg: self.Arg, element_index: ElementIndex, qp_index: int):
return self._space.topology.element_node_index(elt_arg, qp_arg.topo_arg, element_index, qp_index)
return point_index
class ExplicitQuadrature(Quadrature):
"""Quadrature using explicit per-cell points and weights. The number of quadrature points per cell is assumed
to be constant and deduced from the shape of the points and weights arrays.
Args:
domain: Domain of definition of the quadrature formula
points: 2d array of shape ``(domain.geometry_element-count(), points_per_cell)`` containing the coordinates of each quadrature point.
weights: 2d array of shape ``(domain.geometry_element-count(), points_per_cell)`` containing the weight for each quadrature point.
See also: :class:`PicQuadrature`
"""
@wp.struct
class Arg:
points_per_cell: int
points: wp.array2d(dtype=Coords)
weights: wp.array2d(dtype=float)
def __init__(
self, domain: domain.GeometryDomain, points: "wp.array2d(dtype=Coords)", weights: "wp.array2d(dtype=float)"
):
super().__init__(domain)
if points.shape != weights.shape:
raise ValueError("Points and weights arrays must have the same shape")
self._points_per_cell = points.shape[1]
self._points = points
self._weights = weights
@property
def name(self):
return f"{self.__class__.__name__}"
def total_point_count(self):
return self._weights.size
def points_per_element(self):
return self._points_per_cell
@cache.cached_arg_value
def arg_value(self, device):
arg = self.Arg()
arg.points_per_cell = self._points_per_cell
arg.points = self._points.to(device)
arg.weights = self._weights.to(device)
return arg
@wp.func
def point_count(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex):
return qp_arg.points_per_cell
@wp.func
def point_coords(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex, qp_index: int):
return qp_arg.points[element_index, qp_index]
@wp.func
def point_weight(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex, qp_index: int):
return qp_arg.weights[element_index, qp_index]
@wp.func
def point_index(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex, qp_index: int):
return qp_arg.points_per_cell * element_index + qp_index
| 9,746 | Python | 31.929054 | 141 | 0.644162 |
NVIDIA/warp/warp/fem/quadrature/__init__.py | from .pic_quadrature import PicQuadrature
from .quadrature import ExplicitQuadrature, NodalQuadrature, Quadrature, RegularQuadrature
| 133 | Python | 43.666652 | 90 | 0.87218 |
NVIDIA/warp/warp/fem/quadrature/pic_quadrature.py | from typing import Any, Optional, Tuple, Union
import warp as wp
from warp.fem.cache import TemporaryStore, borrow_temporary, cached_arg_value, dynamic_kernel
from warp.fem.domain import GeometryDomain
from warp.fem.types import Coords, ElementIndex, make_free_sample
from warp.fem.utils import compress_node_indices
from .quadrature import Quadrature
wp.set_module_options({"enable_backward": False})
class PicQuadrature(Quadrature):
"""Particle-based quadrature formula, using a global set of points unevenly spread out over geometry elements.
Useful for Particle-In-Cell and derived methods.
Args:
domain: Underlying domain for the quadrature
positions: Either an array containing the world positions of all particles, or a tuple of arrays containing
the cell indices and coordinates for each particle. Note that the former requires the underlying geometry to
define a global :meth:`Geometry.cell_lookup` method; currently this is only available for :class:`Grid2D` and :class:`Grid3D`.
measures: Array containing the measure (area/volume) of each particle, used to defined the integration weights.
If ``None``, defaults to the cell measure divided by the number of particles in the cell.
temporary_store: shared pool from which to allocate temporary arrays
"""
def __init__(
self,
domain: GeometryDomain,
positions: Union[
"wp.array(dtype=wp.vecXd)",
Tuple[
"wp.array(dtype=ElementIndex)",
"wp.array(dtype=Coords)",
],
],
measures: Optional["wp.array(dtype=float)"] = None,
temporary_store: TemporaryStore = None,
):
super().__init__(domain)
self._bin_particles(positions, measures, temporary_store)
@property
def name(self):
return f"{self.__class__.__name__}"
@Quadrature.domain.setter
def domain(self, domain: GeometryDomain):
# Allow changing the quadrature domain as long as underlying geometry and element kind are the same
if self.domain is not None and (
domain.geometry != self.domain.geometry or domain.element_kind != self.domain.element_kind
):
raise RuntimeError(
"Cannot change the domain to that of a different Geometry and/or using different element kinds."
)
self._domain = domain
@wp.struct
class Arg:
cell_particle_offsets: wp.array(dtype=int)
cell_particle_indices: wp.array(dtype=int)
particle_fraction: wp.array(dtype=float)
particle_coords: wp.array(dtype=Coords)
@cached_arg_value
def arg_value(self, device) -> Arg:
arg = PicQuadrature.Arg()
arg.cell_particle_offsets = self._cell_particle_offsets.array.to(device)
arg.cell_particle_indices = self._cell_particle_indices.array.to(device)
arg.particle_fraction = self._particle_fraction.to(device)
arg.particle_coords = self._particle_coords.to(device)
return arg
def total_point_count(self):
return self._particle_coords.shape[0]
def active_cell_count(self):
"""Number of cells containing at least one particle"""
return self._cell_count
@wp.func
def point_count(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex):
return qp_arg.cell_particle_offsets[element_index + 1] - qp_arg.cell_particle_offsets[element_index]
@wp.func
def point_coords(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex, index: int):
particle_index = qp_arg.cell_particle_indices[qp_arg.cell_particle_offsets[element_index] + index]
return qp_arg.particle_coords[particle_index]
@wp.func
def point_weight(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex, index: int):
particle_index = qp_arg.cell_particle_indices[qp_arg.cell_particle_offsets[element_index] + index]
return qp_arg.particle_fraction[particle_index]
@wp.func
def point_index(elt_arg: Any, qp_arg: Arg, element_index: ElementIndex, index: int):
particle_index = qp_arg.cell_particle_indices[qp_arg.cell_particle_offsets[element_index] + index]
return particle_index
def fill_element_mask(self, mask: "wp.array(dtype=int)"):
"""Fills a mask array such that all non-empty elements are set to 1, all empty elements to zero.
Args:
mask: Int warp array with size at least equal to `self.domain.geometry_element_count()`
"""
wp.launch(
kernel=PicQuadrature._fill_mask_kernel,
dim=self.domain.geometry_element_count(),
device=mask.device,
inputs=[self._cell_particle_offsets.array, mask],
)
@wp.kernel
def _fill_mask_kernel(
element_particle_offsets: wp.array(dtype=int),
element_mask: wp.array(dtype=int),
):
i = wp.tid()
element_mask[i] = wp.select(element_particle_offsets[i] == element_particle_offsets[i + 1], 1, 0)
@wp.kernel
def _compute_uniform_fraction(
cell_index: wp.array(dtype=ElementIndex),
cell_particle_offsets: wp.array(dtype=int),
cell_fraction: wp.array(dtype=float),
):
p = wp.tid()
cell = cell_index[p]
cell_particle_count = cell_particle_offsets[cell + 1] - cell_particle_offsets[cell]
cell_fraction[p] = 1.0 / float(cell_particle_count)
def _bin_particles(self, positions, measures, temporary_store: TemporaryStore):
if wp.types.is_array(positions):
# Initialize from positions
@dynamic_kernel(suffix=f"{self.domain.name}")
def bin_particles(
cell_arg_value: self.domain.ElementArg,
positions: wp.array(dtype=positions.dtype),
cell_index: wp.array(dtype=ElementIndex),
cell_coords: wp.array(dtype=Coords),
):
p = wp.tid()
sample = self.domain.element_lookup(cell_arg_value, positions[p])
cell_index[p] = sample.element_index
cell_coords[p] = sample.element_coords
device = positions.device
cell_index_temp = borrow_temporary(temporary_store, shape=positions.shape, dtype=int, device=device)
cell_index = cell_index_temp.array
self._particle_coords_temp = borrow_temporary(
temporary_store, shape=positions.shape, dtype=Coords, device=device
)
self._particle_coords = self._particle_coords_temp.array
wp.launch(
dim=positions.shape[0],
kernel=bin_particles,
inputs=[
self.domain.element_arg_value(device),
positions,
cell_index,
self._particle_coords,
],
device=device,
)
else:
cell_index, self._particle_coords = positions
if cell_index.shape != self._particle_coords.shape:
raise ValueError("Cell index and coordinates arrays must have the same shape")
cell_index_temp = None
self._particle_coords_temp = None
self._cell_particle_offsets, self._cell_particle_indices, self._cell_count, _ = compress_node_indices(
self.domain.geometry_element_count(), cell_index
)
self._compute_fraction(cell_index, measures, temporary_store)
def _compute_fraction(self, cell_index, measures, temporary_store: TemporaryStore):
device = cell_index.device
self._particle_fraction_temp = borrow_temporary(
temporary_store, shape=cell_index.shape, dtype=float, device=device
)
self._particle_fraction = self._particle_fraction_temp.array
if measures is None:
# Split fraction uniformly over all particles in cell
wp.launch(
dim=cell_index.shape,
kernel=PicQuadrature._compute_uniform_fraction,
inputs=[
cell_index,
self._cell_particle_offsets.array,
self._particle_fraction,
],
device=device,
)
else:
# Fraction from particle measure
if measures.shape != cell_index.shape:
raise ValueError("Measures should be an 1d array or length equal to particle count")
@dynamic_kernel(suffix=f"{self.domain.name}")
def compute_fraction(
cell_arg_value: self.domain.ElementArg,
measures: wp.array(dtype=float),
cell_index: wp.array(dtype=ElementIndex),
cell_coords: wp.array(dtype=Coords),
cell_fraction: wp.array(dtype=float),
):
p = wp.tid()
sample = make_free_sample(cell_index[p], cell_coords[p])
cell_fraction[p] = measures[p] / self.domain.element_measure(cell_arg_value, sample)
wp.launch(
dim=measures.shape[0],
kernel=compute_fraction,
inputs=[
self.domain.element_arg_value(device),
measures,
cell_index,
self._particle_coords,
self._particle_fraction,
],
device=device,
)
| 9,515 | Python | 38 | 135 | 0.607252 |
NVIDIA/warp/warp/tests/test_rounding.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
compare_to_numpy = False
print_results = False
@wp.kernel
def test_kernel(
x: wp.array(dtype=float),
x_round: wp.array(dtype=float),
x_rint: wp.array(dtype=float),
x_trunc: wp.array(dtype=float),
x_cast: wp.array(dtype=float),
x_floor: wp.array(dtype=float),
x_ceil: wp.array(dtype=float),
x_frac: wp.array(dtype=float),
):
tid = wp.tid()
x_round[tid] = wp.round(x[tid])
x_rint[tid] = wp.rint(x[tid])
x_trunc[tid] = wp.trunc(x[tid])
x_cast[tid] = float(int(x[tid]))
x_floor[tid] = wp.floor(x[tid])
x_ceil[tid] = wp.ceil(x[tid])
x_frac[tid] = wp.frac(x[tid])
def test_rounding(test, device):
nx = np.array(
[
4.9,
4.5,
4.1,
3.9,
3.5,
3.1,
2.9,
2.5,
2.1,
1.9,
1.5,
1.1,
0.9,
0.5,
0.1,
-0.1,
-0.5,
-0.9,
-1.1,
-1.5,
-1.9,
-2.1,
-2.5,
-2.9,
-3.1,
-3.5,
-3.9,
-4.1,
-4.5,
-4.9,
],
dtype=np.float32,
)
x = wp.array(nx, device=device)
N = len(x)
x_round = wp.empty(N, dtype=float, device=device)
x_rint = wp.empty(N, dtype=float, device=device)
x_trunc = wp.empty(N, dtype=float, device=device)
x_cast = wp.empty(N, dtype=float, device=device)
x_floor = wp.empty(N, dtype=float, device=device)
x_ceil = wp.empty(N, dtype=float, device=device)
x_frac = wp.empty(N, dtype=float, device=device)
wp.launch(
kernel=test_kernel, dim=N, inputs=[x, x_round, x_rint, x_trunc, x_cast, x_floor, x_ceil, x_frac], device=device
)
wp.synchronize()
nx_round = x_round.numpy().reshape(N)
nx_rint = x_rint.numpy().reshape(N)
nx_trunc = x_trunc.numpy().reshape(N)
nx_cast = x_cast.numpy().reshape(N)
nx_floor = x_floor.numpy().reshape(N)
nx_ceil = x_ceil.numpy().reshape(N)
nx_frac = x_frac.numpy().reshape(N)
tab = np.stack([nx, nx_round, nx_rint, nx_trunc, nx_cast, nx_floor, nx_ceil, nx_frac], axis=1)
golden = np.array(
[
[4.9, 5.0, 5.0, 4.0, 4.0, 4.0, 5.0, 0.9],
[4.5, 5.0, 4.0, 4.0, 4.0, 4.0, 5.0, 0.5],
[4.1, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 0.1],
[3.9, 4.0, 4.0, 3.0, 3.0, 3.0, 4.0, 0.9],
[3.5, 4.0, 4.0, 3.0, 3.0, 3.0, 4.0, 0.5],
[3.1, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 0.1],
[2.9, 3.0, 3.0, 2.0, 2.0, 2.0, 3.0, 0.9],
[2.5, 3.0, 2.0, 2.0, 2.0, 2.0, 3.0, 0.5],
[2.1, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 0.1],
[1.9, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0, 0.9],
[1.5, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0, 0.5],
[1.1, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 0.1],
[0.9, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.9],
[0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.5],
[0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.1],
[-0.1, -0.0, -0.0, -0.0, 0.0, -1.0, -0.0, -0.1],
[-0.5, -1.0, -0.0, -0.0, 0.0, -1.0, -0.0, -0.5],
[-0.9, -1.0, -1.0, -0.0, 0.0, -1.0, -0.0, -0.9],
[-1.1, -1.0, -1.0, -1.0, -1.0, -2.0, -1.0, -0.1],
[-1.5, -2.0, -2.0, -1.0, -1.0, -2.0, -1.0, -0.5],
[-1.9, -2.0, -2.0, -1.0, -1.0, -2.0, -1.0, -0.9],
[-2.1, -2.0, -2.0, -2.0, -2.0, -3.0, -2.0, -0.1],
[-2.5, -3.0, -2.0, -2.0, -2.0, -3.0, -2.0, -0.5],
[-2.9, -3.0, -3.0, -2.0, -2.0, -3.0, -2.0, -0.9],
[-3.1, -3.0, -3.0, -3.0, -3.0, -4.0, -3.0, -0.1],
[-3.5, -4.0, -4.0, -3.0, -3.0, -4.0, -3.0, -0.5],
[-3.9, -4.0, -4.0, -3.0, -3.0, -4.0, -3.0, -0.9],
[-4.1, -4.0, -4.0, -4.0, -4.0, -5.0, -4.0, -0.1],
[-4.5, -5.0, -4.0, -4.0, -4.0, -5.0, -4.0, -0.5],
[-4.9, -5.0, -5.0, -4.0, -4.0, -5.0, -4.0, -0.9],
],
dtype=np.float32,
)
assert_np_equal(tab, golden, tol=1e-6)
if print_results:
np.set_printoptions(formatter={"float": lambda x: "{:6.1f}".format(x).replace(".0", ".")})
print("----------------------------------------------")
print(" %5s %5s %5s %5s %5s %5s %5s" % ("x ", "round", "rint", "trunc", "cast", "floor", "ceil"))
print(tab)
print("----------------------------------------------")
if compare_to_numpy:
nx_round = np.round(nx)
nx_rint = np.rint(nx)
nx_trunc = np.trunc(nx)
nx_fix = np.fix(nx)
nx_floor = np.floor(nx)
nx_ceil = np.ceil(nx)
nx_frac = np.modf(nx)[0]
tab = np.stack([nx, nx_round, nx_rint, nx_trunc, nx_fix, nx_floor, nx_ceil, nx_frac], axis=1)
print(" %5s %5s %5s %5s %5s %5s %5s" % ("x ", "round", "rint", "trunc", "fix", "floor", "ceil"))
print(tab)
print("----------------------------------------------")
class TestRounding(unittest.TestCase):
pass
devices = get_test_devices()
add_function_test(TestRounding, "test_rounding", test_rounding, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 5,784 | Python | 31.5 | 119 | 0.449343 |
NVIDIA/warp/warp/tests/test_launch.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
dim_x = wp.constant(2)
dim_y = wp.constant(2)
dim_z = wp.constant(2)
dim_w = wp.constant(2)
@wp.kernel
def kernel1d(a: wp.array(dtype=int, ndim=1)):
i = wp.tid()
wp.expect_eq(a[i], i)
@wp.kernel
def kernel2d(a: wp.array(dtype=int, ndim=2)):
i, j = wp.tid()
wp.expect_eq(a[i, j], i * dim_y + j)
@wp.kernel
def kernel3d(a: wp.array(dtype=int, ndim=3)):
i, j, k = wp.tid()
wp.expect_eq(a[i, j, k], i * dim_y * dim_z + j * dim_z + k)
@wp.kernel
def kernel4d(a: wp.array(dtype=int, ndim=4)):
i, j, k, l = wp.tid()
wp.expect_eq(a[i, j, k, l], i * dim_y * dim_z * dim_w + j * dim_z * dim_w + k * dim_w + l)
def test1d(test, device):
a = np.arange(0, dim_x).reshape(dim_x)
wp.launch(kernel1d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
def test2d(test, device):
a = np.arange(0, dim_x * dim_y).reshape(dim_x, dim_y)
wp.launch(kernel2d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
def test3d(test, device):
a = np.arange(0, dim_x * dim_y * dim_z).reshape(dim_x, dim_y, dim_z)
wp.launch(kernel3d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
def test4d(test, device):
a = np.arange(0, dim_x * dim_y * dim_z * dim_w).reshape(dim_x, dim_y, dim_z, dim_w)
wp.launch(kernel4d, dim=a.shape, inputs=[wp.array(a, dtype=int, device=device)], device=device)
@wp.struct
class Params:
a: wp.array(dtype=int)
i: int
f: float
@wp.kernel
def kernel_cmd(params: Params, i: int, f: float, v: wp.vec3, m: wp.mat33, out: wp.array(dtype=int)):
tid = wp.tid()
wp.expect_eq(params.i, i)
wp.expect_eq(params.f, f)
wp.expect_eq(i, int(f))
wp.expect_eq(v[0], f)
wp.expect_eq(v[1], f)
wp.expect_eq(v[2], f)
wp.expect_eq(m[0, 0], f)
wp.expect_eq(m[1, 1], f)
wp.expect_eq(m[2, 2], f)
out[tid] = tid + i
def test_launch_cmd(test, device):
n = 1
ref = np.arange(0, n)
out = wp.zeros(n, dtype=int, device=device)
params = Params()
params.i = 1
params.f = 1.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
# standard launch
wp.launch(kernel_cmd, dim=n, inputs=[params, params.i, params.f, v, m, out], device=device)
assert_np_equal(out.numpy(), ref + params.i)
# cmd launch
out.zero_()
cmd = wp.launch(kernel_cmd, dim=n, inputs=[params, params.i, params.f, v, m, out], device=device, record_cmd=True)
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
def test_launch_cmd_set_param(test, device):
n = 1
ref = np.arange(0, n)
params = Params()
v = wp.vec3()
m = wp.mat33()
cmd = wp.launch(kernel_cmd, dim=n, inputs=[params, 0, 0.0, v, m, None], device=device, record_cmd=True)
# cmd param modification
out = wp.zeros(n, dtype=int, device=device)
params.i = 13
params.f = 13.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
cmd.set_param_at_index(0, params)
cmd.set_param_at_index(1, params.i)
cmd.set_param_at_index(2, params.f)
cmd.set_param_at_index(3, v)
cmd.set_param_at_index(4, m)
cmd.set_param_by_name("out", out)
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
# test changing params after launch directly
# because we now cache the ctypes object inside the wp.struct
# instance the command buffer will be automatically updated
params.i = 14
params.f = 14.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
# this is the line we explicitly leave out to
# ensure that param changes are reflected in the launch
# launch.set_param_at_index(0, params)
cmd.set_param_at_index(1, params.i)
cmd.set_param_at_index(2, params.f)
cmd.set_param_at_index(3, v)
cmd.set_param_at_index(4, m)
cmd.set_param_by_name("out", out)
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
def test_launch_cmd_set_ctype(test, device):
n = 1
ref = np.arange(0, n)
params = Params()
v = wp.vec3()
m = wp.mat33()
cmd = wp.launch(kernel_cmd, dim=n, inputs=[params, 0, 0.0, v, m, None], device=device, record_cmd=True)
# cmd param modification
out = wp.zeros(n, dtype=int, device=device)
# cmd param modification
out.zero_()
params.i = 13
params.f = 13.0
v = wp.vec3(params.f, params.f, params.f)
m = wp.mat33(params.f, 0.0, 0.0, 0.0, params.f, 0.0, 0.0, 0.0, params.f)
cmd.set_param_at_index_from_ctype(0, params.__ctype__())
cmd.set_param_at_index_from_ctype(1, params.i)
cmd.set_param_at_index_from_ctype(2, params.f)
cmd.set_param_at_index_from_ctype(3, v)
cmd.set_param_at_index_from_ctype(4, m)
cmd.set_param_by_name_from_ctype("out", out.__ctype__())
cmd.launch()
assert_np_equal(out.numpy(), ref + params.i)
@wp.kernel
def arange(out: wp.array(dtype=int)):
tid = wp.tid()
out[tid] = tid
def test_launch_cmd_set_dim(test, device):
n = 10
ref = np.arange(0, n, dtype=int)
out = wp.zeros(n, dtype=int, device=device)
cmd = wp.launch(arange, dim=n, inputs=[out], device=device, record_cmd=True)
cmd.set_dim(5)
cmd.launch()
# check first half the array is filled while rest is still zero
assert_np_equal(out.numpy()[0:5], ref[0:5])
assert_np_equal(out.numpy()[5:], np.zeros(5))
out.zero_()
cmd.set_dim(10)
cmd.launch()
# check the whole array was filled
assert_np_equal(out.numpy(), ref)
def test_launch_cmd_empty(test, device):
n = 10
ref = np.arange(0, n, dtype=int)
out = wp.zeros(n, dtype=int, device=device)
cmd = wp.Launch(arange, device)
cmd.set_dim(5)
cmd.set_param_by_name("out", out)
cmd.launch()
# check first half the array is filled while rest is still zero
assert_np_equal(out.numpy()[0:5], ref[0:5])
assert_np_equal(out.numpy()[5:], np.zeros(5))
out.zero_()
cmd.set_dim(10)
cmd.launch()
# check the whole array was filled
assert_np_equal(out.numpy(), ref)
@wp.kernel
def kernel_mul(
values: wp.array(dtype=int),
coeff: int,
out: wp.array(dtype=int),
):
tid = wp.tid()
out[tid] = values[tid] * coeff
def test_launch_tuple_args(test, device):
values = wp.array(np.arange(0, 4), dtype=int, device=device)
coeff = 3
out = wp.empty_like(values)
wp.launch(
kernel_mul,
dim=len(values),
inputs=(
values,
coeff,
),
outputs=(out,),
device=device,
)
assert_np_equal(out.numpy(), np.array((0, 3, 6, 9)))
wp.launch(
kernel_mul,
dim=len(values),
inputs=(
values,
coeff,
out,
),
device=device,
)
assert_np_equal(out.numpy(), np.array((0, 3, 6, 9)))
wp.launch(
kernel_mul,
dim=len(values),
outputs=(
values,
coeff,
out,
),
device=device,
)
assert_np_equal(out.numpy(), np.array((0, 3, 6, 9)))
devices = get_test_devices()
class TestLaunch(unittest.TestCase):
pass
add_function_test(TestLaunch, "test_launch_1d", test1d, devices=devices)
add_function_test(TestLaunch, "test_launch_2d", test2d, devices=devices)
add_function_test(TestLaunch, "test_launch_3d", test3d, devices=devices)
add_function_test(TestLaunch, "test_launch_4d", test4d, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd", test_launch_cmd, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_set_param", test_launch_cmd_set_param, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_set_ctype", test_launch_cmd_set_ctype, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_set_dim", test_launch_cmd_set_dim, devices=devices)
add_function_test(TestLaunch, "test_launch_cmd_empty", test_launch_cmd_empty, devices=devices)
add_function_test(TestLaunch, "test_launch_tuple_args", test_launch_tuple_args, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 8,862 | Python | 24.107649 | 118 | 0.619499 |
NVIDIA/warp/warp/tests/test_large.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import math
import unittest
from typing import Any
import warp as wp
from warp.tests.unittest_utils import *
@wp.kernel
def conditional_sum(result: wp.array(dtype=wp.uint64)):
i, j, k = wp.tid()
if i == 0:
wp.atomic_add(result, 0, wp.uint64(1))
def test_large_launch_large_kernel(test, device):
"""Test tid() on kernel launch of 2**33 threads.
The function conditional sum will add 1 to result for every thread that has an i index of 0.
Due to the size of the grid, this test is not run on CPUs
"""
test_result = wp.zeros(shape=(1,), dtype=wp.uint64, device=device)
large_dim_length = 2**16
half_result = large_dim_length * large_dim_length
wp.launch(kernel=conditional_sum, dim=[2, large_dim_length, large_dim_length], inputs=[test_result], device=device)
test.assertEqual(test_result.numpy()[0], half_result)
@wp.kernel
def count_elements(result: wp.array(dtype=wp.uint64)):
wp.atomic_add(result, 0, wp.uint64(1))
def test_large_launch_max_blocks(test, device):
# Loop over 1000x1x1 elements using a grid of 256 threads
test_result = wp.zeros(shape=(1,), dtype=wp.uint64, device=device)
wp.launch(count_elements, (1000,), inputs=[test_result], max_blocks=1, device=device)
test.assertEqual(test_result.numpy()[0], 1000)
# Loop over 2x10x10 elements using a grid of 256 threads, using the tid() index to count half the elements
test_result.zero_()
wp.launch(
conditional_sum,
(
2,
50,
10,
),
inputs=[test_result],
max_blocks=1,
device=device,
)
test.assertEqual(test_result.numpy()[0], 500)
def test_large_launch_very_large_kernel(test, device):
"""Due to the size of the grid, this test is not run on CPUs"""
# Dim is chosen to be larger than the maximum CUDA one-dimensional grid size (total threads)
dim = (2**31 - 1) * 256 + 1
test_result = wp.zeros(shape=(1,), dtype=wp.uint64, device=device)
wp.launch(count_elements, (dim,), inputs=[test_result], device=device)
test.assertEqual(test_result.numpy()[0], dim)
def test_large_arrays_slow(test, device):
# The goal of this test is to use arrays just large enough to know
# if there's a flaw in handling arrays with more than 2**31-1 elements
# Unfortunately, it takes a long time to run so it won't be run automatically
# without changes to support how frequently a test may be run
total_elements = 2**31 + 8
# 2-D to 4-D arrays: test zero_, fill_, then zero_ for scalar data types:
for total_dims in range(2, 5):
dim_x = math.ceil(total_elements ** (1 / total_dims))
shape_tuple = tuple([dim_x] * total_dims)
for wptype in wp.types.scalar_types:
a1 = wp.zeros(shape_tuple, dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros_like(a1.numpy()))
a1.fill_(127)
assert_np_equal(a1.numpy(), 127 * np.ones_like(a1.numpy()))
a1.zero_()
assert_np_equal(a1.numpy(), np.zeros_like(a1.numpy()))
@wp.kernel
def check_array_equal_value(data: wp.array2d(dtype=Any), expect: Any):
i, j = wp.tid()
wp.expect_eq(data[i, j], expect)
def test_large_arrays_fast(test, device):
# A truncated version of test_large_arrays_slow meant to catch basic errors
# Make is so that a (dim_x, dim_x) array has more than 2**31 elements
dim_x = math.ceil(math.sqrt(2**31))
a1 = wp.zeros((dim_x, dim_x), dtype=wp.int8, device=device)
a1.fill_(127)
wp.launch(check_array_equal_value, a1.shape, inputs=[a1, wp.int8(127)], device=device)
a1.zero_()
wp.launch(check_array_equal_value, a1.shape, inputs=[a1, wp.int8(0)], device=device)
def test_large_array_excessive_zeros(test, device):
# Tests the allocation of an array with length exceeding 2**31-1 in a dimension
with test.assertRaisesRegex(
ValueError, "Array shapes must not exceed the maximum representable value of a signed 32-bit integer"
):
_ = wp.zeros((2**31), dtype=int, device=device)
def test_large_array_excessive_numpy(test, device):
# Tests the allocation of an array from a numpy array with length exceeding 2**31-1 in a dimension
large_np_array = np.empty((2**31), dtype=int)
with test.assertRaisesRegex(
ValueError, "Array shapes must not exceed the maximum representable value of a signed 32-bit integer"
):
_ = wp.array(large_np_array, device=device)
devices = get_test_devices()
class TestLarge(unittest.TestCase):
pass
add_function_test(
TestLarge,
"test_large_launch_large_kernel",
test_large_launch_large_kernel,
devices=get_selected_cuda_test_devices(),
)
add_function_test(TestLarge, "test_large_launch_max_blocks", test_large_launch_max_blocks, devices=devices)
add_function_test(
TestLarge,
"test_large_launch_very_large_kernel",
test_large_launch_very_large_kernel,
devices=get_selected_cuda_test_devices(),
)
add_function_test(TestLarge, "test_large_arrays_fast", test_large_arrays_fast, devices=devices)
add_function_test(TestLarge, "test_large_array_excessive_zeros", test_large_array_excessive_zeros, devices=devices)
add_function_test(TestLarge, "test_large_array_excessive_numpy", test_large_array_excessive_numpy, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 5,873 | Python | 33.552941 | 119 | 0.680742 |
NVIDIA/warp/warp/tests/test_examples.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""Test Warp examples with unittest.
This module tests the Warp examples registered in it using the unittest
framework. When registering tests with add_example_test(), three optional
dictionaries can be provided: test_options, test_options_cuda, and
test_options_cpu. These are added to the command line arguments in-order, so
if a parameter is specified in both test_options and test_options_cuda, the
one in test_options_cuda will take precedence due to how argparse works.
Generally the test_options[_cpu,_cuda] dictionaries should be used to prevent
graphical windows from being open by the example {"headless": True} and to
override example defaults so the example can run in less than ten seconds.
Use {"usd_required": True} and {"torch_required": True} to skip running the test
if usd-core or torch are not found in the Python environment.
Use the "num_frames" and "train_iters" keys to control the number of steps.
"""
import os
import subprocess
import sys
import unittest
from typing import Any, Dict, Optional, Type
import warp as wp
import warp.tests.unittest_utils
from warp.tests.unittest_utils import (
USD_AVAILABLE,
get_selected_cuda_test_devices,
get_test_devices,
sanitize_identifier,
)
def _build_command_line_options(test_options: Dict[str, Any]) -> list:
"""Helper function to build command-line options from the test options dictionary."""
additional_options = []
for key, value in test_options.items():
if key == "headless" and value:
additional_options.extend(["--headless"])
else:
# Just add --key value
additional_options.extend(["--" + key, str(value)])
return additional_options
def _merge_options(base_options: Dict[str, Any], device_options: Dict[str, Any]) -> Dict[str, Any]:
"""Helper function to merge base test options with device-specific test options."""
merged_options = base_options.copy()
# Update options with device-specific dictionary, overwriting existing keys with the more-specific values
merged_options.update(device_options)
return merged_options
def add_example_test(
cls: Type,
name: str,
devices: Optional[list] = None,
test_options: Optional[Dict[str, Any]] = None,
test_options_cpu: Optional[Dict[str, Any]] = None,
test_options_cuda: Optional[Dict[str, Any]] = None,
):
"""Registers a Warp example to run on ``devices`` as a TestCase."""
if test_options is None:
test_options = {}
if test_options_cpu is None:
test_options_cpu = {}
if test_options_cuda is None:
test_options_cuda = {}
def run(test, device):
if wp.get_device(device).is_cuda:
options = _merge_options(test_options, test_options_cuda)
else:
options = _merge_options(test_options, test_options_cpu)
# Mark the test as skipped if Torch is not installed but required
torch_required = options.pop("torch_required", False)
if torch_required:
try:
import torch
if wp.get_device(device).is_cuda and not torch.cuda.is_available():
# Ensure torch has CUDA support
test.skipTest("Torch not compiled with CUDA support")
except Exception as e:
test.skipTest(f"{e}")
# Mark the test as skipped if USD is not installed but required
usd_required = options.pop("usd_required", False)
if usd_required and not USD_AVAILABLE:
test.skipTest("Requires usd-core")
# Find the current Warp cache
warp_cache_path = wp.config.kernel_cache_dir
env_vars = os.environ.copy()
if warp_cache_path is not None:
env_vars["WARP_CACHE_PATH"] = warp_cache_path
if warp.tests.unittest_utils.coverage_enabled:
import tempfile
# Generate a random coverage data file name - file is deleted along with containing directory
with tempfile.NamedTemporaryFile(
dir=warp.tests.unittest_utils.coverage_temp_dir, delete=False
) as coverage_file:
pass
command = ["coverage", "run", f"--data-file={coverage_file.name}"]
if warp.tests.unittest_utils.coverage_branch:
command.append("--branch")
else:
command = [sys.executable]
# Append Warp commands
command.extend(["-m", f"warp.examples.{name}", "--device", str(device)])
stage_path = (
options.pop(
"stage_path",
os.path.join(os.path.dirname(__file__), f"outputs/{name}_{sanitize_identifier(device)}.usd"),
)
if USD_AVAILABLE
else "None"
)
if stage_path:
command.extend(["--stage_path", stage_path])
try:
os.remove(stage_path)
except OSError:
pass
command.extend(_build_command_line_options(options))
# with wp.ScopedTimer(f"{name}_{sanitize_identifier(device)}"):
# Run the script as a subprocess
result = subprocess.run(command, capture_output=True, text=True, env=env_vars)
# Check the return code (0 is standard for success)
test.assertEqual(
result.returncode,
0,
msg=f"Failed with return code {result.returncode}, command: {' '.join(command)}\n\nOutput:\n{result.stdout}\n{result.stderr}",
)
# If the test succeeded, try to clean up the output by default
if stage_path and result.returncode == 0:
try:
os.remove(stage_path)
except OSError:
pass
from warp.tests.unittest_utils import add_function_test
add_function_test(cls, f"test_{name}", run, devices=devices, check_output=False)
cuda_test_devices = get_selected_cuda_test_devices(mode="basic") # Don't test on multiple GPUs to save time
test_devices = get_test_devices(mode="basic")
# NOTE: To give the parallel test runner more opportunities to parallelize test cases,
# we break up the tests into multiple TestCase classes
class TestCoreExamples(unittest.TestCase):
pass
# Exclude unless we can run headless somehow
# add_example_test(TestCoreExamples, name="example_render_opengl")
add_example_test(TestCoreExamples, name="core.example_dem", devices=test_devices, test_options_cpu={"num_frames": 2})
add_example_test(
TestCoreExamples,
name="core.example_fluid",
devices=test_devices,
test_options={"num_frames": 100, "headless": True},
)
add_example_test(
TestCoreExamples,
name="core.example_graph_capture",
devices=test_devices,
test_options={"headless": True},
test_options_cpu={"num_frames": 100},
)
add_example_test(TestCoreExamples, name="core.example_marching_cubes", devices=cuda_test_devices)
add_example_test(TestCoreExamples, name="core.example_mesh", devices=test_devices, test_options={"usd_required": True})
add_example_test(
TestCoreExamples, name="core.example_mesh_intersect", devices=test_devices, test_options={"usd_required": True}
)
add_example_test(TestCoreExamples, name="core.example_nvdb", devices=test_devices)
add_example_test(
TestCoreExamples,
name="core.example_raycast",
devices=test_devices,
test_options={"usd_required": True, "headless": True},
)
add_example_test(
TestCoreExamples,
name="core.example_raymarch",
devices=test_devices,
test_options={"height": 512, "width": 1024, "headless": True},
)
add_example_test(TestCoreExamples, name="core.example_sph", devices=test_devices, test_options_cpu={"num_frames": 1})
add_example_test(
TestCoreExamples,
name="core.example_torch",
devices=test_devices,
test_options={"headless": True, "num_frames": 1000, "torch_required": True},
)
add_example_test(TestCoreExamples, name="core.example_wave", devices=test_devices)
class TestOptimExamples(unittest.TestCase):
pass
add_example_test(
TestOptimExamples, name="optim.example_bounce", devices=test_devices, test_options_cpu={"train_iters": 3}
)
add_example_test(
TestOptimExamples,
name="optim.example_drone",
devices=test_devices,
test_options={"headless": True},
test_options_cpu={"num_frames": 10},
)
add_example_test(
TestOptimExamples, name="optim.example_cloth_throw", devices=test_devices, test_options_cpu={"train_iters": 3}
)
add_example_test(
TestOptimExamples,
name="optim.example_diffray",
devices=test_devices,
test_options={"usd_required": True, "headless": True},
test_options_cpu={"train_iters": 2},
)
add_example_test(TestOptimExamples, name="optim.example_inverse_kinematics", devices=test_devices)
add_example_test(
TestOptimExamples,
name="optim.example_inverse_kinematics_torch",
devices=test_devices,
test_options={"torch_required": True},
)
add_example_test(TestOptimExamples, name="optim.example_spring_cage", devices=test_devices)
add_example_test(
TestOptimExamples,
name="optim.example_trajectory",
devices=test_devices,
test_options={"headless": True, "train_iters": 50},
)
# NOTE: This example uses CUTLASS and will run orders of magnitude slower when Warp is built in debug mode
add_example_test(
TestOptimExamples,
name="optim.example_walker",
devices=test_devices,
test_options={"usd_required": True},
test_options_cuda={
"train_iters": 1 if warp.context.runtime.core.is_debug_enabled() else 3,
"num_frames": 1 if warp.context.runtime.core.is_debug_enabled() else 60,
},
test_options_cpu={"train_iters": 1, "num_frames": 30},
)
class TestSimExamples(unittest.TestCase):
pass
add_example_test(TestSimExamples, name="sim.example_cartpole", devices=test_devices)
add_example_test(
TestSimExamples,
name="sim.example_cloth",
devices=test_devices,
test_options={"usd_required": True},
test_options_cpu={"num_frames": 10},
)
add_example_test(
TestSimExamples, name="sim.example_granular", devices=test_devices, test_options_cpu={"num_frames": 10}
)
add_example_test(TestSimExamples, name="sim.example_granular_collision_sdf", devices=cuda_test_devices)
add_example_test(TestSimExamples, name="sim.example_jacobian_ik", devices=test_devices)
add_example_test(TestSimExamples, name="sim.example_particle_chain", devices=test_devices)
add_example_test(
TestSimExamples, name="sim.example_quadruped", devices=test_devices, test_options_cpu={"num_frames": 100}
)
add_example_test(TestSimExamples, name="sim.example_rigid_chain", devices=test_devices)
add_example_test(
TestSimExamples,
name="sim.example_rigid_contact",
devices=test_devices,
test_options={"usd_required": True},
test_options_cpu={"num_frames": 3},
)
add_example_test(
TestSimExamples, name="sim.example_rigid_soft_contact", devices=test_devices, test_options_cpu={"num_frames": 10}
)
add_example_test(TestSimExamples, name="sim.example_rigid_force", devices=test_devices)
add_example_test(TestSimExamples, name="sim.example_rigid_gyroscopic", devices=test_devices)
add_example_test(
TestSimExamples, name="sim.example_soft_body", devices=test_devices, test_options_cpu={"num_frames": 10}
)
class TestFemExamples(unittest.TestCase):
pass
class TestFemDiffusionExamples(unittest.TestCase):
pass
add_example_test(
TestFemDiffusionExamples,
name="fem.example_diffusion_mgpu",
devices=get_selected_cuda_test_devices(mode="basic"),
test_options={"headless": True},
)
add_example_test(
TestFemExamples,
name="fem.example_apic_fluid",
devices=get_selected_cuda_test_devices(),
test_options={"num_frames": 5, "voxel_size": 2.0},
)
# The following examples do not need CUDA
add_example_test(
TestFemDiffusionExamples,
name="fem.example_diffusion",
devices=test_devices,
test_options={"resolution": 10, "mesh": "tri", "headless": True},
)
add_example_test(
TestFemDiffusionExamples, name="fem.example_diffusion_3d", devices=test_devices, test_options={"headless": True}
)
add_example_test(
TestFemExamples,
name="fem.example_deformed_geometry",
devices=test_devices,
test_options={"resolution": 10, "mesh": "tri", "headless": True},
)
add_example_test(
TestFemExamples,
name="fem.example_convection_diffusion",
devices=test_devices,
test_options={"resolution": 20, "headless": True},
)
add_example_test(
TestFemExamples,
name="fem.example_burgers",
devices=test_devices,
test_options={"resolution": 20, "num_frames": 25, "degree": 1, "headless": True},
)
add_example_test(
TestFemExamples,
name="fem.example_convection_diffusion_dg",
devices=test_devices,
test_options={"resolution": 20, "num_frames": 25, "mesh": "quad", "headless": True},
)
add_example_test(
TestFemExamples,
name="fem.example_mixed_elasticity",
devices=test_devices,
test_options={"nonconforming_stresses": True, "mesh": "quad", "headless": True},
)
add_example_test(
TestFemExamples, name="fem.example_stokes_transfer", devices=test_devices, test_options={"headless": True}
)
add_example_test(
TestFemExamples,
name="fem.example_stokes",
devices=test_devices,
test_options={"resolution": 10, "nonconforming_pressures": True, "headless": True},
)
add_example_test(
TestFemExamples,
name="fem.example_navier_stokes",
devices=test_devices,
test_options={"num_frames": 101, "resolution": 10, "tri_mesh": True, "headless": True},
)
if __name__ == "__main__":
# force rebuild of all kernels
wp.build.clear_kernel_cache()
unittest.main(verbosity=2, failfast=True)
| 14,108 | Python | 33.923267 | 138 | 0.683513 |
NVIDIA/warp/warp/tests/test_generics.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
from typing import Any
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.func
def generic_adder(a: Any, b: Any):
return a + b
@wp.kernel
def test_generic_adder():
wp.expect_eq(generic_adder(17, 25), 42)
wp.expect_eq(generic_adder(7.0, 10.0), 17.0)
v1 = wp.vec3(1.0, 2.0, 3.0)
v2 = wp.vec3(10.0, 20.0, 30.0)
wp.expect_eq(generic_adder(v1, v2), wp.vec3(11.0, 22.0, 33.0))
# regular functions for floats
@wp.func
def specialized_func(a: float, b: float):
return a * b
@wp.func
def specialized_func(a: float, b: float, c: float):
return a * b * c
# generic forms
@wp.func
def specialized_func(a: Any, b: Any):
return a + b
@wp.func
def specialized_func(a: Any, b: Any, c: Any):
return a + b + c
# specializations for ints
@wp.func
def specialized_func(a: int, b: int):
return a - b
@wp.func
def specialized_func(a: int, b: int, c: int):
return a - b - c
@wp.kernel
def test_specialized_func():
# subtraction with int args
wp.expect_eq(specialized_func(17, 25), -8)
wp.expect_eq(specialized_func(17, 25, 10), -18)
# multiplication with float args
wp.expect_eq(specialized_func(7.0, 10.0), 70.0)
wp.expect_eq(specialized_func(7.0, 10.0, 2.0), 140.0)
# addition with vector args
v1 = wp.vec3(1.0, 2.0, 3.0)
v2 = wp.vec3(10.0, 20.0, 30.0)
v3 = wp.vec3(100.0, 200.0, 300.0)
wp.expect_eq(specialized_func(v1, v2), wp.vec3(11.0, 22.0, 33.0))
wp.expect_eq(specialized_func(v1, v2, v3), wp.vec3(111.0, 222.0, 333.0))
# generic array kernel, version 1 (Any)
@wp.kernel
def generic_array_kernel_v1(a: Any, b: Any, c: Any):
tid = wp.tid()
sum = a[tid] + b[tid] # test direct access
c[tid] = generic_adder(sum, sum) # test generic function
wp.overload(generic_array_kernel_v1, [wp.array(dtype=int), wp.array(dtype=int), wp.array(dtype=int)])
wp.overload(generic_array_kernel_v1, [wp.array(dtype=float), wp.array(dtype=float), wp.array(dtype=float)])
wp.overload(generic_array_kernel_v1, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3)])
# generic array kernel, version 2 (generic dtype)
@wp.kernel
def generic_array_kernel_v2(a: wp.array(dtype=Any), b: wp.array(dtype=Any), c: wp.array(dtype=Any)):
tid = wp.tid()
sum = a[tid] + b[tid] # test direct access
c[tid] = generic_adder(sum, sum) # test generic function
wp.overload(generic_array_kernel_v2, [wp.array(dtype=int), wp.array(dtype=int), wp.array(dtype=int)])
wp.overload(generic_array_kernel_v2, [wp.array(dtype=float), wp.array(dtype=float), wp.array(dtype=float)])
wp.overload(generic_array_kernel_v2, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3)])
# generic array kernel, version 3 (unspecified dtype)
@wp.kernel
def generic_array_kernel_v3(a: wp.array(), b: wp.array(), c: wp.array()):
tid = wp.tid()
sum = a[tid] + b[tid] # test direct access
c[tid] = generic_adder(sum, sum) # test generic function
wp.overload(generic_array_kernel_v3, [wp.array(dtype=int), wp.array(dtype=int), wp.array(dtype=int)])
wp.overload(generic_array_kernel_v3, [wp.array(dtype=float), wp.array(dtype=float), wp.array(dtype=float)])
wp.overload(generic_array_kernel_v3, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3), wp.array(dtype=wp.vec3)])
def test_generic_array_kernel(test, device):
with wp.ScopedDevice(device):
n = 10
ai = wp.array(data=np.ones(n, dtype=np.int32))
ci = wp.empty(10, dtype=int)
af = wp.array(data=np.ones(n, dtype=np.float32))
cf = wp.empty(10, dtype=float)
a3 = wp.array(data=np.ones((n, 3), dtype=np.float32), dtype=wp.vec3)
c3 = wp.empty(n, dtype=wp.vec3)
wp.launch(generic_array_kernel_v1, dim=n, inputs=[af, af, cf])
wp.launch(generic_array_kernel_v1, dim=n, inputs=[ai, ai, ci])
wp.launch(generic_array_kernel_v1, dim=n, inputs=[a3, a3, c3])
assert_np_equal(ci.numpy(), np.full((n,), 4, dtype=np.int32))
assert_np_equal(cf.numpy(), np.full((n,), 4.0, dtype=np.float32))
assert_np_equal(c3.numpy(), np.full((n, 3), 4.0, dtype=np.float32))
wp.launch(generic_array_kernel_v2, dim=n, inputs=[af, af, cf])
wp.launch(generic_array_kernel_v2, dim=n, inputs=[ai, ai, ci])
wp.launch(generic_array_kernel_v2, dim=n, inputs=[a3, a3, c3])
assert_np_equal(ci.numpy(), np.full((n,), 4, dtype=np.int32))
assert_np_equal(cf.numpy(), np.full((n,), 4.0, dtype=np.float32))
assert_np_equal(c3.numpy(), np.full((n, 3), 4.0, dtype=np.float32))
wp.launch(generic_array_kernel_v3, dim=n, inputs=[af, af, cf])
wp.launch(generic_array_kernel_v3, dim=n, inputs=[ai, ai, ci])
wp.launch(generic_array_kernel_v3, dim=n, inputs=[a3, a3, c3])
assert_np_equal(ci.numpy(), np.full((n,), 4, dtype=np.int32))
assert_np_equal(cf.numpy(), np.full((n,), 4.0, dtype=np.float32))
assert_np_equal(c3.numpy(), np.full((n, 3), 4.0, dtype=np.float32))
# kernel that adds any scalar value to an array
@wp.kernel
def generic_accumulator_kernel(a: wp.array(dtype=wp.float64), value: Any):
tid = wp.tid()
a[tid] = a[tid] + wp.float64(value)
# overload named args
wp.overload(generic_accumulator_kernel, {"value": int})
wp.overload(generic_accumulator_kernel, {"value": float})
wp.overload(generic_accumulator_kernel, {"value": wp.float64})
wp.overload(generic_accumulator_kernel, {"value": wp.bool})
def test_generic_accumulator_kernel(test, device):
with wp.ScopedDevice(device):
n = 10
a = wp.zeros(n, dtype=wp.float64)
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, 25])
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, 17.0])
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, wp.float64(8.0)])
wp.launch(generic_accumulator_kernel, dim=a.size, inputs=[a, wp.bool(True)])
assert_np_equal(a.numpy(), np.full((n,), 51.0, dtype=np.float64))
# generic kernel used to automatically generate overloads from launch args
@wp.kernel
def generic_fill(a: wp.array(dtype=Any), value: Any):
tid = wp.tid()
a[tid] = value
def test_generic_fill(test, device):
with wp.ScopedDevice(device):
n = 10
ai = wp.zeros(n, dtype=int)
af = wp.zeros(n, dtype=float)
a3 = wp.zeros(n, dtype=wp.vec3)
ab = wp.zeros(n, dtype=wp.bool)
wp.launch(generic_fill, dim=ai.size, inputs=[ai, 42])
wp.launch(generic_fill, dim=af.size, inputs=[af, 17.0])
wp.launch(generic_fill, dim=a3.size, inputs=[a3, wp.vec3(5.0, 5.0, 5.0)])
wp.launch(generic_fill, dim=ab.size, inputs=[ab, wp.bool(True)])
assert_np_equal(ai.numpy(), np.full((n,), 42, dtype=np.int32))
assert_np_equal(af.numpy(), np.full((n,), 17.0, dtype=np.float32))
assert_np_equal(a3.numpy(), np.full((n, 3), 5.0, dtype=np.float32))
assert_np_equal(ab.numpy(), np.full((n,), True, dtype=np.bool_))
# generic kernel used to create and launch explicit overloads
@wp.kernel
def generic_fill_v2(a: wp.array(dtype=Any), value: Any):
tid = wp.tid()
a[tid] = value
vec3b_type = wp.vec(3, wp.bool)
# create explicit overloads to be launched directly
fill_int = wp.overload(generic_fill_v2, [wp.array(dtype=int), int])
fill_float = wp.overload(generic_fill_v2, [wp.array(dtype=float), float])
fill_vec3 = wp.overload(generic_fill_v2, [wp.array(dtype=wp.vec3), wp.vec3])
fill_vec3b = wp.overload(generic_fill_v2, [wp.array(dtype=vec3b_type), vec3b_type])
def test_generic_fill_overloads(test, device):
with wp.ScopedDevice(device):
n = 10
ai = wp.zeros(n, dtype=int)
af = wp.zeros(n, dtype=float)
a3 = wp.zeros(n, dtype=wp.vec3)
a3b = wp.zeros(n, dtype=vec3b_type)
wp.launch(fill_int, dim=ai.size, inputs=[ai, 42])
wp.launch(fill_float, dim=af.size, inputs=[af, 17.0])
wp.launch(fill_vec3, dim=a3.size, inputs=[a3, wp.vec3(5.0, 5.0, 5.0)])
wp.launch(fill_vec3b, dim=a3b.size, inputs=[a3b, vec3b_type([True, True, True])])
assert_np_equal(ai.numpy(), np.full((n,), 42, dtype=np.int32))
assert_np_equal(af.numpy(), np.full((n,), 17.0, dtype=np.float32))
assert_np_equal(a3.numpy(), np.full((n, 3), 5.0, dtype=np.float32))
assert_np_equal(a3b.numpy(), np.full((n, 3), True, dtype=np.bool_))
# custom vector/matrix types
my_vec5 = wp.vec(length=5, dtype=wp.float32)
my_mat55 = wp.mat(shape=(5, 5), dtype=wp.float32)
@wp.kernel
def generic_transform(v: Any, m: Any, expected: Any):
result = wp.mul(m, v)
wp.expect_eq(result, expected)
# use overload decorator syntax
@wp.overload
def generic_transform(v: wp.vec2, m: wp.mat22, expected: wp.vec2): # fmt: skip
...
@wp.overload
def generic_transform(v: wp.vec3, m: wp.mat33, expected: wp.vec3): # fmt: skip
...
@wp.overload
def generic_transform(v: wp.vec4, m: wp.mat44, expected: wp.vec4): # fmt: skip
...
@wp.overload
def generic_transform(v: my_vec5, m: my_mat55, expected: my_vec5): # fmt: skip
...
def test_generic_transform_kernel(test, device):
with wp.ScopedDevice(device):
v2 = wp.vec2(1, 2)
m22 = wp.mat22(2, 0, 0, 2)
e2 = wp.vec2(2, 4)
v3 = wp.vec3(1, 2, 3)
m33 = wp.mat33(2, 0, 0, 0, 2, 0, 0, 0, 2)
e3 = wp.vec3(2, 4, 6)
v4 = wp.vec4(1, 2, 3, 4)
m44 = wp.mat44(2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2)
e4 = wp.vec4(2, 4, 6, 8)
v5 = my_vec5(1, 2, 3, 4, 5)
m55 = my_mat55(2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2)
e5 = my_vec5(2, 4, 6, 8, 10)
wp.launch(generic_transform, dim=1, inputs=[v2, m22, e2])
wp.launch(generic_transform, dim=1, inputs=[v3, m33, e3])
wp.launch(generic_transform, dim=1, inputs=[v4, m44, e4])
wp.launch(generic_transform, dim=1, inputs=[v5, m55, e5])
wp.synchronize()
@wp.kernel
def generic_transform_array(v: wp.array(), m: wp.array(), result: wp.array()):
tid = wp.tid()
result[tid] = wp.mul(m[tid], v[tid])
wp.overload(generic_transform_array, [wp.array(dtype=wp.vec2), wp.array(dtype=wp.mat22), wp.array(dtype=wp.vec2)])
wp.overload(generic_transform_array, [wp.array(dtype=wp.vec3), wp.array(dtype=wp.mat33), wp.array(dtype=wp.vec3)])
wp.overload(generic_transform_array, [wp.array(dtype=wp.vec4), wp.array(dtype=wp.mat44), wp.array(dtype=wp.vec4)])
wp.overload(generic_transform_array, [wp.array(dtype=my_vec5), wp.array(dtype=my_mat55), wp.array(dtype=my_vec5)])
def test_generic_transform_array_kernel(test, device):
with wp.ScopedDevice(device):
n = 10
a2_data = np.tile(np.arange(2, dtype=np.float32), (n, 1))
a3_data = np.tile(np.arange(3, dtype=np.float32), (n, 1))
a4_data = np.tile(np.arange(4, dtype=np.float32), (n, 1))
a5_data = np.tile(np.arange(5, dtype=np.float32), (n, 1))
m22_data = np.tile((np.identity(2, dtype=np.float32) * 2), (n, 1, 1))
m33_data = np.tile((np.identity(3, dtype=np.float32) * 2), (n, 1, 1))
m44_data = np.tile((np.identity(4, dtype=np.float32) * 2), (n, 1, 1))
m55_data = np.tile((np.identity(5, dtype=np.float32) * 2), (n, 1, 1))
a2 = wp.array(data=a2_data, dtype=wp.vec2)
a3 = wp.array(data=a3_data, dtype=wp.vec3)
a4 = wp.array(data=a4_data, dtype=wp.vec4)
a5 = wp.array(data=a5_data, dtype=my_vec5)
m22 = wp.array(data=m22_data, dtype=wp.mat22)
m33 = wp.array(data=m33_data, dtype=wp.mat33)
m44 = wp.array(data=m44_data, dtype=wp.mat44)
m55 = wp.array(data=m55_data, dtype=my_mat55)
b2 = wp.zeros_like(a2)
b3 = wp.zeros_like(a3)
b4 = wp.zeros_like(a4)
b5 = wp.zeros_like(a5)
wp.launch(generic_transform_array, dim=n, inputs=[a2, m22, b2])
wp.launch(generic_transform_array, dim=n, inputs=[a3, m33, b3])
wp.launch(generic_transform_array, dim=n, inputs=[a4, m44, b4])
wp.launch(generic_transform_array, dim=n, inputs=[a5, m55, b5])
assert_np_equal(b2.numpy(), a2_data * 2)
assert_np_equal(b3.numpy(), a3_data * 2)
assert_np_equal(b4.numpy(), a4_data * 2)
assert_np_equal(b5.numpy(), a5_data * 2)
@wp.struct
class Foo:
x: float
y: float
z: float
@wp.struct
class Bar:
x: wp.vec3
y: wp.vec3
z: wp.vec3
@wp.kernel
def test_generic_struct_kernel(s: Any):
# test member access for generic structs
wp.expect_eq(s.x + s.y, s.z)
wp.overload(test_generic_struct_kernel, [Foo])
wp.overload(test_generic_struct_kernel, [Bar])
@wp.kernel
def test_generic_type_cast_kernel(a: Any, b: Any):
a = type(a)(b)
c = type(generic_adder(b, b))(a)
wp.expect_eq(b, c)
wp.overload(test_generic_type_cast_kernel, [wp.float32, wp.float64])
wp.overload(test_generic_type_cast_kernel, [wp.float32, wp.int32])
wp.overload(test_generic_type_cast_kernel, [wp.vec3f, wp.vec3d])
wp.overload(test_generic_type_cast_kernel, [wp.mat22f, wp.mat22d])
def test_generic_type_cast(test, device):
with wp.ScopedDevice(device):
wp.launch(test_generic_type_cast_kernel, dim=1, inputs=[1.0, 2.0])
wp.launch(test_generic_type_cast_kernel, dim=1, inputs=[2.0, -5])
wp.launch(test_generic_type_cast_kernel, dim=1, inputs=[wp.vec3f(1.0, 2.0, 3.0), wp.vec3d(4.0, 5.0, 6.0)])
wp.launch(test_generic_type_cast_kernel, dim=1, inputs=[wp.mat22f(0.0), wp.mat22d(np.eye(2))])
wp.synchronize()
@wp.kernel
def test_generic_scalar_construction_kernel(a: wp.array(dtype=Any)):
zero = type(a[0])(0)
copy = a.dtype(a[0])
copy += zero
wp.expect_eq(copy, a[0])
wp.overload(test_generic_scalar_construction_kernel, [wp.array(dtype=wp.int32)])
wp.overload(test_generic_scalar_construction_kernel, [wp.array(dtype=wp.float64)])
def test_generic_scalar_construction(test, device):
with wp.ScopedDevice(device):
wp.launch(test_generic_scalar_construction_kernel, dim=1, inputs=[wp.array([1.0], dtype=wp.int32)])
wp.launch(test_generic_scalar_construction_kernel, dim=1, inputs=[wp.array([-5], dtype=wp.float64)])
wp.synchronize()
@wp.kernel
def test_generic_type_construction_kernel(a: wp.array(dtype=Any)):
zero = type(a[0])()
copy = type(a).dtype(a[0]) * a.dtype.dtype(1.0)
copy += zero
wp.expect_eq(copy, a[0])
wp.overload(test_generic_type_construction_kernel, [wp.array(dtype=wp.vec3f)])
wp.overload(test_generic_type_construction_kernel, [wp.array(dtype=wp.mat22d)])
def test_generic_type_construction(test, device):
with wp.ScopedDevice(device):
wp.launch(test_generic_type_construction_kernel, dim=1, inputs=[wp.array([1.0, 2.0, 3.0], dtype=wp.vec3f)])
wp.launch(test_generic_type_construction_kernel, dim=1, inputs=[wp.array([np.eye(2)], dtype=wp.mat22d)])
wp.synchronize()
@wp.kernel
def test_generic_struct_construction_kernel(a: Any):
b = type(a)(a.x, a.y, a.z)
wp.expect_eq(a.x, b.x)
wp.expect_eq(a.y, b.y)
wp.expect_eq(a.z, b.z)
wp.overload(test_generic_struct_construction_kernel, [Foo])
wp.overload(test_generic_struct_construction_kernel, [Bar])
@wp.kernel
def test_generic_type_as_argument_kernel(a: Any):
vec = wp.vector(length=2, dtype=type(a))
matrix = wp.identity(n=vec.length, dtype=vec.dtype) * a
wp.expect_eq(wp.trace(matrix), type(a)(2.0) * a)
wp.overload(test_generic_type_as_argument_kernel, [wp.float32])
wp.overload(test_generic_type_as_argument_kernel, [wp.float64])
def test_generic_type_as_argument(test, device):
with wp.ScopedDevice(device):
wp.launch(test_generic_type_as_argument_kernel, dim=1, inputs=[2.0])
wp.launch(test_generic_type_as_argument_kernel, dim=1, inputs=[-1.0])
wp.synchronize()
def test_type_operator_misspell(test, device):
@wp.kernel
def kernel():
i = wp.tid()
_ = typez(i)(0)
with test.assertRaisesRegex(KeyError, r"Referencing undefined symbol: typez"):
wp.launch(
kernel,
dim=1,
inputs=[],
device=device,
)
def test_type_attribute_error(test, device):
@wp.kernel
def kernel():
a = wp.vec3(0.0)
_ = a.dtype.shape
with test.assertRaisesRegex(AttributeError, r"`shape` is not an attribute of '<class 'warp.types.float32'>'"):
wp.launch(
kernel,
dim=1,
inputs=[],
device=device,
)
class TestGenerics(unittest.TestCase):
pass
devices = get_test_devices()
add_kernel_test(TestGenerics, name="test_generic_adder", kernel=test_generic_adder, dim=1, devices=devices)
add_kernel_test(TestGenerics, name="test_specialized_func", kernel=test_specialized_func, dim=1, devices=devices)
add_function_test(TestGenerics, "test_generic_array_kernel", test_generic_array_kernel, devices=devices)
add_function_test(TestGenerics, "test_generic_accumulator_kernel", test_generic_accumulator_kernel, devices=devices)
add_function_test(TestGenerics, "test_generic_fill", test_generic_fill, devices=devices)
add_function_test(TestGenerics, "test_generic_fill_overloads", test_generic_fill_overloads, devices=devices)
add_function_test(TestGenerics, "test_generic_transform_kernel", test_generic_transform_kernel, devices=devices)
add_function_test(
TestGenerics, "test_generic_transform_array_kernel", test_generic_transform_array_kernel, devices=devices
)
add_function_test(TestGenerics, "test_generic_type_cast", test_generic_type_cast, devices=devices)
add_function_test(TestGenerics, "test_generic_type_construction", test_generic_type_construction, devices=devices)
add_function_test(TestGenerics, "test_generic_scalar_construction", test_generic_scalar_construction, devices=devices)
add_function_test(TestGenerics, "test_generic_type_as_argument", test_generic_type_as_argument, devices=devices)
foo = Foo()
foo.x = 17.0
foo.y = 25.0
foo.z = 42.0
bar = Bar()
bar.x = wp.vec3(1, 2, 3)
bar.y = wp.vec3(10, 20, 30)
bar.z = wp.vec3(11, 22, 33)
add_kernel_test(
TestGenerics,
name="test_generic_struct_kernel",
kernel=test_generic_struct_kernel,
dim=1,
inputs=[foo],
devices=devices,
)
add_kernel_test(
TestGenerics,
name="test_generic_struct_kernel",
kernel=test_generic_struct_kernel,
dim=1,
inputs=[bar],
devices=devices,
)
add_kernel_test(
TestGenerics,
name="test_generic_struct_construction_kernel",
kernel=test_generic_struct_construction_kernel,
dim=1,
inputs=[foo],
devices=devices,
)
add_kernel_test(
TestGenerics,
name="test_generic_struct_construction_kernel",
kernel=test_generic_struct_construction_kernel,
dim=1,
inputs=[bar],
devices=devices,
)
add_function_test(TestGenerics, "test_type_operator_misspell", test_type_operator_misspell, devices=devices)
add_function_test(TestGenerics, "test_type_attribute_error", test_type_attribute_error, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 19,605 | Python | 33.396491 | 118 | 0.649222 |
NVIDIA/warp/warp/tests/test_fp16.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.kernel
def load_store_half(f32: wp.array(dtype=wp.float32), f16: wp.array(dtype=wp.float16)):
tid = wp.tid()
# check conversion from f32->f16
a = wp.float16(f32[tid])
b = f16[tid]
wp.expect_eq(a, b)
# check stores
f16[tid] = a
def test_fp16_conversion(test, device):
s = [1.0, 2.0, 3.0, -3.14159]
np_f32 = np.array(s, dtype=np.float32)
np_f16 = np.array(s, dtype=np.float16)
wp_f32 = wp.array(s, dtype=wp.float32, device=device)
wp_f16 = wp.array(s, dtype=wp.float16, device=device)
assert_np_equal(np_f32, wp_f32.numpy())
assert_np_equal(np_f16, wp_f16.numpy())
wp.launch(load_store_half, dim=len(s), inputs=[wp_f32, wp_f16], device=device)
# check that stores worked
assert_np_equal(np_f16, wp_f16.numpy())
@wp.kernel
def value_load_store_half(f16_value: wp.float16, f16_array: wp.array(dtype=wp.float16)):
wp.expect_eq(f16_value, f16_array[0])
# check stores
f16_array[0] = f16_value
def test_fp16_kernel_parameter(test, device):
"""Test the ability to pass in fp16 into kernels as parameters"""
s = [1.0, 2.0, 3.0, -3.14159]
for test_val in s:
np_f16 = np.array([test_val], dtype=np.float16)
wp_f16 = wp.array([test_val], dtype=wp.float16, device=device)
wp.launch(value_load_store_half, (1,), inputs=[wp.float16(test_val), wp_f16], device=device)
# check that stores worked
assert_np_equal(np_f16, wp_f16.numpy())
# Do the same thing but pass in test_val as a Python float to test automatic conversion
wp_f16 = wp.array([test_val], dtype=wp.float16, device=device)
wp.launch(value_load_store_half, (1,), inputs=[test_val, wp_f16], device=device)
assert_np_equal(np_f16, wp_f16.numpy())
@wp.kernel
def mul_half(input: wp.array(dtype=wp.float16), output: wp.array(dtype=wp.float16)):
tid = wp.tid()
# convert to compute type fp32
x = wp.float(input[tid]) * 2.0
# store back as fp16
output[tid] = wp.float16(x)
def test_fp16_grad(test, device):
rng = np.random.default_rng(123)
# checks that gradients are correctly propagated for
# fp16 arrays, even when intermediate calculations
# are performed in e.g.: fp32
s = rng.random(size=15).astype(np.float16)
input = wp.array(s, dtype=wp.float16, device=device, requires_grad=True)
output = wp.zeros_like(input)
tape = wp.Tape()
with tape:
wp.launch(mul_half, dim=len(s), inputs=[input, output], device=device)
ones = wp.array(np.ones(len(output)), dtype=wp.float16, device=device)
tape.backward(grads={output: ones})
assert_np_equal(input.grad.numpy(), np.ones(len(s)) * 2.0)
class TestFp16(unittest.TestCase):
pass
devices = []
if wp.is_cpu_available():
devices.append("cpu")
for cuda_device in get_selected_cuda_test_devices():
if cuda_device.arch >= 70:
devices.append(cuda_device)
add_function_test(TestFp16, "test_fp16_conversion", test_fp16_conversion, devices=devices)
add_function_test(TestFp16, "test_fp16_grad", test_fp16_grad, devices=devices)
add_function_test(TestFp16, "test_fp16_kernel_parameter", test_fp16_kernel_parameter, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 3,824 | Python | 28.651163 | 102 | 0.675209 |
NVIDIA/warp/warp/tests/test_intersect.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.kernel
def intersect_tri(
v0: wp.vec3, v1: wp.vec3, v2: wp.vec3, u0: wp.vec3, u1: wp.vec3, u2: wp.vec3, result: wp.array(dtype=int)
):
tid = wp.tid()
result[0] = wp.intersect_tri_tri(v0, v1, v2, u0, u1, u2)
def test_intersect_tri(test, device):
points_intersect = [
wp.vec3(0.0, 0.0, 0.0),
wp.vec3(1.0, 0.0, 0.0),
wp.vec3(0.0, 0.0, 1.0),
wp.vec3(0.5, -0.5, 0.0),
wp.vec3(0.5, -0.5, 1.0),
wp.vec3(0.5, 0.5, 0.0),
]
points_separated = [
wp.vec3(0.0, 0.0, 0.0),
wp.vec3(1.0, 0.0, 0.0),
wp.vec3(0.0, 0.0, 1.0),
wp.vec3(-0.5, -0.5, 0.0),
wp.vec3(-0.5, -0.5, 1.0),
wp.vec3(-0.5, 0.5, 0.0),
]
result = wp.zeros(1, dtype=int, device=device)
wp.launch(intersect_tri, dim=1, inputs=[*points_intersect, result], device=device)
assert_np_equal(result.numpy(), np.array([1]))
wp.launch(intersect_tri, dim=1, inputs=[*points_separated, result], device=device)
assert_np_equal(result.numpy(), np.array([0]))
devices = get_test_devices()
class TestIntersect(unittest.TestCase):
pass
add_function_test(TestIntersect, "test_intersect_tri", test_intersect_tri, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2, failfast=False)
| 1,855 | Python | 27.121212 | 109 | 0.638814 |
NVIDIA/warp/warp/tests/test_torch.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.kernel
def op_kernel(x: wp.array(dtype=float), y: wp.array(dtype=float)):
tid = wp.tid()
y[tid] = 0.5 - x[tid] * 2.0
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
@wp.kernel
def arange(start: int, step: int, a: wp.array(dtype=int)):
tid = wp.tid()
a[tid] = start + step * tid
# copy elements between non-contiguous 1d arrays of float
@wp.kernel
def copy1d_float_kernel(dst: wp.array(dtype=float), src: wp.array(dtype=float)):
i = wp.tid()
dst[i] = src[i]
# copy elements between non-contiguous 2d arrays of float
@wp.kernel
def copy2d_float_kernel(dst: wp.array2d(dtype=float), src: wp.array2d(dtype=float)):
i, j = wp.tid()
dst[i, j] = src[i, j]
# copy elements between non-contiguous 3d arrays of float
@wp.kernel
def copy3d_float_kernel(dst: wp.array3d(dtype=float), src: wp.array3d(dtype=float)):
i, j, k = wp.tid()
dst[i, j, k] = src[i, j, k]
# copy elements between non-contiguous 2d arrays of vec3
@wp.kernel
def copy2d_vec3_kernel(dst: wp.array2d(dtype=wp.vec3), src: wp.array2d(dtype=wp.vec3)):
i, j = wp.tid()
dst[i, j] = src[i, j]
# copy elements between non-contiguous 2d arrays of mat22
@wp.kernel
def copy2d_mat22_kernel(dst: wp.array2d(dtype=wp.mat22), src: wp.array2d(dtype=wp.mat22)):
i, j = wp.tid()
dst[i, j] = src[i, j]
def test_dtype_from_torch(test, device):
import torch
def test_conversions(torch_type, warp_type):
test.assertEqual(wp.dtype_from_torch(torch_type), warp_type)
test_conversions(torch.float16, wp.float16)
test_conversions(torch.float32, wp.float32)
test_conversions(torch.float64, wp.float64)
test_conversions(torch.int8, wp.int8)
test_conversions(torch.int16, wp.int16)
test_conversions(torch.int32, wp.int32)
test_conversions(torch.int64, wp.int64)
test_conversions(torch.uint8, wp.uint8)
test_conversions(torch.bool, wp.bool)
def test_dtype_to_torch(test, device):
import torch
def test_conversions(warp_type, torch_type):
test.assertEqual(wp.dtype_to_torch(warp_type), torch_type)
test_conversions(wp.float16, torch.float16)
test_conversions(wp.float32, torch.float32)
test_conversions(wp.float64, torch.float64)
test_conversions(wp.int8, torch.int8)
test_conversions(wp.int16, torch.int16)
test_conversions(wp.int32, torch.int32)
test_conversions(wp.int64, torch.int64)
test_conversions(wp.uint8, torch.uint8)
test_conversions(wp.uint16, torch.int16)
test_conversions(wp.uint32, torch.int32)
test_conversions(wp.uint64, torch.int64)
test_conversions(wp.bool, torch.bool)
def test_device_conversion(test, device):
torch_device = wp.device_to_torch(device)
warp_device = wp.device_from_torch(torch_device)
test.assertEqual(warp_device, device)
def test_torch_zerocopy(test, device):
import torch
a = wp.zeros(10, dtype=wp.float32, device=device)
t = wp.to_torch(a)
assert a.ptr == t.data_ptr()
torch_device = wp.device_to_torch(device)
t = torch.zeros(10, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
def test_from_torch(test, device):
import torch
torch_device = wp.device_to_torch(device)
# automatically determine warp dtype
def wrap_scalar_tensor_implicit(torch_dtype, expected_warp_dtype):
t = torch.zeros(10, dtype=torch_dtype, device=torch_device)
a = wp.from_torch(t)
assert a.dtype == expected_warp_dtype
assert a.shape == tuple(t.shape)
wrap_scalar_tensor_implicit(torch.float64, wp.float64)
wrap_scalar_tensor_implicit(torch.float32, wp.float32)
wrap_scalar_tensor_implicit(torch.float16, wp.float16)
wrap_scalar_tensor_implicit(torch.int64, wp.int64)
wrap_scalar_tensor_implicit(torch.int32, wp.int32)
wrap_scalar_tensor_implicit(torch.int16, wp.int16)
wrap_scalar_tensor_implicit(torch.int8, wp.int8)
wrap_scalar_tensor_implicit(torch.uint8, wp.uint8)
wrap_scalar_tensor_implicit(torch.bool, wp.bool)
# explicitly specify warp dtype
def wrap_scalar_tensor_explicit(torch_dtype, expected_warp_dtype):
t = torch.zeros(10, dtype=torch_dtype, device=torch_device)
a = wp.from_torch(t, expected_warp_dtype)
assert a.dtype == expected_warp_dtype
assert a.shape == tuple(t.shape)
wrap_scalar_tensor_explicit(torch.float64, wp.float64)
wrap_scalar_tensor_explicit(torch.float32, wp.float32)
wrap_scalar_tensor_explicit(torch.float16, wp.float16)
wrap_scalar_tensor_explicit(torch.int64, wp.int64)
wrap_scalar_tensor_explicit(torch.int64, wp.uint64)
wrap_scalar_tensor_explicit(torch.int32, wp.int32)
wrap_scalar_tensor_explicit(torch.int32, wp.uint32)
wrap_scalar_tensor_explicit(torch.int16, wp.int16)
wrap_scalar_tensor_explicit(torch.int16, wp.uint16)
wrap_scalar_tensor_explicit(torch.int8, wp.int8)
wrap_scalar_tensor_explicit(torch.int8, wp.uint8)
wrap_scalar_tensor_explicit(torch.uint8, wp.uint8)
wrap_scalar_tensor_explicit(torch.uint8, wp.int8)
wrap_scalar_tensor_explicit(torch.bool, wp.uint8)
wrap_scalar_tensor_explicit(torch.bool, wp.int8)
wrap_scalar_tensor_explicit(torch.bool, wp.bool)
def wrap_vec_tensor(n, desired_warp_dtype):
t = torch.zeros((10, n), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_vec_tensor(2, wp.vec2)
wrap_vec_tensor(3, wp.vec3)
wrap_vec_tensor(4, wp.vec4)
wrap_vec_tensor(6, wp.spatial_vector)
wrap_vec_tensor(7, wp.transform)
def wrap_mat_tensor(n, m, desired_warp_dtype):
t = torch.zeros((10, n, m), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_mat_tensor(2, 2, wp.mat22)
wrap_mat_tensor(3, 3, wp.mat33)
wrap_mat_tensor(4, 4, wp.mat44)
wrap_mat_tensor(6, 6, wp.spatial_matrix)
def wrap_vec_tensor_with_grad(n, desired_warp_dtype):
t = torch.zeros((10, n), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype, requires_grad=True)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_vec_tensor_with_grad(2, wp.vec2)
wrap_vec_tensor_with_grad(3, wp.vec3)
wrap_vec_tensor_with_grad(4, wp.vec4)
wrap_vec_tensor_with_grad(6, wp.spatial_vector)
wrap_vec_tensor_with_grad(7, wp.transform)
def wrap_mat_tensor_with_grad(n, m, desired_warp_dtype):
t = torch.zeros((10, n, m), dtype=torch.float32, device=torch_device)
a = wp.from_torch(t, desired_warp_dtype, requires_grad=True)
assert a.dtype == desired_warp_dtype
assert a.shape == (10,)
wrap_mat_tensor_with_grad(2, 2, wp.mat22)
wrap_mat_tensor_with_grad(3, 3, wp.mat33)
wrap_mat_tensor_with_grad(4, 4, wp.mat44)
wrap_mat_tensor_with_grad(6, 6, wp.spatial_matrix)
def test_to_torch(test, device):
import torch
def wrap_scalar_array(warp_dtype, expected_torch_dtype):
a = wp.zeros(10, dtype=warp_dtype, device=device)
t = wp.to_torch(a)
assert t.dtype == expected_torch_dtype
assert tuple(t.shape) == a.shape
wrap_scalar_array(wp.float64, torch.float64)
wrap_scalar_array(wp.float32, torch.float32)
wrap_scalar_array(wp.float16, torch.float16)
wrap_scalar_array(wp.int64, torch.int64)
wrap_scalar_array(wp.int32, torch.int32)
wrap_scalar_array(wp.int16, torch.int16)
wrap_scalar_array(wp.int8, torch.int8)
wrap_scalar_array(wp.uint8, torch.uint8)
wrap_scalar_array(wp.bool, torch.bool)
# not supported by torch
# wrap_scalar_array(wp.uint64, torch.int64)
# wrap_scalar_array(wp.uint32, torch.int32)
# wrap_scalar_array(wp.uint16, torch.int16)
def wrap_vec_array(n, warp_dtype):
a = wp.zeros(10, dtype=warp_dtype, device=device)
t = wp.to_torch(a)
assert t.dtype == torch.float32
assert tuple(t.shape) == (10, n)
wrap_vec_array(2, wp.vec2)
wrap_vec_array(3, wp.vec3)
wrap_vec_array(4, wp.vec4)
wrap_vec_array(6, wp.spatial_vector)
wrap_vec_array(7, wp.transform)
def wrap_mat_array(n, m, warp_dtype):
a = wp.zeros(10, dtype=warp_dtype, device=device)
t = wp.to_torch(a)
assert t.dtype == torch.float32
assert tuple(t.shape) == (10, n, m)
wrap_mat_array(2, 2, wp.mat22)
wrap_mat_array(3, 3, wp.mat33)
wrap_mat_array(4, 4, wp.mat44)
wrap_mat_array(6, 6, wp.spatial_matrix)
def test_from_torch_slices(test, device):
import torch
torch_device = wp.device_to_torch(device)
# 1D slice, contiguous
t_base = torch.arange(10, dtype=torch.float32, device=torch_device)
t = t_base[2:9]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert a.is_contiguous
assert a.shape == tuple(t.shape)
assert_np_equal(a.numpy(), t.cpu().numpy())
# 1D slice with non-contiguous stride
t_base = torch.arange(10, dtype=torch.float32, device=torch_device)
t = t_base[2:9:2]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy1d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 2D slices (non-contiguous)
t_base = torch.arange(24, dtype=torch.float32, device=torch_device).reshape((4, 6))
t = t_base[1:3, 2:5]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy2d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 3D slices (non-contiguous)
t_base = torch.arange(36, dtype=torch.float32, device=torch_device).reshape((4, 3, 3))
t = t_base[::2, 0:1, 1:2]
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 2D slices of vec3 (inner contiguous, outer non-contiguous)
t_base = torch.arange(150, dtype=torch.float32, device=torch_device).reshape((10, 5, 3))
t = t_base[1:7:2, 2:5]
a = wp.from_torch(t, dtype=wp.vec3)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape[:-1])
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy2d_vec3_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# 2D slices of mat22 (inner contiguous, outer non-contiguous)
t_base = torch.arange(200, dtype=torch.float32, device=torch_device).reshape((10, 5, 2, 2))
t = t_base[1:7:2, 2:5]
a = wp.from_torch(t, dtype=wp.mat22)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape[:-2])
# copy contents to contiguous array
a_contiguous = wp.empty_like(a)
wp.launch(copy2d_mat22_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
def test_from_torch_zero_strides(test, device):
import torch
torch_device = wp.device_to_torch(device)
t_base = torch.arange(9, dtype=torch.float32, device=torch_device).reshape((3, 3))
# expand outermost dimension
t = t_base.unsqueeze(0).expand(3, -1, -1)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# expand middle dimension
t = t_base.unsqueeze(1).expand(-1, 3, -1)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
# expand innermost dimension
t = t_base.unsqueeze(2).expand(-1, -1, 3)
a = wp.from_torch(t)
assert a.ptr == t.data_ptr()
assert not a.is_contiguous
assert a.shape == tuple(t.shape)
a_contiguous = wp.empty_like(a)
wp.launch(copy3d_float_kernel, dim=a.shape, inputs=[a_contiguous, a], device=device)
assert_np_equal(a_contiguous.numpy(), t.cpu().numpy())
def test_torch_mgpu_from_torch(test, device):
import torch
n = 32
t0 = torch.arange(0, n, 1, dtype=torch.int32, device="cuda:0")
t1 = torch.arange(0, n * 2, 2, dtype=torch.int32, device="cuda:1")
a0 = wp.from_torch(t0, dtype=wp.int32)
a1 = wp.from_torch(t1, dtype=wp.int32)
assert a0.device == "cuda:0"
assert a1.device == "cuda:1"
expected0 = np.arange(0, n, 1)
expected1 = np.arange(0, n * 2, 2)
assert_np_equal(a0.numpy(), expected0)
assert_np_equal(a1.numpy(), expected1)
def test_torch_mgpu_to_torch(test, device):
n = 32
with wp.ScopedDevice("cuda:0"):
a0 = wp.empty(n, dtype=wp.int32)
wp.launch(arange, dim=a0.size, inputs=[0, 1, a0])
with wp.ScopedDevice("cuda:1"):
a1 = wp.empty(n, dtype=wp.int32)
wp.launch(arange, dim=a1.size, inputs=[0, 2, a1])
t0 = wp.to_torch(a0)
t1 = wp.to_torch(a1)
assert str(t0.device) == "cuda:0"
assert str(t1.device) == "cuda:1"
expected0 = np.arange(0, n, 1, dtype=np.int32)
expected1 = np.arange(0, n * 2, 2, dtype=np.int32)
assert_np_equal(t0.cpu().numpy(), expected0)
assert_np_equal(t1.cpu().numpy(), expected1)
def test_torch_mgpu_interop(test, device):
import torch
n = 1024 * 1024
with torch.cuda.device(0):
t0 = torch.arange(n, dtype=torch.float32, device="cuda")
a0 = wp.from_torch(t0)
wp.launch(inc, dim=a0.size, inputs=[a0], stream=wp.stream_from_torch())
with torch.cuda.device(1):
t1 = torch.arange(n, dtype=torch.float32, device="cuda")
a1 = wp.from_torch(t1)
wp.launch(inc, dim=a1.size, inputs=[a1], stream=wp.stream_from_torch())
assert a0.device == "cuda:0"
assert a1.device == "cuda:1"
expected = np.arange(n, dtype=int) + 1
# ensure the torch tensors were modified by warp
assert_np_equal(t0.cpu().numpy(), expected)
assert_np_equal(t1.cpu().numpy(), expected)
def test_torch_autograd(test, device):
"""Test torch autograd with a custom Warp op"""
import torch
# custom autograd op
class TestFunc(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
# allocate output array
y = torch.empty_like(x)
ctx.x = x
ctx.y = y
wp.launch(kernel=op_kernel, dim=len(x), inputs=[wp.from_torch(x)], outputs=[wp.from_torch(y)])
return y
@staticmethod
def backward(ctx, adj_y):
# adjoints should be allocated as zero initialized
adj_x = torch.zeros_like(ctx.x).contiguous()
adj_y = adj_y.contiguous()
wp_x = wp.from_torch(ctx.x, grad=adj_x)
wp_y = wp.from_torch(ctx.y, grad=adj_y)
wp.launch(
kernel=op_kernel,
dim=len(ctx.x),
# fwd inputs
inputs=[wp_x],
outputs=[wp_y],
# adj inputs (already stored in input/output arrays, passing null pointers)
adj_inputs=[None],
adj_outputs=[None],
adjoint=True,
)
return adj_x
# run autograd on given device
with wp.ScopedDevice(device):
torch_device = wp.device_to_torch(device)
# input data
x = torch.ones(16, dtype=torch.float32, device=torch_device, requires_grad=True)
# execute op
y = TestFunc.apply(x)
# compute grads
l = y.sum()
l.backward()
passed = (x.grad == -2.0).all()
assert passed.item()
def test_torch_graph_torch_stream(test, device):
"""Capture Torch graph on Torch stream"""
wp.load_module(device=device)
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
g = torch.cuda.CUDAGraph()
# create a device-specific torch stream to use for capture
# (otherwise torch.cuda.graph reuses its capture stream, which can be problematic if it's from a different device)
torch_stream = torch.cuda.Stream(device=torch_device)
# make warp use the same stream
warp_stream = wp.stream_from_torch(torch_stream)
# capture graph
with wp.ScopedStream(warp_stream), torch.cuda.graph(g, stream=torch_stream):
wp.capture_begin(force_module_load=False, external=True)
try:
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
finally:
wp.capture_end()
# replay graph
num_iters = 10
for _i in range(num_iters):
g.replay()
passed = (t == num_iters * 4.0).all()
assert passed.item()
def test_torch_graph_warp_stream(test, device):
"""Capture Torch graph on Warp stream"""
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
g = torch.cuda.CUDAGraph()
# make torch use the warp stream from the given device
torch_stream = wp.stream_to_torch(device)
# capture graph
with wp.ScopedDevice(device), torch.cuda.graph(g, stream=torch_stream):
wp.capture_begin(force_module_load=False, external=True)
try:
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
finally:
wp.capture_end()
# replay graph
num_iters = 10
for _i in range(num_iters):
g.replay()
passed = (t == num_iters * 4.0).all()
assert passed.item()
def test_warp_graph_warp_stream(test, device):
"""Capture Warp graph on Warp stream"""
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
# make torch use the warp stream from the given device
torch_stream = wp.stream_to_torch(device)
# capture graph
with wp.ScopedDevice(device), torch.cuda.stream(torch_stream):
wp.capture_begin(force_module_load=False)
try:
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
finally:
g = wp.capture_end()
# replay graph
num_iters = 10
for _i in range(num_iters):
wp.capture_launch(g)
passed = (t == num_iters * 4.0).all()
assert passed.item()
def test_warp_graph_torch_stream(test, device):
"""Capture Warp graph on Torch stream"""
wp.load_module(device=device)
import torch
torch_device = wp.device_to_torch(device)
n = 1024 * 1024
t = torch.zeros(n, dtype=torch.float32, device=torch_device)
a = wp.from_torch(t)
# create a device-specific torch stream to use for capture
# (the default torch stream is not suitable for graph capture)
torch_stream = torch.cuda.Stream(device=torch_device)
# make warp use the same stream
warp_stream = wp.stream_from_torch(torch_stream)
# capture graph
with wp.ScopedStream(warp_stream), torch.cuda.stream(torch_stream):
wp.capture_begin(force_module_load=False)
try:
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
t += 1.0
wp.launch(inc, dim=n, inputs=[a])
finally:
g = wp.capture_end()
# replay graph
num_iters = 10
for _i in range(num_iters):
wp.capture_launch(g)
passed = (t == num_iters * 4.0).all()
assert passed.item()
class TestTorch(unittest.TestCase):
pass
test_devices = get_test_devices()
try:
import torch
# check which Warp devices work with Torch
# CUDA devices may fail if Torch was not compiled with CUDA support
torch_compatible_devices = []
torch_compatible_cuda_devices = []
for d in test_devices:
try:
t = torch.arange(10, device=wp.device_to_torch(d))
t += 1
torch_compatible_devices.append(d)
if d.is_cuda:
torch_compatible_cuda_devices.append(d)
except Exception as e:
print(f"Skipping Torch tests on device '{d}' due to exception: {e}")
add_function_test(TestTorch, "test_dtype_from_torch", test_dtype_from_torch, devices=None)
add_function_test(TestTorch, "test_dtype_to_torch", test_dtype_to_torch, devices=None)
if torch_compatible_devices:
add_function_test(TestTorch, "test_device_conversion", test_device_conversion, devices=torch_compatible_devices)
add_function_test(TestTorch, "test_from_torch", test_from_torch, devices=torch_compatible_devices)
add_function_test(TestTorch, "test_from_torch_slices", test_from_torch_slices, devices=torch_compatible_devices)
add_function_test(
TestTorch,
"test_from_torch_zero_strides",
test_from_torch_zero_strides,
devices=torch_compatible_devices,
)
add_function_test(TestTorch, "test_to_torch", test_to_torch, devices=torch_compatible_devices)
add_function_test(TestTorch, "test_torch_zerocopy", test_torch_zerocopy, devices=torch_compatible_devices)
add_function_test(TestTorch, "test_torch_autograd", test_torch_autograd, devices=torch_compatible_devices)
if torch_compatible_cuda_devices:
add_function_test(
TestTorch,
"test_torch_graph_torch_stream",
test_torch_graph_torch_stream,
devices=torch_compatible_cuda_devices,
)
add_function_test(
TestTorch,
"test_torch_graph_warp_stream",
test_torch_graph_warp_stream,
devices=torch_compatible_cuda_devices,
)
add_function_test(
TestTorch,
"test_warp_graph_warp_stream",
test_warp_graph_warp_stream,
devices=torch_compatible_cuda_devices,
)
add_function_test(
TestTorch,
"test_warp_graph_torch_stream",
test_warp_graph_torch_stream,
devices=torch_compatible_cuda_devices,
)
# multi-GPU tests
if len(torch_compatible_cuda_devices) > 1:
add_function_test(TestTorch, "test_torch_mgpu_from_torch", test_torch_mgpu_from_torch)
add_function_test(TestTorch, "test_torch_mgpu_to_torch", test_torch_mgpu_to_torch)
add_function_test(TestTorch, "test_torch_mgpu_interop", test_torch_mgpu_interop)
except Exception as e:
print(f"Skipping Torch tests due to exception: {e}")
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 24,392 | Python | 31.874663 | 120 | 0.638775 |
NVIDIA/warp/warp/tests/test_mesh.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
# fmt: off
POINT_POSITIONS = (
( 0.5, -0.5, 0.5),
(-0.5, -0.5, 0.5),
( 0.5, 0.5, 0.5),
(-0.5, 0.5, 0.5),
(-0.5, -0.5, -0.5),
( 0.5, -0.5, -0.5),
(-0.5, 0.5, -0.5),
( 0.5, 0.5, -0.5),
)
# Right-hand winding order. This corresponds to USD's (and others).
RIGHT_HANDED_FACE_VERTEX_INDICES = (
0, 3, 1,
0, 2, 3,
4, 7, 5,
4, 6, 7,
6, 2, 7,
6, 3, 2,
5, 1, 4,
5, 0, 1,
5, 2, 0,
5, 7, 2,
1, 6, 4,
1, 3, 6,
)
# Left-hand winding order. This corresponds to Houdini's (and others).
LEFT_HANDED_FACE_VERTEX_INDICES = (
0, 1, 3,
0, 3, 2,
4, 5, 7,
4, 7, 6,
6, 7, 2,
6, 2, 3,
5, 4, 1,
5, 1, 0,
5, 0, 2,
5, 2, 7,
1, 4, 6,
1, 6, 3,
)
# fmt: on
POINT_COUNT = 8
VERTEX_COUNT = 36
FACE_COUNT = 12
@wp.kernel(enable_backward=False)
def read_points_kernel(
mesh_id: wp.uint64,
out_points: wp.array(dtype=wp.vec3),
):
tid = wp.tid()
mesh = wp.mesh_get(mesh_id)
out_points[tid] = mesh.points[tid]
@wp.kernel(enable_backward=False)
def read_indices_kernel(
mesh_id: wp.uint64,
out_indices: wp.array(dtype=int),
):
tid = wp.tid()
mesh = wp.mesh_get(mesh_id)
out_indices[tid * 3 + 0] = mesh.indices[tid * 3 + 0]
out_indices[tid * 3 + 1] = mesh.indices[tid * 3 + 1]
out_indices[tid * 3 + 2] = mesh.indices[tid * 3 + 2]
def test_mesh_read_properties(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
mesh = wp.Mesh(points=points, indices=indices)
assert mesh.points.size == POINT_COUNT
assert mesh.indices.size == VERTEX_COUNT
assert int(mesh.indices.size / 3) == FACE_COUNT
out_points = wp.empty(POINT_COUNT, dtype=wp.vec3, device=device)
wp.launch(read_points_kernel, dim=POINT_COUNT, inputs=[mesh.id], outputs=[out_points], device=device)
assert_np_equal(out_points.numpy(), np.array(POINT_POSITIONS))
out_indices = wp.empty(VERTEX_COUNT, dtype=int, device=device)
wp.launch(read_indices_kernel, dim=FACE_COUNT, inputs=[mesh.id], outputs=[out_indices], device=device)
assert_np_equal(out_indices.numpy(), np.array(RIGHT_HANDED_FACE_VERTEX_INDICES))
@wp.kernel(enable_backward=False)
def query_point_kernel(
mesh_id: wp.uint64,
expected_sign: float,
):
point = wp.vec3(0.1, 0.2, 0.3)
expected_pos = wp.vec3(0.1, 0.2, 0.5)
sign = float(0.0)
face = int(0)
bary_u = float(0.0)
bary_v = float(0.0)
wp.mesh_query_point(mesh_id, point, 1e6, sign, face, bary_u, bary_v)
pos = wp.mesh_eval_position(mesh_id, face, bary_u, bary_v)
wp.expect_eq(wp.sign(sign), expected_sign)
wp.expect_eq(face, 1)
wp.expect_near(wp.length(pos - expected_pos), 0.0)
def test_mesh_query_point(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = -1.0
wp.launch(query_point_kernel, dim=1, inputs=[mesh.id, expected_sign], device=device)
indices = wp.array(LEFT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = 1.0
wp.launch(query_point_kernel, dim=1, inputs=[mesh.id, expected_sign], device=device)
@wp.kernel(enable_backward=False)
def query_ray_kernel(
mesh_id: wp.uint64,
expected_sign: float,
):
start = wp.vec3(0.1, 0.2, 0.3)
dir = wp.normalize(wp.vec3(-1.2, 2.3, -3.4))
expected_t = 0.557828
expected_pos = wp.vec3(-0.0565217, 0.5, -0.143478)
t = float(0.0)
bary_u = float(0.0)
bary_v = float(0.0)
sign = float(0.0)
normal = wp.vec3(0.0, 0.0, 0.0)
face = int(0)
wp.mesh_query_ray(
mesh_id,
start,
dir,
1e6,
t,
bary_u,
bary_v,
sign,
normal,
face,
)
pos = wp.mesh_eval_position(mesh_id, face, bary_u, bary_v)
wp.expect_near(t, expected_t)
wp.expect_near(t, wp.length(pos - start), 1e-6)
wp.expect_eq(wp.sign(sign), expected_sign)
wp.expect_eq(face, 4)
wp.expect_near(wp.length(pos - expected_pos), 0.0, 1e-6)
def test_mesh_query_ray(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = -1.0
wp.launch(
query_ray_kernel,
dim=1,
inputs=[
mesh.id,
expected_sign,
],
device=device,
)
indices = wp.array(LEFT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
mesh = wp.Mesh(points=points, indices=indices)
expected_sign = 1.0
wp.launch(
query_ray_kernel,
dim=1,
inputs=[
mesh.id,
expected_sign,
],
device=device,
)
def test_mesh_refit_graph(test, device):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
mesh = wp.Mesh(points=points, indices=indices)
wp.capture_begin(device, force_module_load=False)
try:
mesh.refit()
finally:
graph = wp.capture_end(device)
# replay
num_iters = 10
for _ in range(num_iters):
wp.capture_launch(graph)
wp.synchronize_device(device)
def test_mesh_exceptions(test, device):
# points and indices must be on same device
with test.assertRaises(RuntimeError):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device="cpu")
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
wp.Mesh(points=points, indices=indices)
# points must be vec3
with test.assertRaises(RuntimeError):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3d, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
wp.Mesh(points=points, indices=indices)
# velocities must be vec3
with test.assertRaises(RuntimeError):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
velocities = wp.zeros(points.shape, dtype=wp.vec3d, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
wp.Mesh(points=points, indices=indices, velocities=velocities)
# indices must be int32
with test.assertRaises(RuntimeError):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=wp.int64, device=device)
wp.Mesh(points=points, indices=indices)
# indices must be 1d
with test.assertRaises(RuntimeError):
points = wp.array(POINT_POSITIONS, dtype=wp.vec3, device=device)
indices = wp.array(RIGHT_HANDED_FACE_VERTEX_INDICES, dtype=int, device=device)
indices = indices.reshape((3, -1))
wp.Mesh(points=points, indices=indices)
devices = get_test_devices()
class TestMesh(unittest.TestCase):
pass
add_function_test(TestMesh, "test_mesh_read_properties", test_mesh_read_properties, devices=devices)
add_function_test(TestMesh, "test_mesh_query_point", test_mesh_query_point, devices=devices)
add_function_test(TestMesh, "test_mesh_query_ray", test_mesh_query_ray, devices=devices)
add_function_test(TestMesh, "test_mesh_refit_graph", test_mesh_refit_graph, devices=get_selected_cuda_test_devices())
add_function_test(TestMesh, "test_mesh_exceptions", test_mesh_exceptions, devices=get_selected_cuda_test_devices())
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 8,386 | Python | 28.741135 | 117 | 0.641426 |
NVIDIA/warp/warp/tests/test_lvalue.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.kernel
def rmw_array_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
foos[i] += wp.uint32(1)
def test_rmw_array(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=rmw_array_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.struct
class RmwFoo:
field: wp.uint32
@wp.kernel
def rmw_array_struct_kernel(foos: wp.array(dtype=RmwFoo)):
i = wp.tid()
foos[i].field += wp.uint32(1)
def test_rmw_array_struct(test, device):
foos = wp.zeros((10,), dtype=RmwFoo, device=device)
wp.launch(kernel=rmw_array_struct_kernel, dim=(10,), inputs=[foos], device=device)
expected = RmwFoo()
expected.field = 1
for f in foos.list():
test.assertEqual(f.field, expected.field)
@wp.func
def lookup(foos: wp.array(dtype=wp.uint32), index: int):
return foos[index]
@wp.kernel
def lookup_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
x = lookup(foos, i)
foos[i] = x + wp.uint32(1)
def test_lookup(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=lookup_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.func
def lookup3(foos: wp.array(dtype=wp.float32), index: int):
return foos[index]
@wp.kernel
def grad_kernel(foos: wp.array(dtype=wp.float32), bars: wp.array(dtype=wp.float32)):
i = wp.tid()
x = lookup3(foos, i)
bars[i] = x * wp.float32(i) + 1.0
def test_grad(test, device):
num = 10
data = np.linspace(20, 20 + num, num, endpoint=False, dtype=np.float32)
input = wp.array(data, device=device, requires_grad=True)
output = wp.zeros(num, dtype=wp.float32, device=device)
ones = wp.array(np.ones(len(output)), dtype=wp.float32, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel=grad_kernel, dim=(num,), inputs=[input], outputs=[output], device=device)
tape.backward(grads={output: ones})
# test forward results
for i, f in enumerate(output.list()):
test.assertEqual(f, data[i] * i + 1)
# test backward results
for i, f in enumerate(tape.gradients[input].list()):
test.assertEqual(f, i)
@wp.func
def lookup2(foos: wp.array(dtype=wp.uint32), index: int):
if index % 2 == 0:
x = foos[index]
x = wp.uint32(0)
return x
else:
return foos[index]
@wp.kernel
def lookup2_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
x = lookup2(foos, i)
foos[i] = x + wp.uint32(1)
def test_lookup2(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=lookup2_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.kernel
def unary_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
foos[i] = wp.uint32(-1)
x = -foos[i]
foos[i] = x
def test_unary(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=unary_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.kernel
def rvalue_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
if foos[i] < wp.uint32(1):
foos[i] = wp.uint32(1)
def test_rvalue(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=rvalue_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
# Tests, among other things, that assigning a reference to a new variable does
# not create a reference
@wp.kernel
def intermediate_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
x = foos[i]
x = x + wp.uint32(1)
foos[i] = x
def test_intermediate(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=intermediate_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.kernel
def array_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
foos[i] = wp.uint32(1)
def test_array_assign(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=array_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.func
def increment(arg: wp.uint32):
return arg + wp.uint32(1)
@wp.kernel
def array_call_kernel(foos: wp.array(dtype=wp.uint32)):
i = wp.tid()
foos[i] = increment(foos[i])
def test_array_call_assign(test, device):
arr = wp.zeros((10,), dtype=wp.uint32, device=device)
wp.launch(kernel=array_kernel, dim=(10,), inputs=[arr], device=device)
assert_np_equal(arr.numpy(), np.ones(10))
@wp.struct
class Foo:
field: wp.uint32
@wp.kernel
def array_struct_kernel(foos: wp.array(dtype=Foo)):
i = wp.tid()
foos[i].field = wp.uint32(1)
def test_array_struct_assign(test, device):
foos = wp.zeros((10,), dtype=Foo, device=device)
wp.launch(kernel=array_struct_kernel, dim=(10,), inputs=[foos], device=device)
expected = Foo()
expected.field = 1
test.assertEqual(expected.field, 1)
for f in foos.list():
test.assertEqual(f.field, 1)
@wp.struct
class Bar:
field: wp.uint32
@wp.struct
class Baz:
bar: Bar
@wp.kernel
def array_struct_struct_kernel(foos: wp.array(dtype=Baz)):
i = wp.tid()
foos[i].bar.field = wp.uint32(1)
def test_array_struct_struct_assign(test, device):
foos = wp.zeros((10,), dtype=Baz, device=device)
wp.launch(kernel=array_struct_struct_kernel, dim=(10,), inputs=[foos], device=device)
expected = Baz()
expected.bar.field = 1
test.assertEqual(expected.bar.field, 1)
for f in foos.list():
test.assertEqual(f.bar.field, 1)
@wp.struct
class S:
a: wp.uint32
b: wp.float32
@wp.struct
class F:
x: wp.float32
s: S
y: wp.int32
@wp.kernel
def complex_kernel(foos: wp.array(dtype=F)):
i = wp.tid()
foos[i].x += wp.float32(1.0)
foos[i].y = wp.int32(2)
foos[i].s.b += wp.float32(3.0)
foos[i].s.a = wp.uint32(foos[i].y)
def test_complex(test, device):
foos = wp.zeros((10,), dtype=F, device=device)
wp.launch(kernel=complex_kernel, dim=(10,), inputs=[foos], device=device)
expected = F()
expected.x = 1.0
expected.y = 2
expected.s.b = 3.0
expected.s.a = expected.y
for f in foos.list():
test.assertEqual(f.x, expected.x)
test.assertEqual(f.y, expected.y)
test.assertEqual(f.s.a, expected.s.a)
test.assertEqual(f.s.b, expected.s.b)
@wp.struct
class Svec:
a: wp.uint32
b: wp.vec2f
@wp.struct
class Fvec:
x: wp.vec2f
s: Svec
y: wp.int32
@wp.kernel
def swizzle_kernel(foos: wp.array(dtype=Fvec)):
i = wp.tid()
foos[i].x += wp.vec2f(1.0, 2.0)
foos[i].y = wp.int32(3)
foos[i].s.b = wp.vec2f(4.0, 5.0)
foos[i].s.b.y = wp.float32(6.0)
foos[i].s.b.x = foos[i].x.y
foos[i].s.a = wp.uint32(foos[i].y)
def test_swizzle(test, device):
foos = wp.zeros((10,), dtype=Fvec, device=device)
wp.launch(kernel=swizzle_kernel, dim=(10,), inputs=[foos], device=device)
expected = Fvec()
expected.x = wp.vec2f(1.0, 2.0)
expected.y = 3
expected.s.b = wp.vec2f(4.0, 5.0)
expected.s.b.y = 6.0
expected.s.b.x = expected.x.y
expected.s.a = expected.y
for f in foos.list():
test.assertEqual(f.x, expected.x)
test.assertEqual(f.y, expected.y)
test.assertEqual(f.s.a, expected.s.a)
test.assertEqual(f.s.b, expected.s.b)
@wp.kernel
def slice_kernel(a: wp.array2d(dtype=wp.vec3), b: wp.array2d(dtype=wp.vec3), c: wp.array2d(dtype=wp.vec3)):
tid = wp.tid()
c[tid][0] = a[tid][0] + b[tid][0]
def test_slice(test, device):
a = wp.full((1, 1), value=1.0, dtype=wp.vec3, requires_grad=True, device=device)
b = wp.full((1, 1), value=1.0, dtype=wp.vec3, requires_grad=True, device=device)
c = wp.zeros((1, 1), dtype=wp.vec3, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(kernel=slice_kernel, dim=1, inputs=[a, b], outputs=[c], device=device)
c.grad = wp.full((1, 1), value=1.0, dtype=wp.vec3, device=device)
tape.backward()
x = a.grad.list()[0]
y = b.grad.list()[0]
expected = wp.vec3(1.0)
test.assertEqual(x, expected)
test.assertEqual(y, expected)
devices = get_test_devices()
class TestLValue(unittest.TestCase):
def test_swizzle_error_invalid_attribute(self):
v = wp.vec3(1, 2, 3)
with self.assertRaisesRegex(AttributeError, r"'vec3f' object has no attribute 'foo'$"):
v.foo # noqa: B018
try:
v.bar = 123
except AttributeError:
self.fail()
add_function_test(TestLValue, "test_rmw_array", test_rmw_array, devices=devices)
add_function_test(TestLValue, "test_rmw_array_struct", test_rmw_array_struct, devices=devices)
add_function_test(TestLValue, "test_lookup", test_lookup, devices=devices)
add_function_test(TestLValue, "test_lookup2", test_lookup2, devices=devices)
add_function_test(TestLValue, "test_grad", test_grad, devices=devices)
add_function_test(TestLValue, "test_unary", test_unary, devices=devices)
add_function_test(TestLValue, "test_rvalue", test_rvalue, devices=devices)
add_function_test(TestLValue, "test_intermediate", test_intermediate, devices=devices)
add_function_test(TestLValue, "test_array_assign", test_array_assign, devices=devices)
add_function_test(TestLValue, "test_array_struct_assign", test_array_struct_assign, devices=devices)
add_function_test(TestLValue, "test_array_struct_struct_assign", test_array_struct_struct_assign, devices=devices)
add_function_test(TestLValue, "test_complex", test_complex, devices=devices)
add_function_test(TestLValue, "test_swizzle", test_swizzle, devices=devices)
add_function_test(TestLValue, "test_slice", test_slice, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 10,580 | Python | 24.192857 | 114 | 0.649811 |
NVIDIA/warp/warp/tests/test_mat_scalar_ops.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
np_signed_int_types = [
np.int8,
np.int16,
np.int32,
np.int64,
np.byte,
]
np_unsigned_int_types = [
np.uint8,
np.uint16,
np.uint32,
np.uint64,
np.ubyte,
]
np_int_types = np_signed_int_types + np_unsigned_int_types
np_float_types = [np.float16, np.float32, np.float64]
np_scalar_types = np_int_types + np_float_types
def randvals(rng, shape, dtype):
if dtype in np_float_types:
return rng.standard_normal(size=shape).astype(dtype)
elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]:
return rng.integers(1, high=3, size=shape, dtype=dtype)
return rng.integers(1, high=5, size=shape, dtype=dtype)
kernel_cache = {}
def getkernel(func, suffix=""):
key = func.__name__ + "_" + suffix
if key not in kernel_cache:
kernel_cache[key] = wp.Kernel(func=func, key=key)
return kernel_cache[key]
def get_select_kernel(dtype):
def output_select_kernel_fn(
input: wp.array(dtype=dtype),
index: int,
out: wp.array(dtype=dtype),
):
out[0] = input[index]
return getkernel(output_select_kernel_fn, suffix=dtype.__name__)
def test_arrays(test, device, dtype):
rng = np.random.default_rng(123)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
v2_np = randvals(rng, [10, 2, 2], dtype)
v3_np = randvals(rng, [10, 3, 3], dtype)
v4_np = randvals(rng, [10, 4, 4], dtype)
v5_np = randvals(rng, [10, 5, 5], dtype)
v32_np = randvals(rng, [10, 3, 2], dtype)
v2 = wp.array(v2_np, dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(v3_np, dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(v4_np, dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(v5_np, dtype=mat55, requires_grad=True, device=device)
v32 = wp.array(v32_np, dtype=mat32, requires_grad=True, device=device)
assert_np_equal(v2.numpy(), v2_np, tol=1.0e-6)
assert_np_equal(v3.numpy(), v3_np, tol=1.0e-6)
assert_np_equal(v4.numpy(), v4_np, tol=1.0e-6)
assert_np_equal(v5.numpy(), v5_np, tol=1.0e-6)
assert_np_equal(v32.numpy(), v32_np, tol=1.0e-6)
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
v2 = wp.array(v2_np, dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(v3_np, dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(v4_np, dtype=mat44, requires_grad=True, device=device)
assert_np_equal(v2.numpy(), v2_np, tol=1.0e-6)
assert_np_equal(v3.numpy(), v3_np, tol=1.0e-6)
assert_np_equal(v4.numpy(), v4_np, tol=1.0e-6)
def test_components(test, device, dtype):
# test accessing matrix components from Python - this is especially important
# for float16, which requires special handling internally
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat23 = wp.types.matrix(shape=(2, 3), dtype=wptype)
m = mat23(1, 2, 3, 4, 5, 6)
# test __getitem__ for row vectors
r0 = m[0]
r1 = m[1]
test.assertEqual(r0[0], 1)
test.assertEqual(r0[1], 2)
test.assertEqual(r0[2], 3)
test.assertEqual(r1[0], 4)
test.assertEqual(r1[1], 5)
test.assertEqual(r1[2], 6)
# test __getitem__ for individual components
test.assertEqual(m[0, 0], 1)
test.assertEqual(m[0, 1], 2)
test.assertEqual(m[0, 2], 3)
test.assertEqual(m[1, 0], 4)
test.assertEqual(m[1, 1], 5)
test.assertEqual(m[1, 2], 6)
# test __setitem__ for row vectors
m[0] = [7, 8, 9]
m[1] = [10, 11, 12]
test.assertEqual(m[0, 0], 7)
test.assertEqual(m[0, 1], 8)
test.assertEqual(m[0, 2], 9)
test.assertEqual(m[1, 0], 10)
test.assertEqual(m[1, 1], 11)
test.assertEqual(m[1, 2], 12)
# test __setitem__ for individual components
m[0, 0] = 13
m[0, 1] = 14
m[0, 2] = 15
m[1, 0] = 16
m[1, 1] = 17
m[1, 2] = 18
test.assertEqual(m[0, 0], 13)
test.assertEqual(m[0, 1], 14)
test.assertEqual(m[0, 2], 15)
test.assertEqual(m[1, 0], 16)
test.assertEqual(m[1, 1], 17)
test.assertEqual(m[1, 2], 18)
def test_constants(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
cm22 = wp.constant(mat22(22))
cm33 = wp.constant(mat33(33))
cm44 = wp.constant(mat44(44))
cm55 = wp.constant(mat55(55))
cm32 = wp.constant(mat32(32))
def check_matrix_constants():
wp.expect_eq(cm22, mat22(wptype(22)))
wp.expect_eq(cm33, mat33(wptype(33)))
wp.expect_eq(cm44, mat44(wptype(44)))
wp.expect_eq(cm55, mat55(wptype(55)))
wp.expect_eq(cm32, mat32(wptype(32)))
kernel = getkernel(check_matrix_constants, suffix=dtype.__name__)
if register_kernels:
return
def test_constructors(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_scalar_mat_constructor(
input: wp.array(dtype=wptype),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m2result = wptype(2) * mat22(input[0])
m3result = wptype(2) * mat33(input[0])
m4result = wptype(2) * mat44(input[0])
m5result = wptype(2) * mat55(input[0])
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m5result[i, j]
idx = idx + 1
def check_component_mat_constructor(
input: wp.array(dtype=wptype),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m2result = wptype(2) * mat22(input[0], input[1], input[2], input[3])
m3result = wptype(2) * mat33(
input[4],
input[5],
input[6],
input[7],
input[8],
input[9],
input[10],
input[11],
input[12],
)
m4result = wptype(2) * mat44(
input[13],
input[14],
input[15],
input[16],
input[17],
input[18],
input[19],
input[20],
input[21],
input[22],
input[23],
input[24],
input[25],
input[26],
input[27],
input[28],
)
m5result = wptype(2) * mat55(
input[29],
input[30],
input[31],
input[32],
input[33],
input[34],
input[35],
input[36],
input[37],
input[38],
input[39],
input[40],
input[41],
input[42],
input[43],
input[44],
input[45],
input[46],
input[47],
input[48],
input[49],
input[50],
input[51],
input[52],
input[53],
)
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m5result[i, j]
idx = idx + 1
def check_vector_mat_constructor(
input: wp.array(dtype=wptype),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m2result = wptype(2) * mat22(vec2(input[0], input[2]), vec2(input[1], input[3]))
m3result = wptype(2) * mat33(
vec3(input[4], input[7], input[10]),
vec3(input[5], input[8], input[11]),
vec3(input[6], input[9], input[12]),
)
m4result = wptype(2) * mat44(
vec4(input[13], input[17], input[21], input[25]),
vec4(input[14], input[18], input[22], input[26]),
vec4(input[15], input[19], input[23], input[27]),
vec4(input[16], input[20], input[24], input[28]),
)
m5result = wptype(2) * mat55(
vec5(input[29], input[34], input[39], input[44], input[49]),
vec5(input[30], input[35], input[40], input[45], input[50]),
vec5(input[31], input[36], input[41], input[46], input[51]),
vec5(input[32], input[37], input[42], input[47], input[52]),
vec5(input[33], input[38], input[43], input[48], input[53]),
)
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m5result[i, j]
idx = idx + 1
kernel = getkernel(check_scalar_mat_constructor, suffix=dtype.__name__)
compkernel = getkernel(check_component_mat_constructor, suffix=dtype.__name__)
veckernel = getkernel(check_vector_mat_constructor, suffix=dtype.__name__)
if register_kernels:
return
input = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device)
val = input.numpy()[0]
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * val * np.ones(2 * 2), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * val * np.ones(3 * 3), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * val * np.ones(4 * 4), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * val * np.ones(5 * 5), tol=tol)
if dtype in np_float_types:
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
test.assertEqual(tape.gradients[input].numpy()[0], 2)
tape.zero()
input = wp.array(randvals(rng, [2 * 2 + 3 * 3 + 4 * 4 + 5 * 5], dtype), requires_grad=True, device=device)
wp.launch(compkernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
assert_np_equal(2 * input.numpy(), outcomponents.numpy(), tol=10 * tol)
if dtype in np_float_types:
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(compkernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedgrads = np.zeros(len(input))
expectedgrads[idx] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
wp.launch(veckernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
assert_np_equal(2 * input.numpy(), outcomponents.numpy(), tol=10 * tol)
if dtype in np_float_types:
for idx in range(len(outcomponents)):
tape = wp.Tape()
with tape:
wp.launch(veckernel, dim=1, inputs=[input], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedgrads = np.zeros(len(input))
expectedgrads[idx] = 2
assert_np_equal(tape.gradients[input].numpy(), expectedgrads)
tape.zero()
def test_anon_type_instance(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def check_scalar_init(
input: wp.array(dtype=wptype),
output: wp.array(dtype=wptype),
):
m2result = wp.matrix(input[0], shape=(2, 2))
m3result = wp.matrix(input[1], shape=(3, 3))
m4result = wp.matrix(input[2], shape=(4, 4))
m5result = wp.matrix(input[3], shape=(5, 5))
m32result = wp.matrix(input[4], shape=(3, 2))
idx = 0
for i in range(2):
for j in range(2):
output[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
output[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
output[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
output[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
output[idx] = wptype(2) * m32result[i, j]
idx = idx + 1
def check_component_init(
input: wp.array(dtype=wptype),
output: wp.array(dtype=wptype),
):
m2result = wp.matrix(input[0], input[1], input[2], input[3], shape=(2, 2))
m3result = wp.matrix(
input[4], input[5], input[6], input[7], input[8], input[9], input[10], input[11], input[12], shape=(3, 3)
)
m4result = wp.matrix(
input[13],
input[14],
input[15],
input[16],
input[17],
input[18],
input[19],
input[20],
input[21],
input[22],
input[23],
input[24],
input[25],
input[26],
input[27],
input[28],
shape=(4, 4),
)
m5result = wp.matrix(
input[29],
input[30],
input[31],
input[32],
input[33],
input[34],
input[35],
input[36],
input[37],
input[38],
input[39],
input[40],
input[41],
input[42],
input[43],
input[44],
input[45],
input[46],
input[47],
input[48],
input[49],
input[50],
input[51],
input[52],
input[53],
shape=(5, 5),
)
m32result = wp.matrix(input[54], input[55], input[56], input[57], input[58], input[59], shape=(3, 2))
idx = 0
for i in range(2):
for j in range(2):
output[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
output[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
output[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
output[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
output[idx] = wptype(2) * m32result[i, j]
idx = idx + 1
scalar_kernel = getkernel(check_scalar_init, suffix=dtype.__name__)
component_kernel = getkernel(check_component_init, suffix=dtype.__name__)
output_select_kernel = get_select_kernel(wptype)
if register_kernels:
return
input = wp.array(randvals(rng, [5], dtype), requires_grad=True, device=device)
output = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2, dtype=wptype, requires_grad=True, device=device)
wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy()[:4], 2 * np.array([input.numpy()[0]] * 2 * 2), tol=1.0e-6)
assert_np_equal(output.numpy()[4:13], 2 * np.array([input.numpy()[1]] * 3 * 3), tol=1.0e-6)
assert_np_equal(output.numpy()[13:29], 2 * np.array([input.numpy()[2]] * 4 * 4), tol=1.0e-6)
assert_np_equal(output.numpy()[29:54], 2 * np.array([input.numpy()[3]] * 5 * 5), tol=1.0e-6)
assert_np_equal(output.numpy()[54:], 2 * np.array([input.numpy()[4]] * 3 * 2), tol=1.0e-6)
if dtype in np_float_types:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(len(output)):
tape = wp.Tape()
with tape:
wp.launch(scalar_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(input.numpy())
if i < 4:
expected[0] = 2
elif i < 13:
expected[1] = 2
elif i < 29:
expected[2] = 2
elif i < 54:
expected[3] = 2
else:
expected[4] = 2
assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol)
tape.reset()
tape.zero()
input = wp.array(randvals(rng, [2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2], dtype), requires_grad=True, device=device)
output = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2, dtype=wptype, requires_grad=True, device=device)
wp.launch(component_kernel, dim=1, inputs=[input], outputs=[output], device=device)
assert_np_equal(output.numpy(), 2 * input.numpy(), tol=1.0e-6)
if dtype in np_float_types:
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for i in range(len(output)):
tape = wp.Tape()
with tape:
wp.launch(component_kernel, dim=1, inputs=[input], outputs=[output], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[output, i], outputs=[out], device=device)
tape.backward(loss=out)
expected = np.zeros_like(input.numpy())
expected[i] = 2
assert_np_equal(tape.gradients[input].numpy(), expected, tol=tol)
tape.reset()
tape.zero()
def test_identity(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
def check_identity_mat(
output: wp.array(dtype=wptype),
):
m2result = wp.identity(dtype=wptype, n=2)
m3result = wp.identity(dtype=wptype, n=3)
m4result = wp.identity(dtype=wptype, n=4)
m5result = wp.identity(dtype=wptype, n=5)
idx = 0
for i in range(2):
for j in range(2):
output[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
output[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
output[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
output[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
id_kernel = getkernel(check_identity_mat, suffix=dtype.__name__)
if register_kernels:
return
output = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(id_kernel, dim=1, inputs=[], outputs=[output], device=device)
assert_np_equal(output.numpy()[:4], 2 * np.eye(2), tol=1.0e-6)
assert_np_equal(output.numpy()[4:13], 2 * np.eye(3), tol=1.0e-6)
assert_np_equal(output.numpy()[13:29], 2 * np.eye(4), tol=1.0e-6)
assert_np_equal(output.numpy()[29:], 2 * np.eye(5), tol=1.0e-6)
def test_indexing(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_indexing(
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2[0][i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3[0][i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4[0][i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5[0][i, j]
idx = idx + 1
kernel = getkernel(check_mat_indexing, suffix=dtype.__name__)
if register_kernels:
return
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * m3.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * m4.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * m5.numpy().reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
def test_equality(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
def check_mat_equality():
wp.expect_eq(
mat22(wptype(1.0), wptype(2.0), wptype(3.0), wptype(4.0)),
mat22(wptype(1.0), wptype(2.0), wptype(3.0), wptype(4.0)),
)
wp.expect_neq(
mat22(wptype(1.0), wptype(2.0), wptype(3.0), -wptype(4.0)),
mat22(wptype(1.0), wptype(2.0), wptype(3.0), wptype(4.0)),
)
wp.expect_eq(
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
)
wp.expect_neq(
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
mat33(
wptype(1.0),
wptype(2.0),
wptype(3.0),
-wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
),
)
wp.expect_eq(
mat44(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
mat44(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
)
wp.expect_neq(
mat44(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
mat44(
-wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
),
)
wp.expect_eq(
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
)
wp.expect_neq(
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
mat55(
wptype(1.0),
wptype(2.0),
wptype(3.0),
wptype(4.0),
wptype(5.0),
wptype(6.0),
wptype(7.0),
wptype(8.0),
wptype(9.0),
wptype(10.0),
wptype(11.0),
wptype(12.0),
wptype(13.0),
wptype(14.0),
wptype(15.0),
wptype(16.0),
-wptype(17.0),
wptype(18.0),
wptype(19.0),
wptype(20.0),
wptype(21.0),
wptype(22.0),
wptype(23.0),
wptype(24.0),
wptype(25.0),
),
)
kernel = getkernel(check_mat_equality, suffix=dtype.__name__)
if register_kernels:
return
wp.launch(kernel, dim=1, inputs=[], outputs=[], device=device)
def test_scalar_multiplication(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_scalar_mul(
s: wp.array(dtype=wptype),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
outcomponents_rightmul: wp.array(dtype=wptype),
):
m2result = s[0] * m2[0]
m3result = s[0] * m3[0]
m4result = s[0] * m4[0]
m5result = s[0] * m5[0]
m2resultright = m2[0] * s[0]
m3resultright = m3[0] * s[0]
m4resultright = m4[0] * s[0]
m5resultright = m5[0] * s[0]
m2result_2 = s[0] * m2[0]
m3result_2 = s[0] * m3[0]
m4result_2 = s[0] * m4[0]
m5result_2 = s[0] * m5[0]
m2resultright_2 = m2[0] * s[0]
m3resultright_2 = m3[0] * s[0]
m4resultright_2 = m4[0] * s[0]
m5resultright_2 = m5[0] * s[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m2resultright[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m3resultright[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m4resultright[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5result[i, j]
outcomponents_rightmul[idx] = wptype(2) * m5resultright[i, j]
idx = idx + 1
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m2resultright_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m3resultright_2[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m4resultright_2[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5result_2[i, j]
outcomponents_rightmul[idx] = wptype(2) * m5resultright_2[i, j]
idx = idx + 1
kernel = getkernel(check_mat_scalar_mul, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device)
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * (2 * 2 + 3 * 3 + 4 * 4 + 5 * 5), dtype=wptype, requires_grad=True, device=device)
outcomponents_rightmul = wp.zeros(
2 * (2 * 2 + 3 * 3 + 4 * 4 + 5 * 5), dtype=wptype, requires_grad=True, device=device
)
wp.launch(kernel, dim=1, inputs=[s, m2, m3, m4, m5], outputs=[outcomponents, outcomponents_rightmul], device=device)
sval = s.numpy()[0]
assert_np_equal(outcomponents.numpy()[:4], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[:4], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents_rightmul.numpy()[4:13], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[13:29], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[29:54], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[54:58], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[58:67], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[67:83], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[83:108], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[54:58], 2 * sval * m2.numpy().reshape(-1), tol=tol)
assert_np_equal(outcomponents_rightmul.numpy()[58:67], 2 * sval * m3.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[67:83], 2 * sval * m4.numpy().reshape(-1), tol=10 * tol)
assert_np_equal(outcomponents_rightmul.numpy()[83:108], 2 * sval * m5.numpy().reshape(-1), tol=10 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
# test left mul gradient:
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, m2, m3, m4, m5],
outputs=[outcomponents, outcomponents_rightmul],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2 * sval
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult, tol=10 * tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * input.numpy()[0, i, j], tol=10 * tol)
tape.zero()
# test right mul gradient:
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[s, m2, m3, m4, m5],
outputs=[outcomponents, outcomponents_rightmul],
device=device,
)
wp.launch(
output_select_kernel,
dim=1,
inputs=[outcomponents_rightmul, idx],
outputs=[out],
device=device,
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2 * sval
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult, tol=10 * tol)
assert_np_equal(tape.gradients[s].numpy()[0], 2 * input.numpy()[0, i, j], tol=10 * tol)
tape.zero()
idx = idx + 1
def test_matvec_multiplication(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_vec_mul(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v32: wp.array(dtype=vec2),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
m32: wp.array(dtype=mat32),
outcomponents: wp.array(dtype=wptype),
):
v2result = m2[0] * v2[0]
v3result = m3[0] * v3[0]
v4result = m4[0] * v4[0]
v5result = m5[0] * v5[0]
v32result = m32[0] * v32[0]
v2result_2 = m2[0] @ v2[0]
v3result_2 = m3[0] @ v3[0]
v4result_2 = m4[0] @ v4[0]
v5result_2 = m5[0] @ v5[0]
v32result_2 = m32[0] @ v32[0]
idx = 0
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(2):
outcomponents[idx] = wptype(2) * v2result[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v3result[i]
idx = idx + 1
for i in range(4):
outcomponents[idx] = wptype(2) * v4result[i]
idx = idx + 1
for i in range(5):
outcomponents[idx] = wptype(2) * v5result[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v32result[i]
idx = idx + 1
for i in range(2):
outcomponents[idx] = wptype(2) * v2result_2[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v3result_2[i]
idx = idx + 1
for i in range(4):
outcomponents[idx] = wptype(2) * v4result_2[i]
idx = idx + 1
for i in range(5):
outcomponents[idx] = wptype(2) * v5result_2[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v32result_2[i]
idx = idx + 1
kernel = getkernel(check_mat_vec_mul, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals(rng, [1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4], dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5], dtype), dtype=vec5, requires_grad=True, device=device)
v32 = wp.array(randvals(rng, [1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m32 = wp.array(randvals(rng, [1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * (2 + 3 + 4 + 5 + 3), dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:2], 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[2:5], 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[5:9], 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[9:14], 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[14:17], 2 * np.matmul(m32.numpy()[0], v32.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[17:19], 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[19:22], 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents.numpy()[22:26], 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[26:31], 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents.numpy()[31:34], 2 * np.matmul(m32.numpy()[0], v32.numpy()[0]), tol=5 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, invec, inmat in [(2, v2, m2), (3, v3, m3), (4, v4, m4), (5, v5, m5), (3, v32, m32)]:
for i in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32],
outputs=[outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(tape.gradients[invec].numpy()[0], 2 * inmat.numpy()[0, i, :], tol=2 * tol)
expectedresult = np.zeros(inmat.dtype._shape_, dtype=dtype)
expectedresult[i, :] = 2 * invec.numpy()[0]
assert_np_equal(tape.gradients[inmat].numpy()[0], expectedresult, tol=2 * tol)
tape.zero()
idx = idx + 1
def test_vecmat_multiplication(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat23 = wp.types.matrix(shape=(2, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_vec_mat_mul(
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
v32: wp.array(dtype=vec2),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
m23: wp.array(dtype=mat23),
outcomponents: wp.array(dtype=wptype),
):
v2result = v2[0] * m2[0]
v3result = v3[0] * m3[0]
v4result = v4[0] * m4[0]
v5result = v5[0] * m5[0]
v32result = v32[0] * m23[0]
v2result_2 = v2[0] @ m2[0]
v3result_2 = v3[0] @ m3[0]
v4result_2 = v4[0] @ m4[0]
v5result_2 = v5[0] @ m5[0]
v32result_2 = v32[0] @ m23[0]
idx = 0
# multiply outputs by 2 so we've got something to backpropagate:
for i in range(2):
outcomponents[idx] = wptype(2) * v2result[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v3result[i]
idx = idx + 1
for i in range(4):
outcomponents[idx] = wptype(2) * v4result[i]
idx = idx + 1
for i in range(5):
outcomponents[idx] = wptype(2) * v5result[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v32result[i]
idx = idx + 1
for i in range(2):
outcomponents[idx] = wptype(2) * v2result_2[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v3result_2[i]
idx = idx + 1
for i in range(4):
outcomponents[idx] = wptype(2) * v4result_2[i]
idx = idx + 1
for i in range(5):
outcomponents[idx] = wptype(2) * v5result_2[i]
idx = idx + 1
for i in range(3):
outcomponents[idx] = wptype(2) * v32result_2[i]
idx = idx + 1
kernel = getkernel(check_vec_mat_mul, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals(rng, [1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4], dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5], dtype), dtype=vec5, requires_grad=True, device=device)
v32 = wp.array(randvals(rng, [1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m23 = wp.array(randvals(rng, [1, 2, 3], dtype), dtype=mat23, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * (2 + 3 + 4 + 5 + 3), dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m23], outputs=[outcomponents], device=device)
outcomponents_np = outcomponents.numpy()
assert_np_equal(outcomponents_np[:2], 2 * np.matmul(v2.numpy()[0], m2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[2:5], 2 * np.matmul(v3.numpy()[0], m3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[5:9], 2 * np.matmul(v4.numpy()[0], m4.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[9:14], 2 * np.matmul(v5.numpy()[0], m5.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[14:17], 2 * np.matmul(v32.numpy()[0], m23.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[17:19], 2 * np.matmul(v2.numpy()[0], m2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[19:22], 2 * np.matmul(v3.numpy()[0], m3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[22:26], 2 * np.matmul(v4.numpy()[0], m4.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[26:31], 2 * np.matmul(v5.numpy()[0], m5.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[31:34], 2 * np.matmul(v32.numpy()[0], m23.numpy()[0]), tol=5 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, inmat, invec in [(2, m2, v2), (3, m3, v3), (4, m4, v4), (5, m5, v5), (3, m23, v32)]:
for i in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m23],
outputs=[outcomponents],
device=device,
)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
assert_np_equal(tape.gradients[invec].numpy()[0], 2 * inmat.numpy()[0, :, i], tol=2 * tol)
expectedresult = np.zeros(inmat.dtype._shape_, dtype=dtype)
expectedresult[:, i] = 2 * invec.numpy()[0]
assert_np_equal(tape.gradients[inmat].numpy()[0], expectedresult, tol=2 * tol)
tape.zero()
idx = idx + 1
def test_matmat_multiplication(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_mat_mul(
a2: wp.array(dtype=mat22),
a3: wp.array(dtype=mat33),
a4: wp.array(dtype=mat44),
a5: wp.array(dtype=mat55),
a32: wp.array(dtype=mat32),
b2: wp.array(dtype=mat22),
b3: wp.array(dtype=mat33),
b4: wp.array(dtype=mat44),
b5: wp.array(dtype=mat55),
b32: wp.array(dtype=mat32),
outcomponents: wp.array(dtype=wptype),
):
c2result = b2[0] * a2[0]
c3result = b3[0] * a3[0]
c4result = b4[0] * a4[0]
c5result = b5[0] * a5[0]
c32result = b32[0] * a2[0]
c32result2 = b3[0] * a32[0]
c2result_2 = b2[0] @ a2[0]
c3result_2 = b3[0] @ a3[0]
c4result_2 = b4[0] @ a4[0]
c5result_2 = b5[0] @ a5[0]
c32result_2 = b32[0] @ a2[0]
c32result2_2 = b3[0] @ a32[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * c2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * c3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * c4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * c5result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result2[i, j]
idx = idx + 1
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * c2result_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * c3result_2[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * c4result_2[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * c5result_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result_2[i, j]
idx = idx + 1
for i in range(3):
for j in range(2):
outcomponents[idx] = wptype(2) * c32result2_2[i, j]
idx = idx + 1
kernel = getkernel(check_mat_mat_mul, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v32 = wp.array(randvals(rng, [1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m32 = wp.array(randvals(rng, [1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
outcomponents = wp.zeros(
2 * (2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 3 * 2 + 3 * 2), dtype=wptype, requires_grad=True, device=device
)
wp.launch(kernel, dim=1, inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
outcomponents_np = outcomponents.numpy()
assert_np_equal(outcomponents_np[:4].reshape((2, 2)), 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[4:13].reshape((3, 3)), 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[13:29].reshape((4, 4)), 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=2 * tol)
assert_np_equal(outcomponents_np[29:54].reshape((5, 5)), 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=10 * tol)
assert_np_equal(outcomponents_np[54:60].reshape((3, 2)), 2 * np.matmul(m32.numpy()[0], v2.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[60:66].reshape((3, 2)), 2 * np.matmul(m3.numpy()[0], v32.numpy()[0]), tol=5 * tol)
assert_np_equal(outcomponents_np[66:70].reshape((2, 2)), 2 * np.matmul(m2.numpy()[0], v2.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[70:79].reshape((3, 3)), 2 * np.matmul(m3.numpy()[0], v3.numpy()[0]), tol=tol)
assert_np_equal(outcomponents_np[79:95].reshape((4, 4)), 2 * np.matmul(m4.numpy()[0], v4.numpy()[0]), tol=2 * tol)
assert_np_equal(outcomponents_np[95:120].reshape((5, 5)), 2 * np.matmul(m5.numpy()[0], v5.numpy()[0]), tol=10 * tol)
assert_np_equal(
outcomponents_np[120:126].reshape((3, 2)), 2 * np.matmul(m32.numpy()[0], v2.numpy()[0]), tol=5 * tol
)
assert_np_equal(
outcomponents_np[126:132].reshape((3, 2)), 2 * np.matmul(m3.numpy()[0], v32.numpy()[0]), tol=5 * tol
)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for v, m in [(v2, m2), (v3, m3), (v4, m4), (v5, m5), (v2, m32), (v32, m3)]:
rows, cols = m.dtype._shape_[0], v.dtype._shape_[1]
for i in range(rows):
for j in range(cols):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[v2, v3, v4, v5, v32, m2, m3, m4, m5, m32],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expected = np.zeros(v.dtype._shape_, dtype=dtype)
expected[:, j] = 2 * m.numpy()[0, i, :]
assert_np_equal(tape.gradients[v].numpy()[0], expected, tol=10 * tol)
expected = np.zeros(m.dtype._shape_, dtype=dtype)
expected[i, :] = 2 * v.numpy()[0, :, j]
assert_np_equal(tape.gradients[m].numpy()[0], expected, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_cw_multiplication(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 5.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_cw_mul(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
v2result = wptype(2) * wp.cw_mul(v2[0], s2[0])
v3result = wptype(2) * wp.cw_mul(v3[0], s3[0])
v4result = wptype(2) * wp.cw_mul(v4[0], s4[0])
v5result = wptype(2) * wp.cw_mul(v5[0], s5[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_cw_mul, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
outcomponents_np = outcomponents.numpy()
assert_np_equal(outcomponents_np[:4], 2 * (v2.numpy() * s2.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents_np[4:13], 2 * (v3.numpy() * s3.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents_np[13:29], 2 * (v4.numpy() * s4.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents_np[29:54], 2 * (v5.numpy() * s5.numpy()).reshape(-1), tol=50 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2 * in1.numpy()[0][i, j]
assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=5 * tol)
expectedresult[i, j] = 2 * in2.numpy()[0][i, j]
assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=5 * tol)
tape.zero()
idx = idx + 1
def test_cw_division(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_cw_div(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
v2result = wptype(2) * wp.cw_div(v2[0], s2[0])
v3result = wptype(2) * wp.cw_div(v3[0], s3[0])
v4result = wptype(2) * wp.cw_div(v4[0], s4[0])
v5result = wptype(2) * wp.cw_div(v5[0], s5[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_cw_div, suffix=dtype.__name__)
if register_kernels:
return
s2 = randvals(rng, [1, 2, 2], dtype)
s3 = randvals(rng, [1, 3, 3], dtype)
s4 = randvals(rng, [1, 4, 4], dtype)
s5 = randvals(rng, [1, 5, 5], dtype)
# set denominators to 1 if their magnitudes are small
# to prevent divide by zero, or overflows if we're testing
# float16:
s2[np.abs(s2) < 1.0e-2] = 1
s3[np.abs(s3) < 1.0e-2] = 1
s4[np.abs(s4) < 1.0e-2] = 1
s5[np.abs(s5) < 1.0e-2] = 1
s2 = wp.array(s2, dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(s3, dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(s4, dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(s5, dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
if dtype in np_float_types:
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() / s2.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() / s3.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() / s4.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() / s5.numpy()).reshape(-1), tol=50 * tol)
else:
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() // s2.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() // s3.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() // s4.numpy()).reshape(-1), tol=50 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() // s5.numpy()).reshape(-1), tol=50 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, s, v in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
# y = v/s
# dy/dv = 1.0/s
# dy/ds = -v/s^2
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2.0 / (s.numpy()[0, i, j])
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=50 * tol)
expectedresult[i, j] = -2.0 * v.numpy()[0, i, j] / (s.numpy()[0, i, j] ** 2)
assert_np_equal(
tape.gradients[s].numpy()[0], expectedresult, tol=abs(outcomponents.numpy()[idx]) * 50 * tol
)
tape.zero()
idx = idx + 1
def test_outer_product(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec2 = wp.types.vector(length=2, dtype=wptype)
vec3 = wp.types.vector(length=3, dtype=wptype)
vec4 = wp.types.vector(length=4, dtype=wptype)
vec5 = wp.types.vector(length=5, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_outer_product(
s2: wp.array(dtype=vec2),
s3: wp.array(dtype=vec3),
s4: wp.array(dtype=vec4),
s5: wp.array(dtype=vec5),
v2: wp.array(dtype=vec2),
v3: wp.array(dtype=vec3),
v4: wp.array(dtype=vec4),
v5: wp.array(dtype=vec5),
outcomponents: wp.array(dtype=wptype),
):
m22result = wptype(2) * wp.outer(s2[0], v2[0])
m33result = wptype(2) * wp.outer(s3[0], v3[0])
m44result = wptype(2) * wp.outer(s4[0], v4[0])
m55result = wptype(2) * wp.outer(s5[0], v5[0])
m25result = wptype(2) * wp.outer(s2[0], v5[0])
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = m22result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = m33result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = m44result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = m55result[i, j]
idx = idx + 1
for i in range(2):
for j in range(5):
outcomponents[idx] = m25result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_outer_product, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals(rng, [1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
s3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
s4 = wp.array(randvals(rng, [1, 4], dtype), dtype=vec4, requires_grad=True, device=device)
s5 = wp.array(randvals(rng, [1, 5], dtype), dtype=vec5, requires_grad=True, device=device)
v2 = wp.array(randvals(rng, [1, 2], dtype), dtype=vec2, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4], dtype), dtype=vec4, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5], dtype), dtype=vec5, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 2 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s2, s3, s4, s5, v2, v3, v4, v5], outputs=[outcomponents], device=device)
outcomponents_np = outcomponents.numpy()
assert_np_equal(outcomponents_np[:4].reshape((2, 2)), 2 * s2.numpy()[0, :, None] * v2.numpy()[0, None, :], tol=tol)
assert_np_equal(
outcomponents_np[4:13].reshape((3, 3)), 2 * s3.numpy()[0, :, None] * v3.numpy()[0, None, :], tol=10 * tol
)
assert_np_equal(
outcomponents_np[13:29].reshape((4, 4)), 2 * s4.numpy()[0, :, None] * v4.numpy()[0, None, :], tol=10 * tol
)
assert_np_equal(
outcomponents_np[29:54].reshape((5, 5)), 2 * s5.numpy()[0, :, None] * v5.numpy()[0, None, :], tol=10 * tol
)
assert_np_equal(
outcomponents_np[54:].reshape(2, 5), 2 * s2.numpy()[0, :, None] * v5.numpy()[0, None, :], tol=10 * tol
)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for s, v in [(s2, v2), (s3, v3), (s4, v4), (s5, v5), (s2, v5)]:
rows = s.dtype._length_
cols = v.dtype._length_
for i in range(rows):
for j in range(cols):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
# this component's gonna be s_i * v_j, so its s gradient is gonna be nozero
# at the ith component and its v gradient will be nonzero at the jth component:
expectedresult = np.zeros((rows), dtype=dtype)
expectedresult[i] = 2 * v.numpy()[0, j]
assert_np_equal(tape.gradients[s].numpy()[0], expectedresult, tol=10 * tol)
expectedresult = np.zeros((cols), dtype=dtype)
expectedresult[j] = 2 * s.numpy()[0, i]
assert_np_equal(tape.gradients[v].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_transpose(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat32 = wp.types.matrix(shape=(3, 2), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_transpose(
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
m32: wp.array(dtype=mat32),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
mat2 = wptype(2) * wp.transpose(m2[0])
mat3 = wptype(2) * wp.transpose(m3[0])
mat4 = wptype(2) * wp.transpose(m4[0])
mat5 = wptype(2) * wp.transpose(m5[0])
mat32 = wptype(2) * wp.transpose(m32[0])
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = mat2[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = mat3[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = mat4[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = mat5[i, j]
idx = idx + 1
for i in range(2):
for j in range(3):
outcomponents[idx] = mat32[i, j]
idx = idx + 1
kernel = getkernel(check_mat_transpose, suffix=dtype.__name__)
if register_kernels:
return
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
m32 = wp.array(randvals(rng, [1, 3, 2], dtype), dtype=mat32, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5 + 2 * 3, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.numpy()[:4], 2 * m2.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * m3.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * m4.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * m5.numpy()[0].T.reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[54:], 2 * m32.numpy()[0].T.reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for input in [m2, m3, m4, m5]:
for i in range(input.dtype._shape_[0]):
for j in range(input.dtype._shape_[1]):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5, m32], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((input.dtype._shape_[1], input.dtype._shape_[0]), dtype=dtype)
expectedresult[j, i] = 2
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
tape.zero()
idx = idx + 1
def test_scalar_division(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-2,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_scalar_div(
s: wp.array(dtype=wptype),
m2: wp.array(dtype=mat22),
m3: wp.array(dtype=mat33),
m4: wp.array(dtype=mat44),
m5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
m2result = m2[0] / s[0]
m3result = m3[0] / s[0]
m4result = m4[0] / s[0]
m5result = m5[0] / s[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * m2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * m3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * m4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * m5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_scalar_div, suffix=dtype.__name__)
if register_kernels:
return
s = wp.array(randvals(rng, [1], dtype), requires_grad=True, device=device)
m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s, m2, m3, m4, m5], outputs=[outcomponents], device=device)
sval = s.numpy()[0]
if dtype in np_float_types:
assert_np_equal(outcomponents.numpy()[:4], 2 * m2.numpy().reshape(-1) / sval, tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * m3.numpy().reshape(-1) / sval, tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * m4.numpy().reshape(-1) / sval, tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * m5.numpy().reshape(-1) / sval, tol=10 * tol)
else:
assert_np_equal(outcomponents.numpy()[:4], 2 * (m2.numpy().reshape(-1) // sval), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (m3.numpy().reshape(-1) // sval), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (m4.numpy().reshape(-1) // sval), tol=10 * tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (m5.numpy().reshape(-1) // sval), tol=10 * tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s, m2, m3, m4, m5], outputs=[outcomponents], device=device)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2.0 / sval
assert_np_equal(tape.gradients[input].numpy()[0], expectedresult, tol=10 * tol)
assert_np_equal(
tape.gradients[s].numpy()[0], -2 * input.numpy()[0, i, j] / (sval * sval), tol=10 * tol
)
tape.zero()
idx = idx + 1
def test_addition(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 2.0e-2,
np.float32: 5.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_add(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
outcomponents: wp.array(dtype=wptype),
):
v2result = v2[0] + s2[0]
v3result = v3[0] + s3[0]
v4result = v4[0] + s4[0]
v5result = v5[0] + s5[0]
# multiply outputs by 2 so we've got something to backpropagate:
idx = 0
for i in range(2):
for j in range(2):
outcomponents[idx] = wptype(2) * v2result[i, j]
idx = idx + 1
for i in range(3):
for j in range(3):
outcomponents[idx] = wptype(2) * v3result[i, j]
idx = idx + 1
for i in range(4):
for j in range(4):
outcomponents[idx] = wptype(2) * v4result[i, j]
idx = idx + 1
for i in range(5):
for j in range(5):
outcomponents[idx] = wptype(2) * v5result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_add, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() + s2.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() + s3.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() + s4.numpy()).reshape(-1), tol=tol)
assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() + s5.numpy()).reshape(-1), tol=tol)
if dtype in np_float_types:
idx = 0
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
for i in range(dim):
for j in range(dim):
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[outcomponents],
device=device,
)
wp.launch(
output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
)
tape.backward(loss=out)
expectedresult = np.zeros((dim, dim), dtype=dtype)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
expectedresult[i, j] = 2
assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_ddot(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 5.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
def check_mat_dot(
s2: wp.array(dtype=mat22),
s3: wp.array(dtype=mat33),
s4: wp.array(dtype=mat44),
s5: wp.array(dtype=mat55),
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
dot2: wp.array(dtype=wptype),
dot3: wp.array(dtype=wptype),
dot4: wp.array(dtype=wptype),
dot5: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
dot2[0] = wptype(2) * wp.ddot(v2[0], s2[0])
dot3[0] = wptype(2) * wp.ddot(v3[0], s3[0])
dot4[0] = wptype(2) * wp.ddot(v4[0], s4[0])
dot5[0] = wptype(2) * wp.ddot(v5[0], s5[0])
kernel = getkernel(check_mat_dot, suffix=dtype.__name__)
if register_kernels:
return
s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
dot2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
dot3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
dot4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
dot5 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
s2,
s3,
s4,
s5,
v2,
v3,
v4,
v5,
],
outputs=[dot2, dot3, dot4, dot5],
device=device,
)
assert_np_equal(dot2.numpy()[0], 2 * (v2.numpy() * s2.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot3.numpy()[0], 2 * (v3.numpy() * s3.numpy()).sum(), tol=10 * tol)
assert_np_equal(dot4.numpy()[0], 2 * (v4.numpy() * s4.numpy()).sum(), tol=50 * tol)
assert_np_equal(dot5.numpy()[0], 2 * (v5.numpy() * s5.numpy()).sum(), tol=200 * tol)
if dtype in np_float_types:
tape.backward(loss=dot2)
sgrads = tape.gradients[s2].numpy()[0]
expected_grads = 2.0 * v2.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v2].numpy()[0]
expected_grads = 2.0 * s2.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=10 * tol)
tape.zero()
tape.backward(loss=dot3)
sgrads = tape.gradients[s3].numpy()[0]
expected_grads = 2.0 * v3.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v3].numpy()[0]
expected_grads = 2.0 * s3.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=10 * tol)
tape.zero()
tape.backward(loss=dot4)
sgrads = tape.gradients[s4].numpy()[0]
expected_grads = 2.0 * v4.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v4].numpy()[0]
expected_grads = 2.0 * s4.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=10 * tol)
tape.zero()
tape.backward(loss=dot5)
sgrads = tape.gradients[s5].numpy()[0]
expected_grads = 2.0 * v5.numpy()[0]
assert_np_equal(sgrads, expected_grads, tol=10 * tol)
vgrads = tape.gradients[v5].numpy()[0]
expected_grads = 2.0 * s5.numpy()[0]
assert_np_equal(vgrads, expected_grads, tol=10 * tol)
tape.zero()
def test_trace(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
def check_mat_trace(
v2: wp.array(dtype=mat22),
v3: wp.array(dtype=mat33),
v4: wp.array(dtype=mat44),
v5: wp.array(dtype=mat55),
tr2: wp.array(dtype=wptype),
tr3: wp.array(dtype=wptype),
tr4: wp.array(dtype=wptype),
tr5: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
tr2[0] = wptype(2) * wp.trace(v2[0])
tr3[0] = wptype(2) * wp.trace(v3[0])
tr4[0] = wptype(2) * wp.trace(v4[0])
tr5[0] = wptype(2) * wp.trace(v5[0])
kernel = getkernel(check_mat_trace, suffix=dtype.__name__)
if register_kernels:
return
v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
tr2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tr3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tr4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tr5 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[
v2,
v3,
v4,
v5,
],
outputs=[
tr2,
tr3,
tr4,
tr5,
],
device=device,
)
assert_np_equal(tr2.numpy()[0], 2 * np.trace(v2.numpy()[0]), tol=10 * tol)
assert_np_equal(tr3.numpy()[0], 2 * np.trace(v3.numpy()[0]), tol=10 * tol)
assert_np_equal(tr4.numpy()[0], 2 * np.trace(v4.numpy()[0]), tol=200 * tol)
assert_np_equal(tr4.numpy()[0], 2 * np.trace(v4.numpy()[0]), tol=200 * tol)
if dtype in np_float_types:
tape.backward(loss=tr2)
vgrads = tape.gradients[v2].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(2), tol=10 * tol)
tape.zero()
tape.backward(loss=tr3)
vgrads = tape.gradients[v3].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(3), tol=10 * tol)
tape.zero()
tape.backward(loss=tr4)
vgrads = tape.gradients[v4].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(4), tol=10 * tol)
tape.zero()
tape.backward(loss=tr5)
vgrads = tape.gradients[v5].numpy()[0]
assert_np_equal(vgrads, 2.0 * np.eye(5), tol=10 * tol)
tape.zero()
def test_diag(test, device, dtype, register_kernels=False):
rng = np.random.default_rng(123)
tol = {
np.float16: 1.0e-3,
np.float32: 1.0e-6,
np.float64: 1.0e-8,
}.get(dtype, 0)
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
vec5 = wp.types.vector(length=5, dtype=wptype)
output_select_kernel = get_select_kernel(wptype)
def check_mat_diag(
s5: wp.array(dtype=vec5),
outcomponents: wp.array(dtype=wptype),
):
# multiply outputs by 2 so we've got something to backpropagate:
m55result = wptype(2) * wp.diag(s5[0])
idx = 0
for i in range(5):
for j in range(5):
outcomponents[idx] = m55result[i, j]
idx = idx + 1
kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
if register_kernels:
return
s5 = wp.array(randvals(rng, [1, 5], dtype), dtype=vec5, requires_grad=True, device=device)
outcomponents = wp.zeros(5 * 5, dtype=wptype, requires_grad=True, device=device)
out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
wp.launch(kernel, dim=1, inputs=[s5], outputs=[outcomponents], device=device)
assert_np_equal(outcomponents.reshape((5, 5)).numpy(), 2 * np.diag(s5.numpy()[0]), tol=tol)
if dtype in np_float_types:
idx = 0
for i in range(5):
for j in range(5):
tape = wp.Tape()
with tape:
wp.launch(kernel, dim=1, inputs=[s5], outputs=[outcomponents], device=device)
wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
tape.backward(loss=out)
expectedresult = np.zeros(5, dtype=dtype)
if i == j:
expectedresult[i] = 2
assert_np_equal(tape.gradients[s5].numpy()[0], expectedresult, tol=10 * tol)
tape.zero()
idx = idx + 1
def test_equivalent_types(test, device, dtype, register_kernels=False):
wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
# matrix types
mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
# matrix types equivalent to the above
mat22_equiv = wp.types.matrix(shape=(2, 2), dtype=wptype)
mat33_equiv = wp.types.matrix(shape=(3, 3), dtype=wptype)
mat44_equiv = wp.types.matrix(shape=(4, 4), dtype=wptype)
mat55_equiv = wp.types.matrix(shape=(5, 5), dtype=wptype)
# declare kernel with original types
def check_equivalence(
m2: mat22,
m3: mat33,
m4: mat44,
m5: mat55,
):
wp.expect_eq(m2, mat22(wptype(42)))
wp.expect_eq(m3, mat33(wptype(43)))
wp.expect_eq(m4, mat44(wptype(44)))
wp.expect_eq(m5, mat55(wptype(45)))
wp.expect_eq(m2, mat22_equiv(wptype(42)))
wp.expect_eq(m3, mat33_equiv(wptype(43)))
wp.expect_eq(m4, mat44_equiv(wptype(44)))
wp.expect_eq(m5, mat55_equiv(wptype(45)))
kernel = getkernel(check_equivalence, suffix=dtype.__name__)
if register_kernels:
return
# call kernel with equivalent types
m2 = mat22_equiv(42)
m3 = mat33_equiv(43)
m4 = mat44_equiv(44)
m5 = mat55_equiv(45)
wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], device=device)
def test_conversions(test, device, dtype, register_kernels=False):
def check_matrices_equal(
m0: wp.mat22,
m1: wp.mat22,
m2: wp.mat22,
m3: wp.mat22,
m4: wp.mat22,
m5: wp.mat22,
m6: wp.mat22,
):
wp.expect_eq(m1, m0)
wp.expect_eq(m2, m0)
wp.expect_eq(m3, m0)
wp.expect_eq(m4, m0)
wp.expect_eq(m5, m0)
wp.expect_eq(m6, m0)
kernel = getkernel(check_matrices_equal, suffix=dtype.__name__)
if register_kernels:
return
m0 = wp.mat22(1, 2, 3, 4)
# test explicit conversions - constructing matrices from different containers
m1 = wp.mat22(((1, 2), (3, 4))) # nested tuples
m2 = wp.mat22([[1, 2], [3, 4]]) # nested lists
m3 = wp.mat22(np.array([[1, 2], [3, 4]], dtype=dtype)) # 2d array
m4 = wp.mat22((1, 2, 3, 4)) # flat tuple
m5 = wp.mat22([1, 2, 3, 4]) # flat list
m6 = wp.mat22(np.array([1, 2, 3, 4], dtype=dtype)) # 1d array
wp.launch(kernel, dim=1, inputs=[m0, m1, m2, m3, m4, m5, m6], device=device)
# test implicit conversions - passing different containers as matrices to wp.launch()
m1 = ((1, 2), (3, 4)) # nested tuples
m2 = [[1, 2], [3, 4]] # nested lists
m3 = np.array([[1, 2], [3, 4]], dtype=dtype) # 2d array
m4 = (1, 2, 3, 4) # flat tuple
m5 = [1, 2, 3, 4] # flat list
m6 = np.array([1, 2, 3, 4], dtype=dtype) # 1d array
wp.launch(kernel, dim=1, inputs=[m0, m1, m2, m3, m4, m5, m6], device=device)
devices = get_test_devices()
class TestMatScalarOps(unittest.TestCase):
pass
for dtype in np_scalar_types:
add_function_test(TestMatScalarOps, f"test_arrays_{dtype.__name__}", test_arrays, devices=devices, dtype=dtype)
add_function_test(TestMatScalarOps, f"test_components_{dtype.__name__}", test_components, devices=None, dtype=dtype)
add_function_test_register_kernel(
TestMatScalarOps, f"test_constructors_{dtype.__name__}", test_constructors, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps,
f"test_anon_type_instance_{dtype.__name__}",
test_anon_type_instance,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_identity_{dtype.__name__}", test_identity, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_indexing_{dtype.__name__}", test_indexing, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_equality_{dtype.__name__}", test_equality, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps,
f"test_scalar_multiplication_{dtype.__name__}",
test_scalar_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMatScalarOps,
f"test_matvec_multiplication_{dtype.__name__}",
test_matvec_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMatScalarOps,
f"test_vecmat_multiplication_{dtype.__name__}",
test_vecmat_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMatScalarOps,
f"test_matmat_multiplication_{dtype.__name__}",
test_matmat_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMatScalarOps,
f"test_cw_multiplication_{dtype.__name__}",
test_cw_multiplication,
devices=devices,
dtype=dtype,
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_cw_division_{dtype.__name__}", test_cw_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_outer_product_{dtype.__name__}", test_outer_product, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_transpose_{dtype.__name__}", test_transpose, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_scalar_division_{dtype.__name__}", test_scalar_division, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_addition_{dtype.__name__}", test_addition, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_ddot_{dtype.__name__}", test_ddot, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_trace_{dtype.__name__}", test_trace, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_diag_{dtype.__name__}", test_diag, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_get_diag_{dtype.__name__}", test_diag, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_equivalent_types_{dtype.__name__}", test_equivalent_types, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_conversions_{dtype.__name__}", test_conversions, devices=devices, dtype=dtype
)
add_function_test_register_kernel(
TestMatScalarOps, f"test_constants_{dtype.__name__}", test_constants, devices=None, dtype=dtype
)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2, failfast=True)
| 110,256 | Python | 36.941156 | 120 | 0.522548 |
NVIDIA/warp/warp/tests/test_mlp.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.func
def mlp_activation(z: float):
return wp.tanh(z)
@wp.kernel
def mlp_kernel(
weights: wp.array2d(dtype=float),
bias: wp.array(dtype=float),
x: wp.array2d(dtype=float),
y: wp.array2d(dtype=float),
):
wp.mlp(weights, bias, mlp_activation, wp.tid(), x, y)
@wp.kernel
def loss_kernel(x: wp.array2d(dtype=float), loss: wp.array(dtype=float)):
i, j = wp.tid()
wp.atomic_add(loss, 0, x[i, j] * x[i, j])
def test_mlp(test, device):
rng = np.random.default_rng(123)
m = 10
n = 200
batches = 20000
weights = wp.array(rng.random(size=(m, n)) * 0.5 - 0.5, dtype=float, device=device)
bias = wp.array(rng.random(size=m) * 0.5 - 0.5, dtype=float, device=device)
x = wp.array(rng.random(size=(n, batches)), dtype=float, device=device)
y = wp.zeros(shape=(m, batches), device=device)
with wp.ScopedTimer("warp", active=False):
wp.launch(mlp_kernel, dim=batches, inputs=[weights, bias, x, y], device=device)
wp.synchronize()
# A*x + b
with wp.ScopedTimer("numpy", active=False):
expect = np.tanh(weights.numpy().reshape(m, n) @ x.numpy().reshape(-1, batches) + bias.numpy().reshape(m, 1))
result = y.numpy().reshape(-1, batches)
assert_np_equal(result, expect, tol=1.0e-6)
def create_mlp(m, n):
import torch
torch.manual_seed(0)
class FeedForward(torch.nn.Module):
def __init__(self, input_size, hidden_size):
super(FeedForward, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)
self.act = torch.nn.Tanh()
def forward(self, x):
out = self.fc1(x)
out = self.act(out)
return out
return FeedForward(m, n)
def create_golden():
import torch
rng = np.random.default_rng(123)
input_size = 32
hidden_size = 16
batch_size = 64
network = create_mlp(input_size, hidden_size)
x = torch.Tensor(rng.random(size=(batch_size, input_size)))
x.requires_grad = True
y = network.forward(x)
y.retain_grad()
loss = torch.inner(y.flatten(), y.flatten())
loss.backward(retain_graph=True)
results = {}
results["weights"] = network.fc1.weight.cpu().detach().numpy()
results["weights_grad"] = network.fc1.weight.grad.cpu().detach().numpy()
results["bias"] = network.fc1.bias.cpu().detach().numpy()
results["bias_grad"] = network.fc1.bias.grad.cpu().detach().numpy()
results["x"] = x.cpu().detach().numpy()
results["x_grad"] = x.grad.cpu().detach().numpy()
results["y"] = y.cpu().detach().numpy()
results["y_grad"] = y.grad.cpu().detach().numpy()
results["loss"] = loss.cpu().detach().numpy()
np.save(os.path.join(os.path.dirname(__file__), "assets/mlp_golden.npy"), results, allow_pickle=True)
def load_golden():
return np.load(os.path.join(os.path.dirname(__file__), "assets/mlp_golden.npy"), allow_pickle=True).item()
def test_mlp_grad(test, device):
# uncomment to re-build golden files
# create_golden()
results = load_golden()
torch_weights = results["weights"]
torch_weights_grad = results["weights_grad"]
torch_bias = results["bias"]
torch_bias_grad = results["bias_grad"]
torch_x = results["x"].T
torch_x_grad = results["x_grad"].T
torch_y = results["y"].T
torch_y_grad = results["y_grad"].T
torch_loss = results["loss"].T
weights = wp.array(torch_weights, dtype=float, device=device, requires_grad=True)
bias = wp.array(torch_bias, dtype=float, device=device, requires_grad=True)
x = wp.array(torch_x, dtype=float, device=device, requires_grad=True)
y = wp.array(torch_y, dtype=float, device=device, requires_grad=True)
y.zero_()
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
m = torch_weights.shape[0]
n = torch_weights.shape[1]
b = torch_x.shape[1]
tape = wp.Tape()
with tape:
wp.launch(mlp_kernel, dim=b, inputs=[weights, bias, x, y], device=device)
wp.launch(loss_kernel, dim=y.shape, inputs=[y, loss], device=device)
tape.backward(loss=loss)
# check forward result
assert_np_equal(y.numpy().reshape(-1, b), torch_y, tol=1.0e-1)
assert_np_equal(loss.numpy(), torch_loss, tol=1.0e-1)
# check backward result
assert_np_equal(tape.gradients[weights].numpy().reshape(m, n), torch_weights_grad, tol=1.0e-1)
assert_np_equal(tape.gradients[bias].numpy(), torch_bias_grad, tol=1.0e-1)
assert_np_equal(tape.gradients[x].numpy().reshape(n, b), torch_x_grad, tol=1.0e-1)
assert_np_equal(tape.gradients[y].numpy().reshape(m, b), torch_y_grad, tol=1.0e-1)
def profile_mlp_torch():
import torch
rng = np.random.default_rng(123)
m = 128
n = 64
steps = 20
for i in range(steps):
b = 2**i
network = create_mlp(m, n)
x = torch.Tensor(rng.random(size=(b, m)))
with wp.ScopedTimer("torch_forward" + str(b)):
y = network.forward(x)
torch.cuda.synchronize()
for i in range(steps):
b = 2**i
network = create_mlp(m, n)
x = torch.Tensor(rng.random(size=(b, m)))
y = network.forward(x)
loss = torch.norm(y)
# run once to alloc all gradients
loss.backward(retain_graph=True)
with wp.ScopedTimer("torch-backward" + str(b)):
loss.backward()
torch.cuda.synchronize()
def profile_mlp_warp(device):
rng = np.random.default_rng(123)
m = 128
n = 64
steps = 20
for i in range(steps):
b = 2**i
weights = wp.array(rng.random(size=(m, n)) * 0.5 - 0.5, dtype=float, device=device)
bias = wp.array(rng.random(size=m) * 0.5 - 0.5, dtype=float, device=device)
x = wp.array(rng.random(size=(n, b)), dtype=float, device=device)
y = wp.zeros(shape=(m, b), device=device)
with wp.ScopedTimer("warp-forward" + str(b)):
wp.launch(mlp_kernel, dim=b, inputs=[weights, bias, x, y], device=device)
wp.synchronize()
for i in range(steps):
b = 2**i
weights = wp.array(rng.random(size=(m, n)) * 0.5 - 0.5, dtype=float, device=device, requires_grad=True)
bias = wp.array(rng.random(size=m) * 0.5 - 0.5, dtype=float, device=device, requires_grad=True)
x = wp.array(rng.random(size=(n, b)), dtype=float, device=device, requires_grad=True)
y = wp.zeros(shape=(m, b), device=device, requires_grad=True)
loss = wp.zeros(1, dtype=float, device=device)
tape = wp.Tape()
with tape:
wp.launch(mlp_kernel, dim=b, inputs=[weights, bias, x, y], device=device)
wp.launch(loss_kernel, dim=y.size, inputs=[y.flatten(), loss], device=device)
# run backward once to ensure all adjoints are allocated
tape.backward(loss)
wp.synchronize()
with wp.ScopedTimer("warp-backward" + str(b)):
tape.backward(loss)
wp.synchronize()
# profile_mlp_warp("cuda")
# profile_mlp_torch()
devices = get_test_devices()
class TestMLP(unittest.TestCase):
pass
add_function_test(TestMLP, "test_mlp", test_mlp, devices=devices)
add_function_test(TestMLP, "test_mlp_grad", test_mlp_grad, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2, failfast=False)
| 8,000 | Python | 28.094545 | 117 | 0.622 |
NVIDIA/warp/warp/tests/test_array.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@wp.kernel
def kernel_1d(a: wp.array(dtype=int, ndim=1)):
i = wp.tid()
wp.expect_eq(a[i], wp.tid())
a[i] = a[i] * 2
wp.atomic_add(a, i, 1)
wp.expect_eq(a[i], wp.tid() * 2 + 1)
def test_1d(test, device):
dim_x = 4
a = np.arange(0, dim_x, dtype=np.int32)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_1d, dim=arr.size, inputs=[arr], device=device)
@wp.kernel
def kernel_2d(a: wp.array(dtype=int, ndim=2), m: int, n: int):
i = wp.tid() // n
j = wp.tid() % n
wp.expect_eq(a[i, j], wp.tid())
wp.expect_eq(a[i][j], wp.tid())
a[i, j] = a[i, j] * 2
wp.atomic_add(a, i, j, 1)
wp.expect_eq(a[i, j], wp.tid() * 2 + 1)
def test_2d(test, device):
dim_x = 4
dim_y = 2
a = np.arange(0, dim_x * dim_y, dtype=np.int32)
a = a.reshape(dim_x, dim_y)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_2d, dim=arr.size, inputs=[arr, dim_x, dim_y], device=device)
@wp.kernel
def kernel_3d(a: wp.array(dtype=int, ndim=3), m: int, n: int, o: int):
i = wp.tid() // (n * o)
j = wp.tid() % (n * o) // o
k = wp.tid() % o
wp.expect_eq(a[i, j, k], wp.tid())
wp.expect_eq(a[i][j][k], wp.tid())
a[i, j, k] = a[i, j, k] * 2
a[i][j][k] = a[i][j][k] * 2
wp.atomic_add(a, i, j, k, 1)
wp.expect_eq(a[i, j, k], wp.tid() * 4 + 1)
def test_3d(test, device):
dim_x = 8
dim_y = 4
dim_z = 2
a = np.arange(0, dim_x * dim_y * dim_z, dtype=np.int32)
a = a.reshape(dim_x, dim_y, dim_z)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_3d, dim=arr.size, inputs=[arr, dim_x, dim_y, dim_z], device=device)
@wp.kernel
def kernel_4d(a: wp.array(dtype=int, ndim=4), m: int, n: int, o: int, p: int):
i = wp.tid() // (n * o * p)
j = wp.tid() % (n * o * p) // (o * p)
k = wp.tid() % (o * p) / p
l = wp.tid() % p
wp.expect_eq(a[i, j, k, l], wp.tid())
wp.expect_eq(a[i][j][k][l], wp.tid())
def test_4d(test, device):
dim_x = 16
dim_y = 8
dim_z = 4
dim_w = 2
a = np.arange(0, dim_x * dim_y * dim_z * dim_w, dtype=np.int32)
a = a.reshape(dim_x, dim_y, dim_z, dim_w)
arr = wp.array(a, device=device)
test.assertEqual(arr.shape, a.shape)
test.assertEqual(arr.size, a.size)
test.assertEqual(arr.ndim, a.ndim)
with CheckOutput(test):
wp.launch(kernel_4d, dim=arr.size, inputs=[arr, dim_x, dim_y, dim_z, dim_w], device=device)
@wp.kernel
def kernel_4d_transposed(a: wp.array(dtype=int, ndim=4), m: int, n: int, o: int, p: int):
i = wp.tid() // (n * o * p)
j = wp.tid() % (n * o * p) // (o * p)
k = wp.tid() % (o * p) / p
l = wp.tid() % p
wp.expect_eq(a[l, k, j, i], wp.tid())
wp.expect_eq(a[l][k][j][i], wp.tid())
def test_4d_transposed(test, device):
dim_x = 16
dim_y = 8
dim_z = 4
dim_w = 2
a = np.arange(0, dim_x * dim_y * dim_z * dim_w, dtype=np.int32)
a = a.reshape(dim_x, dim_y, dim_z, dim_w)
arr = wp.array(a, device=device)
# Transpose the array manually, as using the wp.array() constructor with arr.T would make it contiguous first
a_T = a.T
arr_T = wp.array(
dtype=arr.dtype,
shape=a_T.shape,
strides=a_T.__array_interface__["strides"],
capacity=arr.capacity,
ptr=arr.ptr,
requires_grad=arr.requires_grad,
device=device,
)
test.assertFalse(arr_T.is_contiguous)
test.assertEqual(arr_T.shape, a_T.shape)
test.assertEqual(arr_T.strides, a_T.__array_interface__["strides"])
test.assertEqual(arr_T.size, a_T.size)
test.assertEqual(arr_T.ndim, a_T.ndim)
with CheckOutput(test):
wp.launch(kernel_4d_transposed, dim=arr_T.size, inputs=[arr_T, dim_x, dim_y, dim_z, dim_w], device=device)
@wp.kernel
def lower_bound_kernel(values: wp.array(dtype=float), arr: wp.array(dtype=float), indices: wp.array(dtype=int)):
tid = wp.tid()
indices[tid] = wp.lower_bound(arr, values[tid])
def test_lower_bound(test, device):
arr = wp.array(np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0], dtype=float), dtype=float, device=device)
values = wp.array(np.array([-0.1, 0.0, 2.5, 4.0, 5.0, 5.5], dtype=float), dtype=float, device=device)
indices = wp.zeros(6, dtype=int, device=device)
wp.launch(kernel=lower_bound_kernel, dim=6, inputs=[values, arr, indices], device=device)
test.assertTrue((np.array([0, 0, 3, 4, 5, 5]) == indices.numpy()).all())
@wp.kernel
def f1(arr: wp.array(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
@wp.kernel
def f2(arr: wp.array2d(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
wp.expect_eq(arr.shape[1], 20)
slice = arr[0]
wp.expect_eq(slice.shape[0], 20)
@wp.kernel
def f3(arr: wp.array3d(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
wp.expect_eq(arr.shape[1], 20)
wp.expect_eq(arr.shape[2], 30)
slice = arr[0, 0]
wp.expect_eq(slice.shape[0], 30)
@wp.kernel
def f4(arr: wp.array4d(dtype=float)):
wp.expect_eq(arr.shape[0], 10)
wp.expect_eq(arr.shape[1], 20)
wp.expect_eq(arr.shape[2], 30)
wp.expect_eq(arr.shape[3], 40)
slice = arr[0, 0, 0]
wp.expect_eq(slice.shape[0], 40)
def test_shape(test, device):
with CheckOutput(test):
a1 = wp.zeros(dtype=float, shape=10, device=device)
wp.launch(f1, dim=1, inputs=[a1], device=device)
a2 = wp.zeros(dtype=float, shape=(10, 20), device=device)
wp.launch(f2, dim=1, inputs=[a2], device=device)
a3 = wp.zeros(dtype=float, shape=(10, 20, 30), device=device)
wp.launch(f3, dim=1, inputs=[a3], device=device)
a4 = wp.zeros(dtype=float, shape=(10, 20, 30, 40), device=device)
wp.launch(f4, dim=1, inputs=[a4], device=device)
def test_negative_shape(test, device):
with test.assertRaisesRegex(ValueError, "Array shapes must be non-negative"):
_ = wp.zeros(shape=-1, dtype=int, device=device)
with test.assertRaisesRegex(ValueError, "Array shapes must be non-negative"):
_ = wp.zeros(shape=-(2**32), dtype=int, device=device)
with test.assertRaisesRegex(ValueError, "Array shapes must be non-negative"):
_ = wp.zeros(shape=(10, -1), dtype=int, device=device)
@wp.kernel
def sum_array(arr: wp.array(dtype=float), loss: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(loss, 0, arr[tid])
def test_flatten(test, device):
np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=float)
arr = wp.array(np_arr, dtype=float, shape=np_arr.shape, device=device, requires_grad=True)
arr_flat = arr.flatten()
arr_comp = wp.array(np_arr.flatten(), dtype=float, device=device)
assert_array_equal(arr_flat, arr_comp)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=sum_array, dim=len(arr_flat), inputs=[arr_flat, loss], device=device)
tape.backward(loss=loss)
grad = tape.gradients[arr_flat]
ones = wp.array(
np.ones(
(8,),
dtype=float,
),
dtype=float,
device=device,
)
assert_array_equal(grad, ones)
test.assertEqual(loss.numpy()[0], 36)
def test_reshape(test, device):
np_arr = np.arange(6, dtype=float)
arr = wp.array(np_arr, dtype=float, device=device, requires_grad=True)
arr_reshaped = arr.reshape((3, 2))
arr_comp = wp.array(np_arr.reshape((3, 2)), dtype=float, device=device)
assert_array_equal(arr_reshaped, arr_comp)
arr_reshaped = arr_reshaped.reshape(6)
assert_array_equal(arr_reshaped, arr)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=sum_array, dim=len(arr_reshaped), inputs=[arr_reshaped, loss], device=device)
tape.backward(loss=loss)
grad = tape.gradients[arr_reshaped]
ones = wp.array(
np.ones(
(6,),
dtype=float,
),
dtype=float,
device=device,
)
assert_array_equal(grad, ones)
test.assertEqual(loss.numpy()[0], 15)
np_arr = np.arange(6, dtype=float)
arr = wp.array(np_arr, dtype=float, device=device)
arr_infer = arr.reshape((-1, 3))
arr_comp = wp.array(np_arr.reshape((-1, 3)), dtype=float, device=device)
assert_array_equal(arr_infer, arr_comp)
@wp.kernel
def compare_stepped_window_a(x: wp.array2d(dtype=float)):
wp.expect_eq(x[0, 0], 1.0)
wp.expect_eq(x[0, 1], 2.0)
wp.expect_eq(x[1, 0], 9.0)
wp.expect_eq(x[1, 1], 10.0)
@wp.kernel
def compare_stepped_window_b(x: wp.array2d(dtype=float)):
wp.expect_eq(x[0, 0], 3.0)
wp.expect_eq(x[0, 1], 4.0)
wp.expect_eq(x[1, 0], 7.0)
wp.expect_eq(x[1, 1], 8.0)
wp.expect_eq(x[2, 0], 11.0)
wp.expect_eq(x[2, 1], 12.0)
def test_slicing(test, device):
np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=float)
arr = wp.array(np_arr, dtype=float, shape=np_arr.shape, device=device, requires_grad=True)
slice_a = arr[1, :, :] # test indexing
slice_b = arr[1:2, :, :] # test slicing
slice_c = arr[-1, :, :] # test negative indexing
slice_d = arr[-2:-1, :, :] # test negative slicing
slice_e = arr[-1:3, :, :] # test mixed slicing
slice_e2 = slice_e[0, 0, :] # test 2x slicing
slice_f = arr[0:3:2, 0, :] # test step
assert_array_equal(slice_a, wp.array(np_arr[1, :, :], dtype=float, device=device))
assert_array_equal(slice_b, wp.array(np_arr[1:2, :, :], dtype=float, device=device))
assert_array_equal(slice_c, wp.array(np_arr[-1, :, :], dtype=float, device=device))
assert_array_equal(slice_d, wp.array(np_arr[-2:-1, :, :], dtype=float, device=device))
assert_array_equal(slice_e, wp.array(np_arr[-1:3, :, :], dtype=float, device=device))
assert_array_equal(slice_e2, wp.array(np_arr[2, 0, :], dtype=float, device=device))
# wp does not support copying from/to non-contiguous arrays
# stepped windows must read on the device the original array was created on
wp.launch(kernel=compare_stepped_window_a, dim=1, inputs=[slice_f], device=device)
slice_flat = slice_b.flatten()
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
tape = wp.Tape()
with tape:
wp.launch(kernel=sum_array, dim=len(slice_flat), inputs=[slice_flat, loss], device=device)
tape.backward(loss=loss)
grad = tape.gradients[slice_flat]
ones = wp.array(
np.ones(
(4,),
dtype=float,
),
dtype=float,
device=device,
)
assert_array_equal(grad, ones)
test.assertEqual(loss.numpy()[0], 26)
index_a = arr[1]
index_b = arr[2, 1]
index_c = arr[1, :]
index_d = arr[:, 1]
assert_array_equal(index_a, wp.array(np_arr[1], dtype=float, device=device))
assert_array_equal(index_b, wp.array(np_arr[2, 1], dtype=float, device=device))
assert_array_equal(index_c, wp.array(np_arr[1, :], dtype=float, device=device))
wp.launch(kernel=compare_stepped_window_b, dim=1, inputs=[index_d], device=device)
np_arr = np.zeros(10, dtype=int)
wp_arr = wp.array(np_arr, dtype=int, device=device)
assert_array_equal(wp_arr[:5], wp.array(np_arr[:5], dtype=int, device=device))
assert_array_equal(wp_arr[1:5], wp.array(np_arr[1:5], dtype=int, device=device))
assert_array_equal(wp_arr[-9:-5:1], wp.array(np_arr[-9:-5:1], dtype=int, device=device))
assert_array_equal(wp_arr[:5,], wp.array(np_arr[:5], dtype=int, device=device)) # noqa: E231
def test_view(test, device):
np_arr_a = np.arange(1, 10, 1, dtype=np.uint32)
np_arr_b = np.arange(1, 10, 1, dtype=np.float32)
np_arr_c = np.arange(1, 10, 1, dtype=np.uint16)
np_arr_d = np.arange(1, 10, 1, dtype=np.float16)
np_arr_e = np.ones((4, 4), dtype=np.float32)
wp_arr_a = wp.array(np_arr_a, dtype=wp.uint32, device=device)
wp_arr_b = wp.array(np_arr_b, dtype=wp.float32, device=device)
wp_arr_c = wp.array(np_arr_a, dtype=wp.uint16, device=device)
wp_arr_d = wp.array(np_arr_b, dtype=wp.float16, device=device)
wp_arr_e = wp.array(np_arr_e, dtype=wp.vec4, device=device)
wp_arr_f = wp.array(np_arr_e, dtype=wp.quat, device=device)
assert_np_equal(wp_arr_a.view(dtype=wp.float32).numpy(), np_arr_a.view(dtype=np.float32))
assert_np_equal(wp_arr_b.view(dtype=wp.uint32).numpy(), np_arr_b.view(dtype=np.uint32))
assert_np_equal(wp_arr_c.view(dtype=wp.float16).numpy(), np_arr_c.view(dtype=np.float16))
assert_np_equal(wp_arr_d.view(dtype=wp.uint16).numpy(), np_arr_d.view(dtype=np.uint16))
assert_array_equal(wp_arr_e.view(dtype=wp.quat), wp_arr_f)
def test_clone_adjoint(test, device):
state_in = wp.from_numpy(
np.array([1.0, 2.0, 3.0]).astype(np.float32), dtype=wp.float32, requires_grad=True, device=device
)
tape = wp.Tape()
with tape:
state_out = wp.clone(state_in)
grads = {state_out: wp.from_numpy(np.array([1.0, 1.0, 1.0]).astype(np.float32), dtype=wp.float32, device=device)}
tape.backward(grads=grads)
assert_np_equal(state_in.grad.numpy(), np.array([1.0, 1.0, 1.0]).astype(np.float32))
def test_assign_adjoint(test, device):
state_in = wp.from_numpy(
np.array([1.0, 2.0, 3.0]).astype(np.float32), dtype=wp.float32, requires_grad=True, device=device
)
state_out = wp.zeros(state_in.shape, dtype=wp.float32, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
state_out.assign(state_in)
grads = {state_out: wp.from_numpy(np.array([1.0, 1.0, 1.0]).astype(np.float32), dtype=wp.float32, device=device)}
tape.backward(grads=grads)
assert_np_equal(state_in.grad.numpy(), np.array([1.0, 1.0, 1.0]).astype(np.float32))
@wp.kernel
def compare_2darrays(x: wp.array2d(dtype=float), y: wp.array2d(dtype=float), z: wp.array2d(dtype=int)):
i, j = wp.tid()
if x[i, j] == y[i, j]:
z[i, j] = 1
@wp.kernel
def compare_3darrays(x: wp.array3d(dtype=float), y: wp.array3d(dtype=float), z: wp.array3d(dtype=int)):
i, j, k = wp.tid()
if x[i, j, k] == y[i, j, k]:
z[i, j, k] = 1
def test_transpose(test, device):
# test default transpose in non-square 2d case
# wp does not support copying from/to non-contiguous arrays so check in kernel
np_arr = np.array([[1, 2], [3, 4], [5, 6]], dtype=float)
arr = wp.array(np_arr, dtype=float, device=device)
arr_transpose = arr.transpose()
arr_compare = wp.array(np_arr.transpose(), dtype=float, device=device)
check = wp.zeros(shape=(2, 3), dtype=int, device=device)
wp.launch(compare_2darrays, dim=(2, 3), inputs=[arr_transpose, arr_compare, check], device=device)
assert_np_equal(check.numpy(), np.ones((2, 3), dtype=int))
# test transpose in square 3d case
# wp does not support copying from/to non-contiguous arrays so check in kernel
np_arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]], dtype=float)
arr = wp.array3d(np_arr, dtype=float, shape=np_arr.shape, device=device, requires_grad=True)
arr_transpose = arr.transpose((0, 2, 1))
arr_compare = wp.array3d(np_arr.transpose((0, 2, 1)), dtype=float, device=device)
check = wp.zeros(shape=(3, 2, 2), dtype=int, device=device)
wp.launch(compare_3darrays, dim=(3, 2, 2), inputs=[arr_transpose, arr_compare, check], device=device)
assert_np_equal(check.numpy(), np.ones((3, 2, 2), dtype=int))
# test transpose in square 3d case without axes supplied
arr_transpose = arr.transpose()
arr_compare = wp.array3d(np_arr.transpose(), dtype=float, device=device)
check = wp.zeros(shape=(2, 2, 3), dtype=int, device=device)
wp.launch(compare_3darrays, dim=(2, 2, 3), inputs=[arr_transpose, arr_compare, check], device=device)
assert_np_equal(check.numpy(), np.ones((2, 2, 3), dtype=int))
# test transpose in 1d case (should be noop)
np_arr = np.array([1, 2, 3], dtype=float)
arr = wp.array(np_arr, dtype=float, device=device)
assert_np_equal(arr.transpose().numpy(), np_arr.transpose())
def test_fill_scalar(test, device):
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a1 = wp.zeros(dim_x, dtype=wptype, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=wptype, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=wptype, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
# fill with int value
fill_value = 42
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full(a1.shape, fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full(a2.shape, fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full(a3.shape, fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full(a4.shape, fill_value, dtype=nptype))
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
if wptype in wp.types.float_types:
# fill with float value
fill_value = 13.37
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full(a1.shape, fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full(a2.shape, fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full(a3.shape, fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full(a4.shape, fill_value, dtype=nptype))
# fill with Warp scalar value
fill_value = wptype(17)
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full(a1.shape, fill_value.value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full(a2.shape, fill_value.value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full(a3.shape, fill_value.value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full(a4.shape, fill_value.value, dtype=nptype))
def test_fill_vector(test, device):
# test filling a vector array with scalar or vector values (vec_type, list, or numpy array)
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# vector types
vector_types = [
wp.types.vector(2, wptype),
wp.types.vector(3, wptype),
wp.types.vector(4, wptype),
wp.types.vector(5, wptype),
]
for vec_type in vector_types:
vec_len = vec_type._length_
a1 = wp.zeros(dim_x, dtype=vec_type, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=vec_type, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=vec_type, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=vec_type, device=device)
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, vec_len), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, vec_len), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, vec_len), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, vec_len), dtype=nptype))
# fill with int scalar
fill_value = 42
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full((*a1.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full((*a2.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full((*a3.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full((*a4.shape, vec_len), fill_value, dtype=nptype))
# test zeroing
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, vec_len), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, vec_len), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, vec_len), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, vec_len), dtype=nptype))
# vector values can be passed as a list, numpy array, or Warp vector instance
fill_list = [17, 42, 99, 101, 127][:vec_len]
fill_arr = np.array(fill_list, dtype=nptype)
fill_vec = vec_type(fill_list)
expected1 = np.tile(fill_arr, a1.size).reshape((*a1.shape, vec_len))
expected2 = np.tile(fill_arr, a2.size).reshape((*a2.shape, vec_len))
expected3 = np.tile(fill_arr, a3.size).reshape((*a3.shape, vec_len))
expected4 = np.tile(fill_arr, a4.size).reshape((*a4.shape, vec_len))
# fill with list of vector length
a1.fill_(fill_list)
a2.fill_(fill_list)
a3.fill_(fill_list)
a4.fill_(fill_list)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with numpy array of vector length
a1.fill_(fill_arr)
a2.fill_(fill_arr)
a3.fill_(fill_arr)
a4.fill_(fill_arr)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with vec instance
a1.fill_(fill_vec)
a2.fill_(fill_vec)
a3.fill_(fill_vec)
a4.fill_(fill_vec)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
if wptype in wp.types.float_types:
# fill with float scalar
fill_value = 13.37
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full((*a1.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full((*a2.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full((*a3.shape, vec_len), fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full((*a4.shape, vec_len), fill_value, dtype=nptype))
# fill with float list of vector length
fill_list = [-2.5, -1.25, 1.25, 2.5, 5.0][:vec_len]
a1.fill_(fill_list)
a2.fill_(fill_list)
a3.fill_(fill_list)
a4.fill_(fill_list)
expected1 = np.tile(np.array(fill_list, dtype=nptype), a1.size).reshape((*a1.shape, vec_len))
expected2 = np.tile(np.array(fill_list, dtype=nptype), a2.size).reshape((*a2.shape, vec_len))
expected3 = np.tile(np.array(fill_list, dtype=nptype), a3.size).reshape((*a3.shape, vec_len))
expected4 = np.tile(np.array(fill_list, dtype=nptype), a4.size).reshape((*a4.shape, vec_len))
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
def test_fill_matrix(test, device):
# test filling a matrix array with scalar or matrix values (mat_type, nested list, or 2d numpy array)
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# matrix types
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mat_type in matrix_types:
mat_len = mat_type._length_
mat_shape = mat_type._shape_
a1 = wp.zeros(dim_x, dtype=mat_type, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=mat_type, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=mat_type, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=mat_type, device=device)
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, *mat_shape), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, *mat_shape), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, *mat_shape), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, *mat_shape), dtype=nptype))
# fill with scalar
fill_value = 42
a1.fill_(fill_value)
a2.fill_(fill_value)
a3.fill_(fill_value)
a4.fill_(fill_value)
assert_np_equal(a1.numpy(), np.full((*a1.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(a2.numpy(), np.full((*a2.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(a3.numpy(), np.full((*a3.shape, *mat_shape), fill_value, dtype=nptype))
assert_np_equal(a4.numpy(), np.full((*a4.shape, *mat_shape), fill_value, dtype=nptype))
# test zeroing
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros((*a1.shape, *mat_shape), dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros((*a2.shape, *mat_shape), dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros((*a3.shape, *mat_shape), dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros((*a4.shape, *mat_shape), dtype=nptype))
# matrix values can be passed as a 1d numpy array, 2d numpy array, flat list, nested list, or Warp matrix instance
if wptype != wp.bool:
fill_arr1 = np.arange(mat_len, dtype=nptype)
else:
fill_arr1 = np.ones(mat_len, dtype=nptype)
fill_arr2 = fill_arr1.reshape(mat_shape)
fill_list1 = list(fill_arr1)
fill_list2 = [list(row) for row in fill_arr2]
fill_mat = mat_type(fill_arr1)
expected1 = np.tile(fill_arr1, a1.size).reshape((*a1.shape, *mat_shape))
expected2 = np.tile(fill_arr1, a2.size).reshape((*a2.shape, *mat_shape))
expected3 = np.tile(fill_arr1, a3.size).reshape((*a3.shape, *mat_shape))
expected4 = np.tile(fill_arr1, a4.size).reshape((*a4.shape, *mat_shape))
# fill with 1d numpy array
a1.fill_(fill_arr1)
a2.fill_(fill_arr1)
a3.fill_(fill_arr1)
a4.fill_(fill_arr1)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with 2d numpy array
a1.fill_(fill_arr2)
a2.fill_(fill_arr2)
a3.fill_(fill_arr2)
a4.fill_(fill_arr2)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with flat list
a1.fill_(fill_list1)
a2.fill_(fill_list1)
a3.fill_(fill_list1)
a4.fill_(fill_list1)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with nested list
a1.fill_(fill_list2)
a2.fill_(fill_list2)
a3.fill_(fill_list2)
a4.fill_(fill_list2)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# clear
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
# fill with mat instance
a1.fill_(fill_mat)
a2.fill_(fill_mat)
a3.fill_(fill_mat)
a4.fill_(fill_mat)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
@wp.struct
class FillStruct:
# scalar members (make sure to test float16)
i1: wp.int8
i2: wp.int16
i4: wp.int32
i8: wp.int64
f2: wp.float16
f4: wp.float32
f8: wp.float16
# vector members (make sure to test vectors of float16)
v2: wp.types.vector(2, wp.int64)
v3: wp.types.vector(3, wp.float32)
v4: wp.types.vector(4, wp.float16)
v5: wp.types.vector(5, wp.uint8)
# matrix members (make sure to test matrices of float16)
m2: wp.types.matrix((2, 2), wp.float64)
m3: wp.types.matrix((3, 3), wp.int32)
m4: wp.types.matrix((4, 4), wp.float16)
m5: wp.types.matrix((5, 5), wp.int8)
# arrays
a1: wp.array(dtype=float)
a2: wp.array2d(dtype=float)
a3: wp.array3d(dtype=float)
a4: wp.array4d(dtype=float)
def test_fill_struct(test, device):
dim_x = 4
nptype = FillStruct.numpy_dtype()
a1 = wp.zeros(dim_x, dtype=FillStruct, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=FillStruct, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=FillStruct, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=FillStruct, device=device)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
s = FillStruct()
# fill with default struct value (should be all zeros)
a1.fill_(s)
a2.fill_(s)
a3.fill_(s)
a4.fill_(s)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
# scalars
s.i1 = -17
s.i2 = 42
s.i4 = 99
s.i8 = 101
s.f2 = -1.25
s.f4 = 13.37
s.f8 = 0.125
# vectors
s.v2 = [21, 22]
s.v3 = [31, 32, 33]
s.v4 = [41, 42, 43, 44]
s.v5 = [51, 52, 53, 54, 55]
# matrices
s.m2 = [[61, 62]] * 2
s.m3 = [[71, 72, 73]] * 3
s.m4 = [[81, 82, 83, 84]] * 4
s.m5 = [[91, 92, 93, 94, 95]] * 5
# arrays
s.a1 = wp.zeros((2,) * 1, dtype=float, device=device)
s.a2 = wp.zeros((2,) * 2, dtype=float, device=device)
s.a3 = wp.zeros((2,) * 3, dtype=float, device=device)
s.a4 = wp.zeros((2,) * 4, dtype=float, device=device)
# fill with custom struct value
a1.fill_(s)
a2.fill_(s)
a3.fill_(s)
a4.fill_(s)
ns = s.numpy_value()
expected1 = np.empty(a1.shape, dtype=nptype)
expected2 = np.empty(a2.shape, dtype=nptype)
expected3 = np.empty(a3.shape, dtype=nptype)
expected4 = np.empty(a4.shape, dtype=nptype)
expected1.fill(ns)
expected2.fill(ns)
expected3.fill(ns)
expected4.fill(ns)
assert_np_equal(a1.numpy(), expected1)
assert_np_equal(a2.numpy(), expected2)
assert_np_equal(a3.numpy(), expected3)
assert_np_equal(a4.numpy(), expected4)
# test clearing
a1.zero_()
a2.zero_()
a3.zero_()
a4.zero_()
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
def test_fill_slices(test, device):
# test fill_ and zero_ for non-contiguous arrays
# Note: we don't need to test the whole range of dtypes (vectors, matrices, structs) here
dim_x = 8
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a1 = wp.zeros(dim_x, dtype=wptype, device=device)
a2 = wp.zeros((dim_x, dim_x), dtype=wptype, device=device)
a3 = wp.zeros((dim_x, dim_x, dim_x), dtype=wptype, device=device)
a4 = wp.zeros((dim_x, dim_x, dim_x, dim_x), dtype=wptype, device=device)
assert_np_equal(a1.numpy(), np.zeros(a1.shape, dtype=nptype))
assert_np_equal(a2.numpy(), np.zeros(a2.shape, dtype=nptype))
assert_np_equal(a3.numpy(), np.zeros(a3.shape, dtype=nptype))
assert_np_equal(a4.numpy(), np.zeros(a4.shape, dtype=nptype))
# partititon each array into even and odd slices
a1a = a1[::2]
a1b = a1[1::2]
a2a = a2[::2]
a2b = a2[1::2]
a3a = a3[::2]
a3b = a3[1::2]
a4a = a4[::2]
a4b = a4[1::2]
# fill even slices
fill_a = 17
a1a.fill_(fill_a)
a2a.fill_(fill_a)
a3a.fill_(fill_a)
a4a.fill_(fill_a)
# ensure filled slices are correct
assert_np_equal(a1a.numpy(), np.full(a1a.shape, fill_a, dtype=nptype))
assert_np_equal(a2a.numpy(), np.full(a2a.shape, fill_a, dtype=nptype))
assert_np_equal(a3a.numpy(), np.full(a3a.shape, fill_a, dtype=nptype))
assert_np_equal(a4a.numpy(), np.full(a4a.shape, fill_a, dtype=nptype))
# ensure unfilled slices are unaffected
assert_np_equal(a1b.numpy(), np.zeros(a1b.shape, dtype=nptype))
assert_np_equal(a2b.numpy(), np.zeros(a2b.shape, dtype=nptype))
assert_np_equal(a3b.numpy(), np.zeros(a3b.shape, dtype=nptype))
assert_np_equal(a4b.numpy(), np.zeros(a4b.shape, dtype=nptype))
# fill odd slices
fill_b = 42
a1b.fill_(fill_b)
a2b.fill_(fill_b)
a3b.fill_(fill_b)
a4b.fill_(fill_b)
# ensure filled slices are correct
assert_np_equal(a1b.numpy(), np.full(a1b.shape, fill_b, dtype=nptype))
assert_np_equal(a2b.numpy(), np.full(a2b.shape, fill_b, dtype=nptype))
assert_np_equal(a3b.numpy(), np.full(a3b.shape, fill_b, dtype=nptype))
assert_np_equal(a4b.numpy(), np.full(a4b.shape, fill_b, dtype=nptype))
# ensure unfilled slices are unaffected
assert_np_equal(a1a.numpy(), np.full(a1a.shape, fill_a, dtype=nptype))
assert_np_equal(a2a.numpy(), np.full(a2a.shape, fill_a, dtype=nptype))
assert_np_equal(a3a.numpy(), np.full(a3a.shape, fill_a, dtype=nptype))
assert_np_equal(a4a.numpy(), np.full(a4a.shape, fill_a, dtype=nptype))
# clear even slices
a1a.zero_()
a2a.zero_()
a3a.zero_()
a4a.zero_()
# ensure cleared slices are correct
assert_np_equal(a1a.numpy(), np.zeros(a1a.shape, dtype=nptype))
assert_np_equal(a2a.numpy(), np.zeros(a2a.shape, dtype=nptype))
assert_np_equal(a3a.numpy(), np.zeros(a3a.shape, dtype=nptype))
assert_np_equal(a4a.numpy(), np.zeros(a4a.shape, dtype=nptype))
# ensure uncleared slices are unaffected
assert_np_equal(a1b.numpy(), np.full(a1b.shape, fill_b, dtype=nptype))
assert_np_equal(a2b.numpy(), np.full(a2b.shape, fill_b, dtype=nptype))
assert_np_equal(a3b.numpy(), np.full(a3b.shape, fill_b, dtype=nptype))
assert_np_equal(a4b.numpy(), np.full(a4b.shape, fill_b, dtype=nptype))
# re-fill even slices
a1a.fill_(fill_a)
a2a.fill_(fill_a)
a3a.fill_(fill_a)
a4a.fill_(fill_a)
# clear odd slices
a1b.zero_()
a2b.zero_()
a3b.zero_()
a4b.zero_()
# ensure cleared slices are correct
assert_np_equal(a1b.numpy(), np.zeros(a1b.shape, dtype=nptype))
assert_np_equal(a2b.numpy(), np.zeros(a2b.shape, dtype=nptype))
assert_np_equal(a3b.numpy(), np.zeros(a3b.shape, dtype=nptype))
assert_np_equal(a4b.numpy(), np.zeros(a4b.shape, dtype=nptype))
# ensure uncleared slices are unaffected
assert_np_equal(a1a.numpy(), np.full(a1a.shape, fill_a, dtype=nptype))
assert_np_equal(a2a.numpy(), np.full(a2a.shape, fill_a, dtype=nptype))
assert_np_equal(a3a.numpy(), np.full(a3a.shape, fill_a, dtype=nptype))
assert_np_equal(a4a.numpy(), np.full(a4a.shape, fill_a, dtype=nptype))
def test_full_scalar(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# fill with int value and specific dtype
fill_value = 42
a = wp.full(shape, fill_value, dtype=wptype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wptype)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(shape, fill_value, dtype=nptype))
if wptype in wp.types.float_types:
# fill with float value and specific dtype
fill_value = 13.37
a = wp.full(shape, fill_value, dtype=wptype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wptype)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(shape, fill_value, dtype=nptype))
# fill with int value and automatically inferred dtype
fill_value = 42
a = wp.full(shape, fill_value, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wp.int32)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, np.int32)
assert_np_equal(na, np.full(shape, fill_value, dtype=np.int32))
# fill with float value and automatically inferred dtype
fill_value = 13.37
a = wp.full(shape, fill_value, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wp.float32)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, np.float32)
assert_np_equal(na, np.full(shape, fill_value, dtype=np.float32))
def test_full_vector(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
# full from scalar
for veclen in [2, 3, 4, 5]:
npshape = (*shape, veclen)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
vectype = wp.types.vector(veclen, wptype)
# fill with scalar int value and specific dtype
fill_value = 42
a = wp.full(shape, fill_value, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, fill_value, dtype=nptype).reshape(npshape))
if wptype in wp.types.float_types:
# fill with scalar float value and specific dtype
fill_value = 13.37
a = wp.full(shape, fill_value, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, fill_value, dtype=nptype).reshape(npshape))
# fill with vector value and specific dtype
fill_vec = vectype(42)
a = wp.full(shape, fill_vec, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, 42, dtype=nptype).reshape(npshape))
# fill with vector value and automatically inferred dtype
a = wp.full(shape, fill_vec, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * veclen, 42, dtype=nptype).reshape(npshape))
fill_lists = [
[17, 42],
[17, 42, 99],
[17, 42, 99, 101],
[17, 42, 99, 101, 127],
]
# full from list and numpy array
for fill_list in fill_lists:
veclen = len(fill_list)
npshape = (*shape, veclen)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
vectype = wp.types.vector(veclen, wptype)
# fill with list and specific dtype
a = wp.full(shape, fill_list, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
expected = np.tile(np.array(fill_list, dtype=nptype), a.size).reshape(npshape)
assert_np_equal(na, expected)
fill_arr = np.array(fill_list, dtype=nptype)
# fill with numpy array and specific dtype
a = wp.full(shape, fill_arr, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with numpy array and automatically infer dtype
a = wp.full(shape, fill_arr, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertTrue(wp.types.types_equal(a.dtype, vectype))
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with list and automatically infer dtype
a = wp.full(shape, fill_list, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
# check that the inferred dtype is a vector
# Note that we cannot guarantee the scalar type, because it depends on numpy and may vary by platform
# (e.g. int64 on Linux and int32 on Windows).
test.assertEqual(a.dtype._wp_generic_type_str_, "vec_t")
test.assertEqual(a.dtype._length_, veclen)
expected = np.tile(np.array(fill_list), a.size).reshape(npshape)
assert_np_equal(na, expected)
def test_full_matrix(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mattype in matrix_types:
npshape = (*shape, *mattype._shape_)
# fill with scalar int value and specific dtype
fill_value = 42
a = wp.full(shape, fill_value, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, fill_value, dtype=nptype).reshape(npshape))
if wptype in wp.types.float_types:
# fill with scalar float value and specific dtype
fill_value = 13.37
a = wp.full(shape, fill_value, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, fill_value, dtype=nptype).reshape(npshape))
# fill with matrix value and specific dtype
fill_mat = mattype(42)
a = wp.full(shape, fill_mat, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, 42, dtype=nptype).reshape(npshape))
# fill with matrix value and automatically inferred dtype
fill_mat = mattype(42)
a = wp.full(shape, fill_mat, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.full(a.size * mattype._length_, 42, dtype=nptype).reshape(npshape))
# fill with 1d numpy array and specific dtype
if wptype != wp.bool:
fill_arr1d = np.arange(mattype._length_, dtype=nptype)
else:
fill_arr1d = np.ones(mattype._length_, dtype=nptype)
a = wp.full(shape, fill_arr1d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
expected = np.tile(fill_arr1d, a.size).reshape(npshape)
assert_np_equal(na, expected)
# fill with 2d numpy array and specific dtype
fill_arr2d = fill_arr1d.reshape(mattype._shape_)
a = wp.full(shape, fill_arr2d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with 2d numpy array and automatically infer dtype
a = wp.full(shape, fill_arr2d, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertTrue(wp.types.types_equal(a.dtype, mattype))
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with flat list and specific dtype
fill_list1d = list(fill_arr1d)
a = wp.full(shape, fill_list1d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
# fill with nested list and specific dtype
fill_list2d = [list(row) for row in fill_arr2d]
a = wp.full(shape, fill_list2d, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, expected)
mat_lists = [
# square matrices
[[1, 2], [3, 4]],
[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]],
# non-square matrices
[[1, 2, 3, 4], [5, 6, 7, 8]],
[[1, 2], [3, 4], [5, 6], [7, 8]],
]
# fill with nested lists and automatically infer dtype
for fill_list in mat_lists:
num_rows = len(fill_list)
num_cols = len(fill_list[0])
npshape = (*shape, num_rows, num_cols)
a = wp.full(shape, fill_list, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
# check that the inferred dtype is a correctly shaped matrix
# Note that we cannot guarantee the scalar type, because it depends on numpy and may vary by platform
# (e.g. int64 on Linux and int32 on Windows).
test.assertEqual(a.dtype._wp_generic_type_str_, "mat_t")
test.assertEqual(a.dtype._shape_, (num_rows, num_cols))
expected = np.tile(np.array(fill_list).flatten(), a.size).reshape(npshape)
assert_np_equal(na, expected)
def test_full_struct(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
s = FillStruct()
# fill with default struct (should be zeros)
a = wp.full(shape, s, dtype=FillStruct, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, FillStruct)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, FillStruct.numpy_dtype())
assert_np_equal(na, np.zeros(a.shape, dtype=FillStruct.numpy_dtype()))
# scalars
s.i1 = -17
s.i2 = 42
s.i4 = 99
s.i8 = 101
s.f2 = -1.25
s.f4 = 13.37
s.f8 = 0.125
# vectors
s.v2 = [21, 22]
s.v3 = [31, 32, 33]
s.v4 = [41, 42, 43, 44]
s.v5 = [51, 52, 53, 54, 55]
# matrices
s.m2 = [[61, 62]] * 2
s.m3 = [[71, 72, 73]] * 3
s.m4 = [[81, 82, 83, 84]] * 4
s.m5 = [[91, 92, 93, 94, 95]] * 5
# arrays
s.a1 = wp.zeros((2,) * 1, dtype=float, device=device)
s.a2 = wp.zeros((2,) * 2, dtype=float, device=device)
s.a3 = wp.zeros((2,) * 3, dtype=float, device=device)
s.a4 = wp.zeros((2,) * 4, dtype=float, device=device)
# fill with initialized struct and explicit dtype
a = wp.full(shape, s, dtype=FillStruct, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, FillStruct)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, FillStruct.numpy_dtype())
expected = np.empty(shape, dtype=FillStruct.numpy_dtype())
expected.fill(s.numpy_value())
assert_np_equal(na, expected)
# fill with initialized struct and automatically inferred dtype
a = wp.full(shape, s, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, FillStruct)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, FillStruct.numpy_dtype())
assert_np_equal(na, expected)
def test_ones_scalar(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a = wp.ones(shape, dtype=wptype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wptype)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.ones(shape, dtype=nptype))
def test_ones_vector(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for veclen in [2, 3, 4, 5]:
npshape = (*shape, veclen)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
vectype = wp.types.vector(veclen, wptype)
a = wp.ones(shape, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.ones(npshape, dtype=nptype))
def test_ones_matrix(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mattype in matrix_types:
npshape = (*shape, *mattype._shape_)
a = wp.ones(shape, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.ones(npshape, dtype=nptype))
def test_ones_like_scalar(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# source array
a = wp.zeros(shape, dtype=wptype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, wptype)
test.assertEqual(na.shape, shape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.zeros(shape, dtype=nptype))
# ones array
b = wp.ones_like(a)
nb = b.numpy()
test.assertEqual(b.shape, shape)
test.assertEqual(b.dtype, wptype)
test.assertEqual(nb.shape, shape)
test.assertEqual(nb.dtype, nptype)
assert_np_equal(nb, np.ones(shape, dtype=nptype))
def test_ones_like_vector(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for veclen in [2, 3, 4, 5]:
npshape = (*shape, veclen)
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
vectype = wp.types.vector(veclen, wptype)
# source array
a = wp.zeros(shape, dtype=vectype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, vectype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.zeros(npshape, dtype=nptype))
# ones array
b = wp.ones_like(a)
nb = b.numpy()
test.assertEqual(b.shape, shape)
test.assertEqual(b.dtype, vectype)
test.assertEqual(nb.shape, npshape)
test.assertEqual(nb.dtype, nptype)
assert_np_equal(nb, np.ones(npshape, dtype=nptype))
def test_ones_like_matrix(test, device):
dim = 4
for ndim in range(1, 5):
shape = (dim,) * ndim
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mattype in matrix_types:
npshape = (*shape, *mattype._shape_)
# source array
a = wp.zeros(shape, dtype=mattype, device=device)
na = a.numpy()
test.assertEqual(a.shape, shape)
test.assertEqual(a.dtype, mattype)
test.assertEqual(na.shape, npshape)
test.assertEqual(na.dtype, nptype)
assert_np_equal(na, np.zeros(npshape, dtype=nptype))
# ones array
b = wp.ones_like(a)
nb = b.numpy()
test.assertEqual(b.shape, shape)
test.assertEqual(b.dtype, mattype)
test.assertEqual(nb.shape, npshape)
test.assertEqual(nb.dtype, nptype)
assert_np_equal(nb, np.ones(npshape, dtype=nptype))
def test_round_trip(test, device):
rng = np.random.default_rng(123)
dim_x = 4
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
a_np = rng.standard_normal(size=dim_x).astype(nptype)
a = wp.array(a_np, device=device)
test.assertEqual(a.dtype, wptype)
assert_np_equal(a.numpy(), a_np)
v_np = rng.standard_normal(size=(dim_x, 3)).astype(nptype)
v = wp.array(v_np, dtype=wp.types.vector(3, wptype), device=device)
assert_np_equal(v.numpy(), v_np)
def test_empty_array(test, device):
# Test whether common operations work with empty (zero-sized) arrays
# without throwing exceptions.
def test_empty_ops(ndim, nrows, ncols, wptype, nptype):
shape = (0,) * ndim
dtype_shape = ()
if wptype in wp.types.scalar_types:
# scalar, vector, or matrix
if ncols > 0:
if nrows > 0:
wptype = wp.types.matrix((nrows, ncols), wptype)
else:
wptype = wp.types.vector(ncols, wptype)
dtype_shape = wptype._shape_
fill_value = wptype(42)
else:
# struct
fill_value = wptype()
# create a zero-sized array
a = wp.empty(shape, dtype=wptype, device=device, requires_grad=True)
test.assertEqual(a.ptr, None)
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, shape)
test.assertEqual(a.grad.ptr, None)
test.assertEqual(a.grad.size, 0)
test.assertEqual(a.grad.shape, shape)
# all of these methods should succeed with zero-sized arrays
a.zero_()
a.fill_(fill_value)
b = a.flatten()
b = a.reshape((0,))
b = a.transpose()
b = a.contiguous()
b = wp.empty_like(a)
b = wp.zeros_like(a)
b = wp.full_like(a, fill_value)
b = wp.clone(a)
wp.copy(a, b)
a.assign(b)
na = a.numpy()
test.assertEqual(na.size, 0)
test.assertEqual(na.shape, (*shape, *dtype_shape))
test.assertEqual(na.dtype, nptype)
test.assertEqual(a.list(), [])
for ndim in range(1, 5):
# test with scalars, vectors, and matrices
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# scalars
test_empty_ops(ndim, 0, 0, wptype, nptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_ops(ndim, 0, ncols, wptype, nptype)
# square matrices
test_empty_ops(ndim, ncols, ncols, wptype, nptype)
# non-square matrices
test_empty_ops(ndim, 2, 3, wptype, nptype)
test_empty_ops(ndim, 3, 2, wptype, nptype)
test_empty_ops(ndim, 3, 4, wptype, nptype)
test_empty_ops(ndim, 4, 3, wptype, nptype)
# test with structs
test_empty_ops(ndim, 0, 0, FillStruct, FillStruct.numpy_dtype())
def test_empty_from_numpy(test, device):
# Test whether wrapping an empty (zero-sized) numpy array works correctly
def test_empty_from_data(ndim, nrows, ncols, wptype, nptype):
shape = (0,) * ndim
dtype_shape = ()
if ncols > 0:
if nrows > 0:
wptype = wp.types.matrix((nrows, ncols), wptype)
else:
wptype = wp.types.vector(ncols, wptype)
dtype_shape = wptype._shape_
npshape = (*shape, *dtype_shape)
na = np.empty(npshape, dtype=nptype)
a = wp.array(na, dtype=wptype, device=device)
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, shape)
for ndim in range(1, 5):
# test with scalars, vectors, and matrices
for nptype, wptype in wp.types.np_dtype_to_warp_type.items():
# scalars
test_empty_from_data(ndim, 0, 0, wptype, nptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_from_data(ndim, 0, ncols, wptype, nptype)
# square matrices
test_empty_from_data(ndim, ncols, ncols, wptype, nptype)
# non-square matrices
test_empty_from_data(ndim, 2, 3, wptype, nptype)
test_empty_from_data(ndim, 3, 2, wptype, nptype)
test_empty_from_data(ndim, 3, 4, wptype, nptype)
test_empty_from_data(ndim, 4, 3, wptype, nptype)
def test_empty_from_list(test, device):
# Test whether creating an array from an empty Python list works correctly
def test_empty_from_data(nrows, ncols, wptype):
if ncols > 0:
if nrows > 0:
wptype = wp.types.matrix((nrows, ncols), wptype)
else:
wptype = wp.types.vector(ncols, wptype)
a = wp.array([], dtype=wptype, device=device)
test.assertEqual(a.size, 0)
test.assertEqual(a.shape, (0,))
# test with scalars, vectors, and matrices
for wptype in wp.types.scalar_types:
# scalars
test_empty_from_data(0, 0, wptype)
for ncols in [2, 3, 4, 5]:
# vectors
test_empty_from_data(0, ncols, wptype)
# square matrices
test_empty_from_data(ncols, ncols, wptype)
# non-square matrices
test_empty_from_data(2, 3, wptype)
test_empty_from_data(3, 2, wptype)
test_empty_from_data(3, 4, wptype)
test_empty_from_data(4, 3, wptype)
def test_to_list_scalar(test, device):
dim = 3
fill_value = 42
for ndim in range(1, 5):
shape = (dim,) * ndim
for wptype in wp.types.scalar_types:
a = wp.full(shape, fill_value, dtype=wptype, device=device)
l = a.list()
test.assertEqual(len(l), a.size)
test.assertTrue(all(x == fill_value for x in l))
def test_to_list_vector(test, device):
dim = 3
for ndim in range(1, 5):
shape = (dim,) * ndim
for veclen in [2, 3, 4, 5]:
for wptype in wp.types.scalar_types:
vectype = wp.types.vector(veclen, wptype)
fill_value = vectype(42)
a = wp.full(shape, fill_value, dtype=vectype, device=device)
l = a.list()
test.assertEqual(len(l), a.size)
test.assertTrue(all(x == fill_value for x in l))
def test_to_list_matrix(test, device):
dim = 3
for ndim in range(1, 5):
shape = (dim,) * ndim
for wptype in wp.types.scalar_types:
matrix_types = [
# square matrices
wp.types.matrix((2, 2), wptype),
wp.types.matrix((3, 3), wptype),
wp.types.matrix((4, 4), wptype),
wp.types.matrix((5, 5), wptype),
# non-square matrices
wp.types.matrix((2, 3), wptype),
wp.types.matrix((3, 2), wptype),
wp.types.matrix((3, 4), wptype),
wp.types.matrix((4, 3), wptype),
]
for mattype in matrix_types:
fill_value = mattype(42)
a = wp.full(shape, fill_value, dtype=mattype, device=device)
l = a.list()
test.assertEqual(len(l), a.size)
test.assertTrue(all(x == fill_value for x in l))
def test_to_list_struct(test, device):
@wp.struct
class Inner:
h: wp.float16
v: wp.vec3
@wp.struct
class ListStruct:
i: int
f: float
h: wp.float16
vi: wp.vec2i
vf: wp.vec3f
vh: wp.vec4h
mi: wp.types.matrix((2, 2), int)
mf: wp.types.matrix((3, 3), float)
mh: wp.types.matrix((4, 4), wp.float16)
inner: Inner
a1: wp.array(dtype=int)
a2: wp.array2d(dtype=float)
a3: wp.array3d(dtype=wp.float16)
bool: wp.bool
dim = 3
s = ListStruct()
s.i = 42
s.f = 2.5
s.h = -1.25
s.vi = wp.vec2i(1, 2)
s.vf = wp.vec3f(0.1, 0.2, 0.3)
s.vh = wp.vec4h(1.0, 2.0, 3.0, 4.0)
s.mi = [[1, 2], [3, 4]]
s.mf = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
s.mh = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
s.inner = Inner()
s.inner.h = 1.5
s.inner.v = [1, 2, 3]
s.a1 = wp.empty(1, dtype=int, device=device)
s.a2 = wp.empty((1, 1), dtype=float, device=device)
s.a3 = wp.empty((1, 1, 1), dtype=wp.float16, device=device)
s.bool = True
for ndim in range(1, 5):
shape = (dim,) * ndim
a = wp.full(shape, s, dtype=ListStruct, device=device)
l = a.list()
for i in range(a.size):
test.assertEqual(l[i].i, s.i)
test.assertEqual(l[i].f, s.f)
test.assertEqual(l[i].h, s.h)
test.assertEqual(l[i].vi, s.vi)
test.assertEqual(l[i].vf, s.vf)
test.assertEqual(l[i].vh, s.vh)
test.assertEqual(l[i].mi, s.mi)
test.assertEqual(l[i].mf, s.mf)
test.assertEqual(l[i].mh, s.mh)
test.assertEqual(l[i].bool, s.bool)
test.assertEqual(l[i].inner.h, s.inner.h)
test.assertEqual(l[i].inner.v, s.inner.v)
test.assertEqual(l[i].a1.dtype, s.a1.dtype)
test.assertEqual(l[i].a1.ndim, s.a1.ndim)
test.assertEqual(l[i].a2.dtype, s.a2.dtype)
test.assertEqual(l[i].a2.ndim, s.a2.ndim)
test.assertEqual(l[i].a3.dtype, s.a3.dtype)
test.assertEqual(l[i].a3.ndim, s.a3.ndim)
@wp.kernel
def kernel_array_to_bool(array_null: wp.array(dtype=float), array_valid: wp.array(dtype=float)):
if not array_null:
# always succeed
wp.expect_eq(0, 0)
else:
# force failure
wp.expect_eq(1, 2)
if array_valid:
# always succeed
wp.expect_eq(0, 0)
else:
# force failure
wp.expect_eq(1, 2)
def test_array_to_bool(test, device):
arr = wp.zeros(8, dtype=float, device=device)
wp.launch(kernel_array_to_bool, dim=1, inputs=[None, arr], device=device)
@wp.struct
class InputStruct:
param1: int
param2: float
param3: wp.vec3
param4: wp.array(dtype=float)
@wp.struct
class OutputStruct:
param1: int
param2: float
param3: wp.vec3
@wp.kernel
def struct_array_kernel(inputs: wp.array(dtype=InputStruct), outputs: wp.array(dtype=OutputStruct)):
tid = wp.tid()
wp.expect_eq(inputs[tid].param1, tid)
wp.expect_eq(inputs[tid].param2, float(tid * tid))
wp.expect_eq(inputs[tid].param3[0], 1.0)
wp.expect_eq(inputs[tid].param3[1], 2.0)
wp.expect_eq(inputs[tid].param3[2], 3.0)
wp.expect_eq(inputs[tid].param4[0], 1.0)
wp.expect_eq(inputs[tid].param4[1], 2.0)
wp.expect_eq(inputs[tid].param4[2], 3.0)
o = OutputStruct()
o.param1 = inputs[tid].param1
o.param2 = inputs[tid].param2
o.param3 = inputs[tid].param3
outputs[tid] = o
def test_array_of_structs(test, device):
num_items = 10
l = []
for i in range(num_items):
s = InputStruct()
s.param1 = i
s.param2 = float(i * i)
s.param3 = wp.vec3(1.0, 2.0, 3.0)
s.param4 = wp.array([1.0, 2.0, 3.0], dtype=float, device=device)
l.append(s)
# initialize array from list of structs
inputs = wp.array(l, dtype=InputStruct, device=device)
outputs = wp.zeros(num_items, dtype=OutputStruct, device=device)
# pass to our compute kernel
wp.launch(struct_array_kernel, dim=num_items, inputs=[inputs, outputs], device=device)
out_numpy = outputs.numpy()
out_list = outputs.list()
out_cptr = outputs.to("cpu").cptr()
for i in range(num_items):
test.assertEqual(out_numpy[i][0], l[i].param1)
test.assertEqual(out_numpy[i][1], l[i].param2)
assert_np_equal(out_numpy[i][2], np.array(l[i].param3))
# test named slices of numpy structured array
test.assertEqual(out_numpy["param1"][i], l[i].param1)
test.assertEqual(out_numpy["param2"][i], l[i].param2)
assert_np_equal(out_numpy["param3"][i], np.array(l[i].param3))
test.assertEqual(out_list[i].param1, l[i].param1)
test.assertEqual(out_list[i].param2, l[i].param2)
test.assertEqual(out_list[i].param3, l[i].param3)
test.assertEqual(out_cptr[i].param1, l[i].param1)
test.assertEqual(out_cptr[i].param2, l[i].param2)
test.assertEqual(out_cptr[i].param3, l[i].param3)
@wp.struct
class GradStruct:
param1: int
param2: float
param3: wp.vec3
@wp.kernel
def test_array_of_structs_grad_kernel(inputs: wp.array(dtype=GradStruct), loss: wp.array(dtype=float)):
tid = wp.tid()
wp.atomic_add(loss, 0, inputs[tid].param2 * 2.0)
def test_array_of_structs_grad(test, device):
num_items = 10
l = []
for i in range(num_items):
g = GradStruct()
g.param2 = float(i)
l.append(g)
a = wp.array(l, dtype=GradStruct, device=device, requires_grad=True)
loss = wp.zeros(1, dtype=float, device=device, requires_grad=True)
with wp.Tape() as tape:
wp.launch(test_array_of_structs_grad_kernel, dim=num_items, inputs=[a, loss], device=device)
tape.backward(loss)
grads = a.grad.numpy()
assert_np_equal(grads["param2"], np.full(num_items, 2.0, dtype=np.float32))
@wp.struct
class NumpyStruct:
x: int
v: wp.vec3
def test_array_of_structs_from_numpy(test, device):
num_items = 10
na = np.zeros(num_items, dtype=NumpyStruct.numpy_dtype())
na["x"] = 17
na["v"] = (1, 2, 3)
a = wp.array(data=na, dtype=NumpyStruct, device=device)
assert_np_equal(a.numpy(), na)
def test_array_of_structs_roundtrip(test, device):
num_items = 10
value = NumpyStruct()
value.x = 17
value.v = wp.vec3(1.0, 2.0, 3.0)
# create Warp structured array
a = wp.full(num_items, value, device=device)
# convert to NumPy structured array
na = a.numpy()
expected = np.zeros(num_items, dtype=NumpyStruct.numpy_dtype())
expected["x"] = value.x
expected["v"] = value.v
assert_np_equal(na, expected)
# modify a field
na["x"] = 42
# convert back to Warp array
a = wp.from_numpy(na, NumpyStruct, device=device)
expected["x"] = 42
assert_np_equal(a.numpy(), expected)
def test_array_from_numpy(test, device):
arr = np.array((1.0, 2.0, 3.0), dtype=float)
result = wp.from_numpy(arr, device=device)
expected = wp.array((1.0, 2.0, 3.0), dtype=wp.float32, shape=(3,))
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.vec3, device=device)
expected = wp.array(((1.0, 2.0, 3.0),), dtype=wp.vec3, shape=(1,))
assert_np_equal(result.numpy(), expected.numpy())
# --------------------------------------------------------------------------
arr = np.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=float)
result = wp.from_numpy(arr, device=device)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.vec3, shape=(2,))
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32, device=device)
expected = wp.array(((1.0, 2.0, 3.0), (4.0, 5.0, 6.0)), dtype=wp.float32, shape=(2, 3))
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32, shape=(6,), device=device)
expected = wp.array((1.0, 2.0, 3.0, 4.0, 5.0, 6.0), dtype=wp.float32, shape=(6,))
assert_np_equal(result.numpy(), expected.numpy())
# --------------------------------------------------------------------------
arr = np.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=float,
)
result = wp.from_numpy(arr, device=device)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.mat44,
shape=(2,),
)
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32, device=device)
expected = wp.array(
(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
),
(
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
),
dtype=wp.float32,
shape=(2, 4, 4),
)
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.vec4, device=device).reshape((8,)) # Reshape from (2, 4)
expected = wp.array(
(
(1.0, 2.0, 3.0, 4.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(2.0, 3.0, 4.0, 5.0),
(3.0, 4.0, 5.0, 6.0),
(4.0, 5.0, 6.0, 7.0),
(5.0, 6.0, 7.0, 8.0),
),
dtype=wp.vec4,
shape=(8,),
)
assert_np_equal(result.numpy(), expected.numpy())
result = wp.from_numpy(arr, dtype=wp.float32, shape=(32,), device=device)
expected = wp.array(
(
1.0,
2.0,
3.0,
4.0,
2.0,
3.0,
4.0,
5.0,
3.0,
4.0,
5.0,
6.0,
4.0,
5.0,
6.0,
7.0,
2.0,
3.0,
4.0,
5.0,
3.0,
4.0,
5.0,
6.0,
4.0,
5.0,
6.0,
7.0,
5.0,
6.0,
7.0,
8.0,
),
dtype=wp.float32,
shape=(32,),
)
assert_np_equal(result.numpy(), expected.numpy())
def test_array_from_cai(test, device):
import torch
@wp.kernel
def first_row_plus_one(x: wp.array2d(dtype=float)):
i, j = wp.tid()
if i == 0:
x[i, j] += 1.0
# start with torch tensor
arr = torch.zeros((3, 3))
torch_device = wp.device_to_torch(device)
arr_torch = arr.to(torch_device)
# wrap as warp array via __cuda_array_interface__
arr_warp = wp.array(arr_torch, device=device)
wp.launch(kernel=first_row_plus_one, dim=(3, 3), inputs=[arr_warp], device=device)
# re-wrap as torch array
arr_torch = wp.to_torch(arr_warp)
# transpose
arr_torch = torch.as_strided(arr_torch, size=(3, 3), stride=(arr_torch.stride(1), arr_torch.stride(0)))
# re-wrap as warp array with new strides
arr_warp = wp.array(arr_torch, device=device)
wp.launch(kernel=first_row_plus_one, dim=(3, 3), inputs=[arr_warp], device=device)
assert_np_equal(arr_warp.numpy(), np.array([[2, 1, 1], [1, 0, 0], [1, 0, 0]]))
devices = get_test_devices()
class TestArray(unittest.TestCase):
def test_array_new_del(self):
# test the scenario in which an array instance is created but not initialized before gc
instance = wp.array.__new__(wp.array)
instance.__del__()
add_function_test(TestArray, "test_shape", test_shape, devices=devices)
add_function_test(TestArray, "test_negative_shape", test_negative_shape, devices=devices)
add_function_test(TestArray, "test_flatten", test_flatten, devices=devices)
add_function_test(TestArray, "test_reshape", test_reshape, devices=devices)
add_function_test(TestArray, "test_slicing", test_slicing, devices=devices)
add_function_test(TestArray, "test_transpose", test_transpose, devices=devices)
add_function_test(TestArray, "test_view", test_view, devices=devices)
add_function_test(TestArray, "test_clone_adjoint", test_clone_adjoint, devices=devices)
add_function_test(TestArray, "test_assign_adjoint", test_assign_adjoint, devices=devices)
add_function_test(TestArray, "test_1d_array", test_1d, devices=devices)
add_function_test(TestArray, "test_2d_array", test_2d, devices=devices)
add_function_test(TestArray, "test_3d_array", test_3d, devices=devices)
add_function_test(TestArray, "test_4d_array", test_4d, devices=devices)
add_function_test(TestArray, "test_4d_array_transposed", test_4d_transposed, devices=devices)
add_function_test(TestArray, "test_fill_scalar", test_fill_scalar, devices=devices)
add_function_test(TestArray, "test_fill_vector", test_fill_vector, devices=devices)
add_function_test(TestArray, "test_fill_matrix", test_fill_matrix, devices=devices)
add_function_test(TestArray, "test_fill_struct", test_fill_struct, devices=devices)
add_function_test(TestArray, "test_fill_slices", test_fill_slices, devices=devices)
add_function_test(TestArray, "test_full_scalar", test_full_scalar, devices=devices)
add_function_test(TestArray, "test_full_vector", test_full_vector, devices=devices)
add_function_test(TestArray, "test_full_matrix", test_full_matrix, devices=devices)
add_function_test(TestArray, "test_full_struct", test_full_struct, devices=devices)
add_function_test(TestArray, "test_ones_scalar", test_ones_scalar, devices=devices)
add_function_test(TestArray, "test_ones_vector", test_ones_vector, devices=devices)
add_function_test(TestArray, "test_ones_matrix", test_ones_matrix, devices=devices)
add_function_test(TestArray, "test_ones_like_scalar", test_ones_like_scalar, devices=devices)
add_function_test(TestArray, "test_ones_like_vector", test_ones_like_vector, devices=devices)
add_function_test(TestArray, "test_ones_like_matrix", test_ones_like_matrix, devices=devices)
add_function_test(TestArray, "test_empty_array", test_empty_array, devices=devices)
add_function_test(TestArray, "test_empty_from_numpy", test_empty_from_numpy, devices=devices)
add_function_test(TestArray, "test_empty_from_list", test_empty_from_list, devices=devices)
add_function_test(TestArray, "test_to_list_scalar", test_to_list_scalar, devices=devices)
add_function_test(TestArray, "test_to_list_vector", test_to_list_vector, devices=devices)
add_function_test(TestArray, "test_to_list_matrix", test_to_list_matrix, devices=devices)
add_function_test(TestArray, "test_to_list_struct", test_to_list_struct, devices=devices)
add_function_test(TestArray, "test_lower_bound", test_lower_bound, devices=devices)
add_function_test(TestArray, "test_round_trip", test_round_trip, devices=devices)
add_function_test(TestArray, "test_array_to_bool", test_array_to_bool, devices=devices)
add_function_test(TestArray, "test_array_of_structs", test_array_of_structs, devices=devices)
add_function_test(TestArray, "test_array_of_structs_grad", test_array_of_structs_grad, devices=devices)
add_function_test(TestArray, "test_array_of_structs_from_numpy", test_array_of_structs_from_numpy, devices=devices)
add_function_test(TestArray, "test_array_of_structs_roundtrip", test_array_of_structs_roundtrip, devices=devices)
add_function_test(TestArray, "test_array_from_numpy", test_array_from_numpy, devices=devices)
try:
import torch
# check which Warp devices work with Torch
# CUDA devices may fail if Torch was not compiled with CUDA support
torch_compatible_devices = []
torch_compatible_cuda_devices = []
for d in devices:
try:
t = torch.arange(10, device=wp.device_to_torch(d))
t += 1
torch_compatible_devices.append(d)
if d.is_cuda:
torch_compatible_cuda_devices.append(d)
except Exception as e:
print(f"Skipping Array tests that use Torch on device '{d}' due to exception: {e}")
add_function_test(TestArray, "test_array_from_cai", test_array_from_cai, devices=torch_compatible_cuda_devices)
except Exception as e:
print(f"Skipping Array tests that use Torch due to exception: {e}")
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 85,239 | Python | 34.281457 | 126 | 0.566243 |
NVIDIA/warp/warp/tests/test_streams.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
from warp.utils import check_iommu
@wp.kernel
def inc(a: wp.array(dtype=float)):
tid = wp.tid()
a[tid] = a[tid] + 1.0
@wp.kernel
def inc_new(src: wp.array(dtype=float), dst: wp.array(dtype=float)):
tid = wp.tid()
dst[tid] = src[tid] + 1.0
@wp.kernel
def sum(a: wp.array(dtype=float), b: wp.array(dtype=float), c: wp.array(dtype=float)):
tid = wp.tid()
c[tid] = a[tid] + b[tid]
# number of elements to use for testing
N = 10 * 1024 * 1024
def test_stream_set(test, device):
device = wp.get_device(device)
old_stream = device.stream
new_stream = wp.Stream(device)
try:
wp.set_stream(new_stream, device)
test.assertTrue(device.has_stream)
test.assertEqual(device.stream, new_stream)
finally:
# restore original stream
wp.set_stream(old_stream, device)
def test_stream_arg_explicit_sync(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.full(N, 42, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
old_stream = wp.get_stream(device)
new_stream = wp.Stream(device)
# allocations need to be explicitly synced before launching work using stream arguments
new_stream.wait_stream(old_stream)
# launch work on new stream
wp.launch(inc, dim=a.size, inputs=[a], stream=new_stream)
wp.copy(b, a, stream=new_stream)
wp.launch(inc, dim=a.size, inputs=[a], stream=new_stream)
wp.copy(c, a, stream=new_stream)
wp.launch(inc, dim=a.size, inputs=[a], stream=new_stream)
assert_np_equal(a.numpy(), np.full(N, fill_value=3.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
def test_stream_scope_implicit_sync(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.full(N, 42, dtype=float)
c = wp.empty(N, dtype=float)
old_stream = wp.get_stream()
new_stream = wp.Stream()
# launch work on new stream
# allocations are implicitly synced when entering wp.ScopedStream
with wp.ScopedStream(new_stream):
assert wp.get_stream() == new_stream
wp.launch(inc, dim=a.size, inputs=[a])
wp.copy(b, a)
wp.launch(inc, dim=a.size, inputs=[a])
wp.copy(c, a)
wp.launch(inc, dim=a.size, inputs=[a])
assert wp.get_stream() == old_stream
assert_np_equal(a.numpy(), np.full(N, fill_value=3.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
def test_stream_arg_synchronize(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
d = wp.empty(N, dtype=float, device=device)
stream1 = wp.get_stream(device)
stream2 = wp.Stream(device)
stream3 = wp.Stream(device)
wp.launch(inc, dim=N, inputs=[a], device=device)
# b and c depend on a
wp.synchronize_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, b], stream=stream2)
wp.launch(inc_new, dim=N, inputs=[a, c], stream=stream3)
# d depends on b and c
wp.synchronize_stream(stream2)
wp.synchronize_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d], device=device)
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_arg_wait_event(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
d = wp.empty(N, dtype=float, device=device)
stream1 = wp.get_stream(device)
stream2 = wp.Stream(device)
stream3 = wp.Stream(device)
event1 = wp.Event(device)
event2 = wp.Event(device)
event3 = wp.Event(device)
wp.launch(inc, dim=N, inputs=[a], stream=stream1)
stream1.record_event(event1)
# b and c depend on a
stream2.wait_event(event1)
stream3.wait_event(event1)
wp.launch(inc_new, dim=N, inputs=[a, b], stream=stream2)
stream2.record_event(event2)
wp.launch(inc_new, dim=N, inputs=[a, c], stream=stream3)
stream3.record_event(event3)
# d depends on b and c
stream1.wait_event(event2)
stream1.wait_event(event3)
wp.launch(sum, dim=N, inputs=[b, c, d], stream=stream1)
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_arg_wait_stream(test, device):
a = wp.zeros(N, dtype=float, device=device)
b = wp.empty(N, dtype=float, device=device)
c = wp.empty(N, dtype=float, device=device)
d = wp.empty(N, dtype=float, device=device)
stream1 = wp.get_stream(device)
stream2 = wp.Stream(device)
stream3 = wp.Stream(device)
wp.launch(inc, dim=N, inputs=[a], stream=stream1)
# b and c depend on a
stream2.wait_stream(stream1)
stream3.wait_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, b], stream=stream2)
wp.launch(inc_new, dim=N, inputs=[a, c], stream=stream3)
# d depends on b and c
stream1.wait_stream(stream2)
stream1.wait_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d], stream=stream1)
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_scope_synchronize(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
d = wp.empty(N, dtype=float)
stream2 = wp.Stream()
stream3 = wp.Stream()
wp.launch(inc, dim=N, inputs=[a])
# b and c depend on a
wp.synchronize_stream()
with wp.ScopedStream(stream2):
wp.launch(inc_new, dim=N, inputs=[a, b])
with wp.ScopedStream(stream3):
wp.launch(inc_new, dim=N, inputs=[a, c])
# d depends on b and c
wp.synchronize_stream(stream2)
wp.synchronize_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d])
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_scope_wait_event(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
d = wp.empty(N, dtype=float)
stream2 = wp.Stream()
stream3 = wp.Stream()
event1 = wp.Event()
event2 = wp.Event()
event3 = wp.Event()
wp.launch(inc, dim=N, inputs=[a])
wp.record_event(event1)
# b and c depend on a
with wp.ScopedStream(stream2):
wp.wait_event(event1)
wp.launch(inc_new, dim=N, inputs=[a, b])
wp.record_event(event2)
with wp.ScopedStream(stream3):
wp.wait_event(event1)
wp.launch(inc_new, dim=N, inputs=[a, c])
wp.record_event(event3)
# d depends on b and c
wp.wait_event(event2)
wp.wait_event(event3)
wp.launch(sum, dim=N, inputs=[b, c, d])
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_stream_scope_wait_stream(test, device):
with wp.ScopedDevice(device):
a = wp.zeros(N, dtype=float)
b = wp.empty(N, dtype=float)
c = wp.empty(N, dtype=float)
d = wp.empty(N, dtype=float)
stream1 = wp.get_stream()
stream2 = wp.Stream()
stream3 = wp.Stream()
wp.launch(inc, dim=N, inputs=[a])
# b and c depend on a
with wp.ScopedStream(stream2):
wp.wait_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, b])
with wp.ScopedStream(stream3):
wp.wait_stream(stream1)
wp.launch(inc_new, dim=N, inputs=[a, c])
# d depends on b and c
wp.wait_stream(stream2)
wp.wait_stream(stream3)
wp.launch(sum, dim=N, inputs=[b, c, d])
assert_np_equal(a.numpy(), np.full(N, fill_value=1.0))
assert_np_equal(b.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(c.numpy(), np.full(N, fill_value=2.0))
assert_np_equal(d.numpy(), np.full(N, fill_value=4.0))
def test_event_synchronize(test, device):
stream = wp.get_stream(device)
a_host = wp.empty(N, dtype=float, device="cpu", pinned=True)
b_host = wp.empty(N, dtype=float, device="cpu", pinned=True)
# initialize GPU array and do an asynchronous readback
a = wp.full(N, 17, dtype=float, device=device)
wp.copy(a_host, a)
a_event = stream.record_event()
b = wp.full(N, 42, dtype=float, device=device)
wp.copy(b_host, b)
b_event = stream.record_event()
wp.synchronize_event(a_event)
assert_np_equal(a_host.numpy(), np.full(N, fill_value=17.0))
wp.synchronize_event(b_event)
assert_np_equal(b_host.numpy(), np.full(N, fill_value=42.0))
def test_event_elapsed_time(test, device):
stream = wp.get_stream(device)
e1 = wp.Event(device, enable_timing=True)
e2 = wp.Event(device, enable_timing=True)
a = wp.zeros(N, dtype=float, device=device)
stream.record_event(e1)
wp.launch(inc, dim=N, inputs=[a], device=device)
stream.record_event(e2)
elapsed = wp.get_event_elapsed_time(e1, e2)
test.assertGreater(elapsed, 0)
devices = get_selected_cuda_test_devices()
class TestStreams(unittest.TestCase):
def test_stream_exceptions(self):
cpu_device = wp.get_device("cpu")
# Can't set the stream on a CPU device
with self.assertRaises(RuntimeError):
stream0 = wp.Stream()
cpu_device.stream = stream0
# Can't create a stream on the CPU
with self.assertRaises(RuntimeError):
wp.Stream(device="cpu")
# Can't create an event with CPU device
with self.assertRaises(RuntimeError):
wp.Event(device=cpu_device)
# Can't get the stream on a CPU device
with self.assertRaises(RuntimeError):
cpu_stream = cpu_device.stream # noqa: F841
@unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices")
@unittest.skipUnless(check_iommu(), "IOMMU seems enabled")
def test_stream_arg_graph_mgpu(self):
wp.load_module(device="cuda:0")
wp.load_module(device="cuda:1")
# Peer-to-peer copies are not possible during graph capture if the arrays were
# allocated using pooled allocators and mempool access is not enabled.
# Here, we force default CUDA allocators and pre-allocate the memory.
with wp.ScopedMempool("cuda:0", False), wp.ScopedMempool("cuda:1", False):
# resources on GPU 0
stream0 = wp.get_stream("cuda:0")
a0 = wp.zeros(N, dtype=float, device="cuda:0")
b0 = wp.empty(N, dtype=float, device="cuda:0")
c0 = wp.empty(N, dtype=float, device="cuda:0")
# resources on GPU 1
stream1 = wp.get_stream("cuda:1")
a1 = wp.zeros(N, dtype=float, device="cuda:1")
# start recording on stream0
wp.capture_begin(stream=stream0, force_module_load=False)
try:
# branch into stream1
stream1.wait_stream(stream0)
# launch concurrent kernels on each stream
wp.launch(inc, dim=N, inputs=[a0], stream=stream0)
wp.launch(inc, dim=N, inputs=[a1], stream=stream1)
# wait for stream1 to finish
stream0.wait_stream(stream1)
# copy values from stream1
wp.copy(b0, a1, stream=stream0)
# compute sum
wp.launch(sum, dim=N, inputs=[a0, b0, c0], stream=stream0)
finally:
# finish recording on stream0
g = wp.capture_end(stream=stream0)
# replay
num_iters = 10
for _ in range(num_iters):
wp.capture_launch(g, stream=stream0)
# check results
assert_np_equal(c0.numpy(), np.full(N, fill_value=2 * num_iters))
@unittest.skipUnless(len(wp.get_cuda_devices()) > 1, "Requires at least two CUDA devices")
@unittest.skipUnless(check_iommu(), "IOMMU seems enabled")
def test_stream_scope_graph_mgpu(self):
wp.load_module(device="cuda:0")
wp.load_module(device="cuda:1")
# Peer-to-peer copies are not possible during graph capture if the arrays were
# allocated using pooled allocators and mempool access is not enabled.
# Here, we force default CUDA allocators and pre-allocate the memory.
with wp.ScopedMempool("cuda:0", False), wp.ScopedMempool("cuda:1", False):
# resources on GPU 0
with wp.ScopedDevice("cuda:0"):
stream0 = wp.get_stream()
a0 = wp.zeros(N, dtype=float)
b0 = wp.empty(N, dtype=float)
c0 = wp.empty(N, dtype=float)
# resources on GPU 1
with wp.ScopedDevice("cuda:1"):
stream1 = wp.get_stream()
a1 = wp.zeros(N, dtype=float)
# capture graph
with wp.ScopedDevice("cuda:0"):
# start recording
wp.capture_begin(force_module_load=False)
try:
with wp.ScopedDevice("cuda:1"):
# branch into stream1
wp.wait_stream(stream0)
wp.launch(inc, dim=N, inputs=[a1])
wp.launch(inc, dim=N, inputs=[a0])
# wait for stream1 to finish
wp.wait_stream(stream1)
# copy values from stream1
wp.copy(b0, a1)
# compute sum
wp.launch(sum, dim=N, inputs=[a0, b0, c0])
finally:
# finish recording
g = wp.capture_end()
# replay
with wp.ScopedDevice("cuda:0"):
num_iters = 10
for _ in range(num_iters):
wp.capture_launch(g)
# check results
assert_np_equal(c0.numpy(), np.full(N, fill_value=2 * num_iters))
add_function_test(TestStreams, "test_stream_set", test_stream_set, devices=devices)
add_function_test(TestStreams, "test_stream_arg_explicit_sync", test_stream_arg_explicit_sync, devices=devices)
add_function_test(TestStreams, "test_stream_scope_implicit_sync", test_stream_scope_implicit_sync, devices=devices)
add_function_test(TestStreams, "test_stream_arg_synchronize", test_stream_arg_synchronize, devices=devices)
add_function_test(TestStreams, "test_stream_arg_wait_event", test_stream_arg_wait_event, devices=devices)
add_function_test(TestStreams, "test_stream_arg_wait_stream", test_stream_arg_wait_stream, devices=devices)
add_function_test(TestStreams, "test_stream_scope_synchronize", test_stream_scope_synchronize, devices=devices)
add_function_test(TestStreams, "test_stream_scope_wait_event", test_stream_scope_wait_event, devices=devices)
add_function_test(TestStreams, "test_stream_scope_wait_stream", test_stream_scope_wait_stream, devices=devices)
add_function_test(TestStreams, "test_event_synchronize", test_event_synchronize, devices=devices)
add_function_test(TestStreams, "test_event_elapsed_time", test_event_elapsed_time, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 16,901 | Python | 33.849484 | 115 | 0.610911 |
NVIDIA/warp/warp/tests/test_smoothstep.py | # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
from dataclasses import dataclass
from typing import Any
import numpy as np
import warp as wp
from warp.tests.unittest_utils import *
@dataclass
class TestData:
a: Any
b: Any
t: float
expected: Any
expected_adj_a: Any = None
expected_adj_b: Any = None
expected_adj_t: float = None
def check_backwards(self):
return self.expected_adj_a is not None and self.expected_adj_b is not None and self.expected_adj_t is not None
TEST_DATA = {
wp.float32: (
TestData(
a=1.0,
b=2.0,
t=1.5,
expected=0.5,
expected_adj_a=-0.75,
expected_adj_b=-0.75,
expected_adj_t=1.5,
),
TestData(
a=-1.0,
b=2.0,
t=-0.25,
expected=0.15625,
expected_adj_a=-0.28125,
expected_adj_b=-0.09375,
expected_adj_t=0.375,
),
TestData(
a=0.0,
b=1.0,
t=9.9,
expected=1.0,
expected_adj_a=0.0,
expected_adj_b=0.0,
expected_adj_t=0.0,
),
TestData(
a=0.0,
b=1.0,
t=-9.9,
expected=0.0,
expected_adj_a=0.0,
expected_adj_b=0.0,
expected_adj_t=0.0,
),
),
}
def test_smoothstep(test, device):
def make_kernel_fn(data_type):
def fn(
a: wp.array(dtype=data_type),
b: wp.array(dtype=data_type),
t: wp.array(dtype=float),
out: wp.array(dtype=data_type),
):
out[0] = wp.smoothstep(a[0], b[0], t[0])
return fn
for data_type in TEST_DATA:
kernel_fn = make_kernel_fn(data_type)
kernel = wp.Kernel(
func=kernel_fn,
key=f"test_smoothstep{data_type.__name__}_kernel",
)
for test_data in TEST_DATA[data_type]:
a = wp.array(
[test_data.a],
dtype=data_type,
device=device,
requires_grad=True,
)
b = wp.array(
[test_data.b],
dtype=data_type,
device=device,
requires_grad=True,
)
t = wp.array(
[test_data.t],
dtype=float,
device=device,
requires_grad=True,
)
out = wp.array(
[0] * wp.types.type_length(data_type),
dtype=data_type,
device=device,
requires_grad=True,
)
tape = wp.Tape()
with tape:
wp.launch(
kernel,
dim=1,
inputs=[a, b, t, out],
device=device,
)
assert_np_equal(
out.numpy(),
np.array([test_data.expected]),
tol=1e-6,
)
if test_data.check_backwards():
tape.backward(out)
assert_np_equal(
tape.gradients[a].numpy(),
np.array([test_data.expected_adj_a]),
tol=1e-6,
)
assert_np_equal(
tape.gradients[b].numpy(),
np.array([test_data.expected_adj_b]),
tol=1e-6,
)
assert_np_equal(
tape.gradients[t].numpy(),
np.array([test_data.expected_adj_t]),
tol=1e-6,
)
devices = get_test_devices()
class TestSmoothstep(unittest.TestCase):
pass
add_function_test(TestSmoothstep, "test_smoothstep", test_smoothstep, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 4,385 | Python | 25.263473 | 118 | 0.474344 |
NVIDIA/warp/warp/tests/test_linear_solvers.py | import unittest
import numpy as np
import warp as wp
from warp.optim.linear import bicgstab, cg, cr, gmres, preconditioner
from warp.tests.unittest_utils import *
wp.init() # For runtime.core.is_cutlass_enabled()
def _check_linear_solve(test, A, b, func, *args, **kwargs):
# test from zero
x = wp.zeros_like(b)
with wp.ScopedDevice(A.device):
niter, err, atol = func(A, b, x, *args, use_cuda_graph=True, **kwargs)
test.assertLessEqual(err, atol)
# test with warm start
with wp.ScopedDevice(A.device):
niter_warm, err, atol = func(A, b, x, *args, use_cuda_graph=False, **kwargs)
test.assertLessEqual(err, atol)
if func in [cr, gmres]:
# monotonic convergence
test.assertLess(niter_warm, niter)
# In CG and BiCGSTAB residual norm is evaluating from running residual
# rather then being computed from scratch as Ax - b
# This can lead to accumulated inaccuracies over iterations, esp in float32
residual = A.numpy() @ x.numpy() - b.numpy()
err_np = np.linalg.norm(residual)
if A.dtype == wp.float64:
test.assertLessEqual(err_np, 2.0 * atol)
else:
test.assertLessEqual(err_np, 32.0 * atol)
def _least_square_system(rng, n: int):
C = rng.uniform(low=-100, high=100, size=(n, n))
f = rng.uniform(low=-100, high=100, size=(n,))
A = C @ C.T
b = C @ f
return A, b
def _make_spd_system(n: int, seed: int, dtype, device):
rng = np.random.default_rng(seed)
A, b = _least_square_system(rng, n)
return wp.array(A, dtype=dtype, device=device), wp.array(b, dtype=dtype, device=device)
def _make_nonsymmetric_system(n: int, seed: int, dtype, device):
rng = np.random.default_rng(seed)
s = rng.uniform(low=0.1, high=10, size=(n,))
A, b = _least_square_system(rng, n)
A = A @ np.diag(s)
return wp.array(A, dtype=dtype, device=device), wp.array(b, dtype=dtype, device=device)
def _make_indefinite_system(n: int, seed: int, dtype, device):
rng = np.random.default_rng(seed)
s = rng.uniform(low=0.1, high=10, size=(n,))
A, b = _least_square_system(rng, n)
A = A @ np.diag(s)
return wp.array(A, dtype=dtype, device=device), wp.array(b, dtype=dtype, device=device)
def _make_identity_system(n: int, seed: int, dtype, device):
rng = np.random.default_rng(seed)
A = np.eye(n)
b = rng.uniform(low=-1.0, high=1.0, size=(n,))
return wp.array(A, dtype=dtype, device=device), wp.array(b, dtype=dtype, device=device)
def test_cg(test, device):
A, b = _make_spd_system(n=64, seed=123, device=device, dtype=wp.float64)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, cg, maxiter=1000)
_check_linear_solve(test, A, b, cg, M=M, maxiter=1000)
A, b = _make_spd_system(n=16, seed=321, device=device, dtype=wp.float32)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, cg, maxiter=1000)
_check_linear_solve(test, A, b, cg, M=M, maxiter=1000)
A, b = _make_identity_system(n=5, seed=321, device=device, dtype=wp.float32)
_check_linear_solve(test, A, b, cg, maxiter=30)
def test_cr(test, device):
A, b = _make_spd_system(n=64, seed=123, device=device, dtype=wp.float64)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, cr, maxiter=1000)
_check_linear_solve(test, A, b, cr, M=M, maxiter=1000)
A, b = _make_spd_system(n=16, seed=321, device=device, dtype=wp.float32)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, cr, maxiter=1000)
_check_linear_solve(test, A, b, cr, M=M, maxiter=1000)
A, b = _make_identity_system(n=5, seed=321, device=device, dtype=wp.float32)
_check_linear_solve(test, A, b, cr, maxiter=30)
def test_bicgstab(test, device):
A, b = _make_nonsymmetric_system(n=64, seed=123, device=device, dtype=wp.float64)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, bicgstab, maxiter=1000)
_check_linear_solve(test, A, b, bicgstab, M=M, maxiter=1000)
_check_linear_solve(test, A, b, bicgstab, M=M, maxiter=1000, is_left_preconditioner=True)
A, b = _make_nonsymmetric_system(n=16, seed=321, device=device, dtype=wp.float32)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, bicgstab, maxiter=1000)
_check_linear_solve(test, A, b, bicgstab, M=M, maxiter=1000)
_check_linear_solve(test, A, b, bicgstab, M=M, maxiter=1000, is_left_preconditioner=True)
A, b = _make_indefinite_system(n=64, seed=121, device=device, dtype=wp.float64)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, bicgstab, maxiter=1000)
_check_linear_solve(test, A, b, bicgstab, M=M, maxiter=1000)
_check_linear_solve(test, A, b, bicgstab, M=M, maxiter=1000, is_left_preconditioner=True)
A, b = _make_identity_system(n=5, seed=321, device=device, dtype=wp.float32)
_check_linear_solve(test, A, b, bicgstab, maxiter=30)
def test_gmres(test, device):
A, b = _make_nonsymmetric_system(n=64, seed=456, device=device, dtype=wp.float64)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, gmres, maxiter=1000, tol=1.0e-3)
_check_linear_solve(test, A, b, gmres, M=M, maxiter=1000, tol=1.0e-5)
_check_linear_solve(test, A, b, gmres, M=M, maxiter=1000, tol=1.0e-5, is_left_preconditioner=True)
A, b = _make_nonsymmetric_system(n=64, seed=654, device=device, dtype=wp.float64)
M = preconditioner(A, "diag")
_check_linear_solve(test, A, b, gmres, maxiter=1000, tol=1.0e-3)
_check_linear_solve(test, A, b, gmres, M=M, maxiter=1000, tol=1.0e-5)
_check_linear_solve(test, A, b, gmres, M=M, maxiter=1000, tol=1.0e-5, is_left_preconditioner=True)
A, b = _make_identity_system(n=5, seed=123, device=device, dtype=wp.float32)
_check_linear_solve(test, A, b, gmres, maxiter=120)
class TestLinearSolvers(unittest.TestCase):
pass
devices = get_test_devices()
if not wp.context.runtime.core.is_cutlass_enabled():
devices = [d for d in devices if not d.is_cuda]
print("Skipping CUDA linear solver tests because CUTLASS is not supported in this build")
if wp.context.runtime.core.is_debug_enabled():
# cutlass-based matmul is *very* slow in debug mode -- skip
devices = [d for d in devices if not d.is_cuda]
print("Skipping CUDA linear solver tests in debug mode")
add_function_test(TestLinearSolvers, "test_cg", test_cg, devices=devices)
add_function_test(TestLinearSolvers, "test_cr", test_cr, devices=devices)
add_function_test(TestLinearSolvers, "test_bicgstab", test_bicgstab, devices=devices)
add_function_test(TestLinearSolvers, "test_gmres", test_gmres, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 6,759 | Python | 34.578947 | 102 | 0.662968 |
NVIDIA/warp/warp/tests/test_math.py | # Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import unittest
from typing import NamedTuple
import numpy as np
import warp as wp
from warp.tests.unittest_utils import add_function_test, assert_np_equal, get_test_devices
class ScalarFloatValues(NamedTuple):
degrees: wp.float32 = None
radians: wp.float32 = None
@wp.kernel
def scalar_float_kernel(
i: int,
x: wp.array(dtype=wp.float32),
out: wp.array(dtype=wp.float32),
):
if i == 0:
out[0] = wp.degrees(x[0])
elif i == 1:
out[0] = wp.radians(x[0])
def test_scalar_math(test, device):
float_values = ScalarFloatValues(degrees=(0.123,), radians=(123.0,))
float_results_expected = ScalarFloatValues(degrees=7.047381, radians=2.146755)
adj_float_results_expected = ScalarFloatValues(degrees=57.29578, radians=0.017453)
for i, values in enumerate(float_values):
x = wp.array([values[0]], dtype=wp.float32, requires_grad=True, device=device)
out = wp.array([0.0], dtype=wp.float32, requires_grad=True, device=device)
tape = wp.Tape()
with tape:
wp.launch(scalar_float_kernel, dim=1, inputs=[i, x, out], device=device)
assert_np_equal(out.numpy(), np.array([float_results_expected[i]]), tol=1e-6)
tape.backward(out)
assert_np_equal(tape.gradients[x].numpy(), np.array([adj_float_results_expected[i]]), tol=1e-6)
devices = get_test_devices()
class TestMath(unittest.TestCase):
def test_vec_type(self):
vec5 = wp.vec(length=5, dtype=float)
v = vec5()
w = vec5()
a = vec5(1.0)
b = vec5(0.0, 0.0, 0.0, 0.0, 0.0)
c = vec5(0.0)
v[0] = 1.0
v.x = 0.0
v[1:] = [1.0, 1.0, 1.0, 1.0]
w[0] = 1.0
w[1:] = [0.0, 0.0, 0.0, 0.0]
self.assertEqual(v[0], w[1], "vec setter error")
self.assertEqual(v.x, w.y, "vec setter error")
for x in v[1:]:
self.assertEqual(x, 1.0, "vec slicing error")
self.assertEqual(b, c, "vec equality error")
self.assertEqual(str(v), "[0.0, 1.0, 1.0, 1.0, 1.0]", "vec to string error")
def test_mat_type(self):
mat55 = wp.mat(shape=(5, 5), dtype=float)
m1 = mat55()
m2 = mat55()
for i in range(5):
for j in range(5):
if i == j:
m1[i, j] = 1.0
else:
m1[i, j] = 0.0
for i in range(5):
m2[i] = [1.0, 1.0, 1.0, 1.0, 1.0]
a = mat55(1.0)
# fmt: off
b = mat55(
1.0, 0.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0,
)
# fmt: on
self.assertEqual(m1, b, "mat element setting error")
self.assertEqual(m2, a, "mat row setting error")
self.assertEqual(m1[0, 0], 1.0, "mat element getting error")
self.assertEqual(m2[0], [1.0, 1.0, 1.0, 1.0, 1.0], "mat row getting error")
self.assertEqual(
str(b),
"[[1.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 1.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 1.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 1.0]]",
"mat to string error",
)
add_function_test(TestMath, "test_scalar_math", test_scalar_math, devices=devices)
if __name__ == "__main__":
wp.build.clear_kernel_cache()
unittest.main(verbosity=2)
| 3,857 | Python | 29.864 | 158 | 0.562095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.